alibaba.ts 6.9 KB

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