alibaba.ts 7.1 KB

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