deepseek.ts 6.7 KB

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