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

87 lines
2.3 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-24 15:41:33 +08:00
import type { MCPServerMetadata } from "../mcp";
2025-04-17 12:02:23 +08:00
import { fetchStream } from "../sse";
import { sleep } from "../utils";
2025-04-24 15:41:33 +08:00
import { resolveServiceURL } from "./resolve-service-url";
2025-04-17 12:02:23 +08:00
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;
2025-04-24 15:41:33 +08:00
mcp_settings?: {
servers: Record<
string,
MCPServerMetadata & {
enabled_tools: string[];
add_to_agents: string[];
}
>;
};
2025-04-17 12:02:23 +08:00
},
options: { abortSignal?: AbortSignal } = {},
) {
if (location.search.includes("mock")) {
return chatStreamMock(userMessage, params, options);
}
2025-04-24 15:41:33 +08:00
return fetchStream<ChatEvent>(resolveServiceURL("chat/stream"), {
body: JSON.stringify({
messages: [{ role: "user", content: userMessage }],
auto_accepted_plan: false,
...params,
}),
signal: options.abortSignal,
});
2025-04-17 12:02:23 +08:00
}
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,
});
2025-04-22 11:03:53 +08:00
await sleep(500);
2025-04-17 12:02:23 +08:00
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-20 11:18:05 +08:00
await sleep(100);
2025-04-17 12:02:23 +08:00
} else if (event === "tool_call_result") {
2025-04-22 11:03:53 +08:00
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);
}
}
}