|
@@ -1,11 +1,12 @@
|
|
|
"use client";
|
|
"use client";
|
|
|
|
|
+import { ApiPath, ByteDance, BYTEDANCE_BASE_URL } from "@/app/constant";
|
|
|
import {
|
|
import {
|
|
|
- ApiPath,
|
|
|
|
|
- ByteDance,
|
|
|
|
|
- BYTEDANCE_BASE_URL,
|
|
|
|
|
- REQUEST_TIMEOUT_MS,
|
|
|
|
|
-} from "@/app/constant";
|
|
|
|
|
-import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
|
|
|
|
|
|
|
+ useAccessStore,
|
|
|
|
|
+ useAppConfig,
|
|
|
|
|
+ useChatStore,
|
|
|
|
|
+ ChatMessageTool,
|
|
|
|
|
+ usePluginStore,
|
|
|
|
|
+} from "@/app/store";
|
|
|
|
|
|
|
|
import {
|
|
import {
|
|
|
ChatOptions,
|
|
ChatOptions,
|
|
@@ -15,14 +16,14 @@ import {
|
|
|
MultimodalContent,
|
|
MultimodalContent,
|
|
|
SpeechOptions,
|
|
SpeechOptions,
|
|
|
} from "../api";
|
|
} from "../api";
|
|
|
-import Locale from "../../locales";
|
|
|
|
|
-import {
|
|
|
|
|
- EventStreamContentType,
|
|
|
|
|
- fetchEventSource,
|
|
|
|
|
-} from "@fortaine/fetch-event-source";
|
|
|
|
|
-import { prettyObject } from "@/app/utils/format";
|
|
|
|
|
|
|
+
|
|
|
|
|
+import { streamWithThink } from "@/app/utils/chat";
|
|
|
import { getClientConfig } from "@/app/config/client";
|
|
import { getClientConfig } from "@/app/config/client";
|
|
|
import { preProcessImageContent } from "@/app/utils/chat";
|
|
import { preProcessImageContent } from "@/app/utils/chat";
|
|
|
|
|
+import {
|
|
|
|
|
+ getMessageTextContentWithoutThinking,
|
|
|
|
|
+ getTimeoutMSByModel,
|
|
|
|
|
+} from "@/app/utils";
|
|
|
import { fetch } from "@/app/utils/stream";
|
|
import { fetch } from "@/app/utils/stream";
|
|
|
|
|
|
|
|
export interface OpenAIListModelResponse {
|
|
export interface OpenAIListModelResponse {
|
|
@@ -34,7 +35,7 @@ export interface OpenAIListModelResponse {
|
|
|
}>;
|
|
}>;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-interface RequestPayload {
|
|
|
|
|
|
|
+interface RequestPayloadForByteDance {
|
|
|
messages: {
|
|
messages: {
|
|
|
role: "system" | "user" | "assistant";
|
|
role: "system" | "user" | "assistant";
|
|
|
content: string | MultimodalContent[];
|
|
content: string | MultimodalContent[];
|
|
@@ -86,7 +87,10 @@ export class DoubaoApi implements LLMApi {
|
|
|
async chat(options: ChatOptions) {
|
|
async chat(options: ChatOptions) {
|
|
|
const messages: ChatOptions["messages"] = [];
|
|
const messages: ChatOptions["messages"] = [];
|
|
|
for (const v of options.messages) {
|
|
for (const v of options.messages) {
|
|
|
- const content = await preProcessImageContent(v.content);
|
|
|
|
|
|
|
+ const content =
|
|
|
|
|
+ v.role === "assistant"
|
|
|
|
|
+ ? getMessageTextContentWithoutThinking(v)
|
|
|
|
|
+ : await preProcessImageContent(v.content);
|
|
|
messages.push({ role: v.role, content });
|
|
messages.push({ role: v.role, content });
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -99,7 +103,7 @@ export class DoubaoApi implements LLMApi {
|
|
|
};
|
|
};
|
|
|
|
|
|
|
|
const shouldStream = !!options.config.stream;
|
|
const shouldStream = !!options.config.stream;
|
|
|
- const requestPayload: RequestPayload = {
|
|
|
|
|
|
|
+ const requestPayload: RequestPayloadForByteDance = {
|
|
|
messages,
|
|
messages,
|
|
|
stream: shouldStream,
|
|
stream: shouldStream,
|
|
|
model: modelConfig.model,
|
|
model: modelConfig.model,
|
|
@@ -124,119 +128,101 @@ export class DoubaoApi implements LLMApi {
|
|
|
// make a fetch request
|
|
// make a fetch request
|
|
|
const requestTimeoutId = setTimeout(
|
|
const requestTimeoutId = setTimeout(
|
|
|
() => controller.abort(),
|
|
() => controller.abort(),
|
|
|
- REQUEST_TIMEOUT_MS,
|
|
|
|
|
|
|
+ getTimeoutMSByModel(options.config.model),
|
|
|
);
|
|
);
|
|
|
|
|
|
|
|
if (shouldStream) {
|
|
if (shouldStream) {
|
|
|
- let responseText = "";
|
|
|
|
|
- let remainText = "";
|
|
|
|
|
- let finished = false;
|
|
|
|
|
- let responseRes: Response;
|
|
|
|
|
-
|
|
|
|
|
- // animate response to make it looks smooth
|
|
|
|
|
- function animateResponseText() {
|
|
|
|
|
- if (finished || controller.signal.aborted) {
|
|
|
|
|
- responseText += remainText;
|
|
|
|
|
- console.log("[Response Animation] finished");
|
|
|
|
|
- if (responseText?.length === 0) {
|
|
|
|
|
- options.onError?.(new Error("empty response from server"));
|
|
|
|
|
- }
|
|
|
|
|
- return;
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- if (remainText.length > 0) {
|
|
|
|
|
- const fetchCount = Math.max(1, Math.round(remainText.length / 60));
|
|
|
|
|
- const fetchText = remainText.slice(0, fetchCount);
|
|
|
|
|
- responseText += fetchText;
|
|
|
|
|
- remainText = remainText.slice(fetchCount);
|
|
|
|
|
- options.onUpdate?.(responseText, fetchText);
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- requestAnimationFrame(animateResponseText);
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- // start animaion
|
|
|
|
|
- animateResponseText();
|
|
|
|
|
-
|
|
|
|
|
- const finish = () => {
|
|
|
|
|
- if (!finished) {
|
|
|
|
|
- finished = true;
|
|
|
|
|
- options.onFinish(responseText + remainText, responseRes);
|
|
|
|
|
- }
|
|
|
|
|
- };
|
|
|
|
|
-
|
|
|
|
|
- controller.signal.onabort = finish;
|
|
|
|
|
-
|
|
|
|
|
- fetchEventSource(chatPath, {
|
|
|
|
|
- fetch: fetch as any,
|
|
|
|
|
- ...chatPayload,
|
|
|
|
|
- async onopen(res) {
|
|
|
|
|
- clearTimeout(requestTimeoutId);
|
|
|
|
|
- const contentType = res.headers.get("content-type");
|
|
|
|
|
- console.log(
|
|
|
|
|
- "[ByteDance] request response content type: ",
|
|
|
|
|
- contentType,
|
|
|
|
|
- );
|
|
|
|
|
- responseRes = res;
|
|
|
|
|
- if (contentType?.startsWith("text/plain")) {
|
|
|
|
|
- responseText = await res.clone().text();
|
|
|
|
|
- return finish();
|
|
|
|
|
|
|
+ const [tools, funcs] = usePluginStore
|
|
|
|
|
+ .getState()
|
|
|
|
|
+ .getAsTools(
|
|
|
|
|
+ useChatStore.getState().currentSession().mask?.plugin || [],
|
|
|
|
|
+ );
|
|
|
|
|
+ return streamWithThink(
|
|
|
|
|
+ chatPath,
|
|
|
|
|
+ requestPayload,
|
|
|
|
|
+ getHeaders(),
|
|
|
|
|
+ tools as any,
|
|
|
|
|
+ funcs,
|
|
|
|
|
+ controller,
|
|
|
|
|
+ // parseSSE
|
|
|
|
|
+ (text: string, runTools: ChatMessageTool[]) => {
|
|
|
|
|
+ // console.log("parseSSE", text, runTools);
|
|
|
|
|
+ const json = JSON.parse(text);
|
|
|
|
|
+ const choices = json.choices as Array<{
|
|
|
|
|
+ delta: {
|
|
|
|
|
+ content: string | null;
|
|
|
|
|
+ tool_calls: ChatMessageTool[];
|
|
|
|
|
+ reasoning_content: string | null;
|
|
|
|
|
+ };
|
|
|
|
|
+ }>;
|
|
|
|
|
+
|
|
|
|
|
+ if (!choices?.length) return { isThinking: false, content: "" };
|
|
|
|
|
+
|
|
|
|
|
+ const tool_calls = choices[0]?.delta?.tool_calls;
|
|
|
|
|
+ if (tool_calls?.length > 0) {
|
|
|
|
|
+ const index = tool_calls[0]?.index;
|
|
|
|
|
+ const id = tool_calls[0]?.id;
|
|
|
|
|
+ const args = tool_calls[0]?.function?.arguments;
|
|
|
|
|
+ if (id) {
|
|
|
|
|
+ runTools.push({
|
|
|
|
|
+ id,
|
|
|
|
|
+ type: tool_calls[0]?.type,
|
|
|
|
|
+ function: {
|
|
|
|
|
+ name: tool_calls[0]?.function?.name as string,
|
|
|
|
|
+ arguments: args,
|
|
|
|
|
+ },
|
|
|
|
|
+ });
|
|
|
|
|
+ } else {
|
|
|
|
|
+ // @ts-ignore
|
|
|
|
|
+ runTools[index]["function"]["arguments"] += args;
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
+ const reasoning = choices[0]?.delta?.reasoning_content;
|
|
|
|
|
+ const content = choices[0]?.delta?.content;
|
|
|
|
|
|
|
|
|
|
+ // Skip if both content and reasoning_content are empty or null
|
|
|
if (
|
|
if (
|
|
|
- !res.ok ||
|
|
|
|
|
- !res.headers
|
|
|
|
|
- .get("content-type")
|
|
|
|
|
- ?.startsWith(EventStreamContentType) ||
|
|
|
|
|
- res.status !== 200
|
|
|
|
|
|
|
+ (!reasoning || reasoning.length === 0) &&
|
|
|
|
|
+ (!content || content.length === 0)
|
|
|
) {
|
|
) {
|
|
|
- const responseTexts = [responseText];
|
|
|
|
|
- let extraInfo = await res.clone().text();
|
|
|
|
|
- try {
|
|
|
|
|
- const resJson = await res.clone().json();
|
|
|
|
|
- extraInfo = prettyObject(resJson);
|
|
|
|
|
- } catch {}
|
|
|
|
|
-
|
|
|
|
|
- if (res.status === 401) {
|
|
|
|
|
- responseTexts.push(Locale.Error.Unauthorized);
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- if (extraInfo) {
|
|
|
|
|
- responseTexts.push(extraInfo);
|
|
|
|
|
- }
|
|
|
|
|
-
|
|
|
|
|
- responseText = responseTexts.join("\n\n");
|
|
|
|
|
-
|
|
|
|
|
- return finish();
|
|
|
|
|
|
|
+ return {
|
|
|
|
|
+ isThinking: false,
|
|
|
|
|
+ content: "",
|
|
|
|
|
+ };
|
|
|
}
|
|
}
|
|
|
- },
|
|
|
|
|
- onmessage(msg) {
|
|
|
|
|
- if (msg.data === "[DONE]" || finished) {
|
|
|
|
|
- return finish();
|
|
|
|
|
- }
|
|
|
|
|
- const text = msg.data;
|
|
|
|
|
- try {
|
|
|
|
|
- const json = JSON.parse(text);
|
|
|
|
|
- const choices = json.choices as Array<{
|
|
|
|
|
- delta: { content: string };
|
|
|
|
|
- }>;
|
|
|
|
|
- const delta = choices[0]?.delta?.content;
|
|
|
|
|
- if (delta) {
|
|
|
|
|
- remainText += delta;
|
|
|
|
|
- }
|
|
|
|
|
- } catch (e) {
|
|
|
|
|
- console.error("[Request] parse error", text, msg);
|
|
|
|
|
|
|
+
|
|
|
|
|
+ if (reasoning && reasoning.length > 0) {
|
|
|
|
|
+ return {
|
|
|
|
|
+ isThinking: true,
|
|
|
|
|
+ content: reasoning,
|
|
|
|
|
+ };
|
|
|
|
|
+ } else if (content && content.length > 0) {
|
|
|
|
|
+ return {
|
|
|
|
|
+ isThinking: false,
|
|
|
|
|
+ content: content,
|
|
|
|
|
+ };
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+ return {
|
|
|
|
|
+ isThinking: false,
|
|
|
|
|
+ content: "",
|
|
|
|
|
+ };
|
|
|
},
|
|
},
|
|
|
- onclose() {
|
|
|
|
|
- finish();
|
|
|
|
|
- },
|
|
|
|
|
- onerror(e) {
|
|
|
|
|
- options.onError?.(e);
|
|
|
|
|
- throw e;
|
|
|
|
|
|
|
+ // processToolMessage, include tool_calls message and tool call results
|
|
|
|
|
+ (
|
|
|
|
|
+ requestPayload: RequestPayloadForByteDance,
|
|
|
|
|
+ toolCallMessage: any,
|
|
|
|
|
+ toolCallResult: any[],
|
|
|
|
|
+ ) => {
|
|
|
|
|
+ requestPayload?.messages?.splice(
|
|
|
|
|
+ requestPayload?.messages?.length,
|
|
|
|
|
+ 0,
|
|
|
|
|
+ toolCallMessage,
|
|
|
|
|
+ ...toolCallResult,
|
|
|
|
|
+ );
|
|
|
},
|
|
},
|
|
|
- openWhenHidden: true,
|
|
|
|
|
- });
|
|
|
|
|
|
|
+ options,
|
|
|
|
|
+ );
|
|
|
} else {
|
|
} else {
|
|
|
const res = await fetch(chatPath, chatPayload);
|
|
const res = await fetch(chatPath, chatPayload);
|
|
|
clearTimeout(requestTimeoutId);
|
|
clearTimeout(requestTimeoutId);
|