alibaba.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. SpeechOptions,
  15. MultimodalContent,
  16. } from "../api";
  17. import Locale from "../../locales";
  18. import {
  19. EventStreamContentType,
  20. fetchEventSource,
  21. } from "@fortaine/fetch-event-source";
  22. import { prettyObject } from "@/app/utils/format";
  23. import { getClientConfig } from "@/app/config/client";
  24. import { getMessageTextContent } 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: getMessageTextContent(v),
  83. }));
  84. const modelConfig = {
  85. ...useAppConfig.getState().modelConfig,
  86. ...useChatStore.getState().currentSession().mask.modelConfig,
  87. ...{
  88. model: options.config.model,
  89. },
  90. };
  91. const shouldStream = !!options.config.stream;
  92. const requestPayload: RequestPayload = {
  93. model: modelConfig.model,
  94. input: {
  95. messages,
  96. },
  97. parameters: {
  98. result_format: "message",
  99. incremental_output: shouldStream,
  100. temperature: modelConfig.temperature,
  101. // max_tokens: modelConfig.max_tokens,
  102. top_p: modelConfig.top_p === 1 ? 0.99 : modelConfig.top_p, // qwen top_p is should be < 1
  103. },
  104. };
  105. const controller = new AbortController();
  106. options.onController?.(controller);
  107. try {
  108. const chatPath = this.path(Alibaba.ChatPath);
  109. const chatPayload = {
  110. method: "POST",
  111. body: JSON.stringify(requestPayload),
  112. signal: controller.signal,
  113. headers: {
  114. ...getHeaders(),
  115. "X-DashScope-SSE": shouldStream ? "enable" : "disable",
  116. },
  117. };
  118. // make a fetch request
  119. const requestTimeoutId = setTimeout(
  120. () => controller.abort(),
  121. REQUEST_TIMEOUT_MS,
  122. );
  123. if (shouldStream) {
  124. let responseText = "";
  125. let remainText = "";
  126. let finished = false;
  127. let responseRes: Response;
  128. // animate response to make it looks smooth
  129. function animateResponseText() {
  130. if (finished || controller.signal.aborted) {
  131. responseText += remainText;
  132. console.log("[Response Animation] finished");
  133. if (responseText?.length === 0) {
  134. options.onError?.(new Error("empty response from server"));
  135. }
  136. return;
  137. }
  138. if (remainText.length > 0) {
  139. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  140. const fetchText = remainText.slice(0, fetchCount);
  141. responseText += fetchText;
  142. remainText = remainText.slice(fetchCount);
  143. options.onUpdate?.(responseText, fetchText);
  144. }
  145. requestAnimationFrame(animateResponseText);
  146. }
  147. // start animaion
  148. animateResponseText();
  149. const finish = () => {
  150. if (!finished) {
  151. finished = true;
  152. options.onFinish(responseText + remainText, responseRes);
  153. }
  154. };
  155. controller.signal.onabort = finish;
  156. fetchEventSource(chatPath, {
  157. fetch: fetch as any,
  158. ...chatPayload,
  159. async onopen(res) {
  160. clearTimeout(requestTimeoutId);
  161. const contentType = res.headers.get("content-type");
  162. console.log(
  163. "[Alibaba] request response content type: ",
  164. contentType,
  165. );
  166. responseRes = res;
  167. if (contentType?.startsWith("text/plain")) {
  168. responseText = await res.clone().text();
  169. return finish();
  170. }
  171. if (
  172. !res.ok ||
  173. !res.headers
  174. .get("content-type")
  175. ?.startsWith(EventStreamContentType) ||
  176. res.status !== 200
  177. ) {
  178. const responseTexts = [responseText];
  179. let extraInfo = await res.clone().text();
  180. try {
  181. const resJson = await res.clone().json();
  182. extraInfo = prettyObject(resJson);
  183. } catch {}
  184. if (res.status === 401) {
  185. responseTexts.push(Locale.Error.Unauthorized);
  186. }
  187. if (extraInfo) {
  188. responseTexts.push(extraInfo);
  189. }
  190. responseText = responseTexts.join("\n\n");
  191. return finish();
  192. }
  193. },
  194. onmessage(msg) {
  195. if (msg.data === "[DONE]" || finished) {
  196. return finish();
  197. }
  198. const text = msg.data;
  199. try {
  200. const json = JSON.parse(text);
  201. const choices = json.output.choices as Array<{
  202. message: { content: string };
  203. }>;
  204. const delta = choices[0]?.message?.content;
  205. if (delta) {
  206. remainText += delta;
  207. }
  208. } catch (e) {
  209. console.error("[Request] parse error", text, msg);
  210. }
  211. },
  212. onclose() {
  213. finish();
  214. },
  215. onerror(e) {
  216. options.onError?.(e);
  217. throw e;
  218. },
  219. openWhenHidden: true,
  220. });
  221. } else {
  222. const res = await fetch(chatPath, chatPayload);
  223. clearTimeout(requestTimeoutId);
  224. const resJson = await res.json();
  225. const message = this.extractMessage(resJson);
  226. options.onFinish(message, res);
  227. }
  228. } catch (e) {
  229. console.log("[Request] failed to make a chat request", e);
  230. options.onError?.(e as Error);
  231. }
  232. }
  233. async usage() {
  234. return {
  235. used: 0,
  236. total: 0,
  237. };
  238. }
  239. async models(): Promise<LLMModel[]> {
  240. return [];
  241. }
  242. }
  243. export { Alibaba };