alibaba.ts 7.4 KB

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