bytedance.ts 6.7 KB

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