alibaba.ts 7.0 KB

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