alibaba.ts 6.9 KB

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