Files
deer-flow/web/src/core/api/chat.ts

81 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-04-17 14:26:41 +08:00
// Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
// SPDX-License-Identifier: MIT
2025-04-17 12:02:23 +08:00
import { env } from "~/env";
import { fetchStream } from "../sse";
import { sleep } from "../utils";
import type { ChatEvent } from "./types";
export function chatStream(
userMessage: string,
params: {
thread_id: string;
max_plan_iterations: number;
max_step_num: number;
interrupt_feedback?: string;
},
options: { abortSignal?: AbortSignal } = {},
) {
if (location.search.includes("mock")) {
return chatStreamMock(userMessage, params, options);
}
return fetchStream<ChatEvent>(
2025-04-17 16:39:27 +08:00
(env.NEXT_PUBLIC_API_URL ?? "/api") + "/chat/stream",
2025-04-17 12:02:23 +08:00
{
body: JSON.stringify({
messages: [{ role: "user", content: userMessage }],
auto_accepted_plan: false,
...params,
}),
signal: options.abortSignal,
},
);
}
async function* chatStreamMock(
userMessage: string,
2025-04-19 11:03:33 +08:00
params: {
2025-04-17 12:02:23 +08:00
thread_id: string;
max_plan_iterations: number;
max_step_num: number;
2025-04-19 11:03:33 +08:00
interrupt_feedback?: string;
2025-04-17 12:02:23 +08:00
} = {
thread_id: "__mock__",
max_plan_iterations: 3,
max_step_num: 1,
2025-04-19 11:03:33 +08:00
interrupt_feedback: undefined,
2025-04-17 12:02:23 +08:00
},
options: { abortSignal?: AbortSignal } = {},
): AsyncIterable<ChatEvent> {
2025-04-19 11:03:33 +08:00
const mockFile =
params.interrupt_feedback === "accepted"
? "/mock-before-interrupt.txt"
: "/mock-after-interrupt.txt";
const res = await fetch(mockFile, {
2025-04-17 12:02:23 +08:00
signal: options.abortSignal,
});
await sleep(800);
const text = await res.text();
const chunks = text.split("\n\n");
for (const chunk of chunks) {
const [eventRaw, dataRaw] = chunk.split("\n") as [string, string];
const [, event] = eventRaw.split("event: ", 2) as [string, string];
const [, data] = dataRaw.split("data: ", 2) as [string, string];
if (event === "message_chunk") {
2025-04-19 11:03:33 +08:00
await sleep(100);
2025-04-17 12:02:23 +08:00
} else if (event === "tool_call_result") {
await sleep(2000);
2025-04-17 12:02:23 +08:00
}
try {
yield {
type: event,
data: JSON.parse(data),
} as ChatEvent;
} catch (e) {
console.error(e);
}
}
}