deepseek.ts 6.7 KB

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