bytedance.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. "use client";
  2. import {
  3. ApiPath,
  4. ByteDance,
  5. BYTEDANCE_BASE_URL,
  6. REQUEST_TIMEOUT_MS,
  7. } from "@/app/constant";
  8. import {
  9. useAccessStore,
  10. useAppConfig,
  11. useChatStore,
  12. ChatMessageTool,
  13. usePluginStore,
  14. } from "@/app/store";
  15. import {
  16. ChatOptions,
  17. getHeaders,
  18. LLMApi,
  19. LLMModel,
  20. MultimodalContent,
  21. SpeechOptions,
  22. } from "../api";
  23. import { streamWithThink } from "@/app/utils/chat";
  24. import { getClientConfig } from "@/app/config/client";
  25. import { preProcessImageContent } from "@/app/utils/chat";
  26. import { getMessageTextContentWithoutThinking } from "@/app/utils";
  27. import { fetch } from "@/app/utils/stream";
  28. export interface OpenAIListModelResponse {
  29. object: string;
  30. data: Array<{
  31. id: string;
  32. object: string;
  33. root: string;
  34. }>;
  35. }
  36. interface RequestPayloadForByteDance {
  37. messages: {
  38. role: "system" | "user" | "assistant";
  39. content: string | MultimodalContent[];
  40. }[];
  41. stream?: boolean;
  42. model: string;
  43. temperature: number;
  44. presence_penalty: number;
  45. frequency_penalty: number;
  46. top_p: number;
  47. max_tokens?: number;
  48. }
  49. export class DoubaoApi implements LLMApi {
  50. path(path: string): string {
  51. const accessStore = useAccessStore.getState();
  52. let baseUrl = "";
  53. if (accessStore.useCustomConfig) {
  54. baseUrl = accessStore.bytedanceUrl;
  55. }
  56. if (baseUrl.length === 0) {
  57. const isApp = !!getClientConfig()?.isApp;
  58. baseUrl = isApp ? BYTEDANCE_BASE_URL : ApiPath.ByteDance;
  59. }
  60. if (baseUrl.endsWith("/")) {
  61. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  62. }
  63. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.ByteDance)) {
  64. baseUrl = "https://" + baseUrl;
  65. }
  66. console.log("[Proxy Endpoint] ", baseUrl, path);
  67. return [baseUrl, path].join("/");
  68. }
  69. extractMessage(res: any) {
  70. return res.choices?.at(0)?.message?.content ?? "";
  71. }
  72. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  73. throw new Error("Method not implemented.");
  74. }
  75. async chat(options: ChatOptions) {
  76. const messages: ChatOptions["messages"] = [];
  77. for (const v of options.messages) {
  78. const content =
  79. v.role === "assistant"
  80. ? getMessageTextContentWithoutThinking(v)
  81. : await preProcessImageContent(v.content);
  82. messages.push({ role: v.role, content });
  83. }
  84. const modelConfig = {
  85. ...useAppConfig.getState().modelConfig,
  86. ...useChatStore.getState().currentSession().mask.modelConfig,
  87. ...{
  88. model: options.config.model,
  89. },
  90. };
  91. const shouldStream = !!options.config.stream;
  92. const requestPayload: RequestPayloadForByteDance = {
  93. messages,
  94. stream: shouldStream,
  95. model: modelConfig.model,
  96. temperature: modelConfig.temperature,
  97. presence_penalty: modelConfig.presence_penalty,
  98. frequency_penalty: modelConfig.frequency_penalty,
  99. top_p: modelConfig.top_p,
  100. };
  101. const controller = new AbortController();
  102. options.onController?.(controller);
  103. try {
  104. const chatPath = this.path(ByteDance.ChatPath);
  105. const chatPayload = {
  106. method: "POST",
  107. body: JSON.stringify(requestPayload),
  108. signal: controller.signal,
  109. headers: getHeaders(),
  110. };
  111. // make a fetch request
  112. const requestTimeoutId = setTimeout(
  113. () => controller.abort(),
  114. REQUEST_TIMEOUT_MS,
  115. );
  116. if (shouldStream) {
  117. const [tools, funcs] = usePluginStore
  118. .getState()
  119. .getAsTools(
  120. useChatStore.getState().currentSession().mask?.plugin || [],
  121. );
  122. return streamWithThink(
  123. chatPath,
  124. requestPayload,
  125. getHeaders(),
  126. tools as any,
  127. funcs,
  128. controller,
  129. // parseSSE
  130. (text: string, runTools: ChatMessageTool[]) => {
  131. // console.log("parseSSE", text, runTools);
  132. const json = JSON.parse(text);
  133. const choices = json.choices as Array<{
  134. delta: {
  135. content: string | null;
  136. tool_calls: ChatMessageTool[];
  137. reasoning_content: string | null;
  138. };
  139. }>;
  140. if (!choices?.length) return { isThinking: false, content: "" };
  141. const tool_calls = choices[0]?.delta?.tool_calls;
  142. if (tool_calls?.length > 0) {
  143. const index = tool_calls[0]?.index;
  144. const id = tool_calls[0]?.id;
  145. const args = tool_calls[0]?.function?.arguments;
  146. if (id) {
  147. runTools.push({
  148. id,
  149. type: tool_calls[0]?.type,
  150. function: {
  151. name: tool_calls[0]?.function?.name as string,
  152. arguments: args,
  153. },
  154. });
  155. } else {
  156. // @ts-ignore
  157. runTools[index]["function"]["arguments"] += args;
  158. }
  159. }
  160. const reasoning = choices[0]?.delta?.reasoning_content;
  161. const content = choices[0]?.delta?.content;
  162. // Skip if both content and reasoning_content are empty or null
  163. if (
  164. (!reasoning || reasoning.trim().length === 0) &&
  165. (!content || content.trim().length === 0)
  166. ) {
  167. return {
  168. isThinking: false,
  169. content: "",
  170. };
  171. }
  172. if (reasoning && reasoning.trim().length > 0) {
  173. return {
  174. isThinking: true,
  175. content: reasoning,
  176. };
  177. } else if (content && content.trim().length > 0) {
  178. return {
  179. isThinking: false,
  180. content: content,
  181. };
  182. }
  183. return {
  184. isThinking: false,
  185. content: "",
  186. };
  187. },
  188. // processToolMessage, include tool_calls message and tool call results
  189. (
  190. requestPayload: RequestPayloadForByteDance,
  191. toolCallMessage: any,
  192. toolCallResult: any[],
  193. ) => {
  194. requestPayload?.messages?.splice(
  195. requestPayload?.messages?.length,
  196. 0,
  197. toolCallMessage,
  198. ...toolCallResult,
  199. );
  200. },
  201. options,
  202. );
  203. } else {
  204. const res = await fetch(chatPath, chatPayload);
  205. clearTimeout(requestTimeoutId);
  206. const resJson = await res.json();
  207. const message = this.extractMessage(resJson);
  208. options.onFinish(message, res);
  209. }
  210. } catch (e) {
  211. console.log("[Request] failed to make a chat request", e);
  212. options.onError?.(e as Error);
  213. }
  214. }
  215. async usage() {
  216. return {
  217. used: 0,
  218. total: 0,
  219. };
  220. }
  221. async models(): Promise<LLMModel[]> {
  222. return [];
  223. }
  224. }
  225. export { ByteDance };