siliconflow.ts 7.7 KB

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