alibaba.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 } 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. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  75. throw new Error("Method not implemented.");
  76. }
  77. transcription(options: TranscriptionOptions): Promise<string> {
  78. throw new Error("Method not implemented.");
  79. }
  80. async chat(options: ChatOptions) {
  81. const messages = options.messages.map((v) => ({
  82. role: v.role,
  83. content: getMessageTextContent(v),
  84. }));
  85. const modelConfig = {
  86. ...useAppConfig.getState().modelConfig,
  87. ...useChatStore.getState().currentSession().mask.modelConfig,
  88. ...{
  89. model: options.config.model,
  90. },
  91. };
  92. const shouldStream = !!options.config.stream;
  93. const requestPayload: RequestPayload = {
  94. model: modelConfig.model,
  95. input: {
  96. messages,
  97. },
  98. parameters: {
  99. result_format: "message",
  100. incremental_output: shouldStream,
  101. temperature: modelConfig.temperature,
  102. // max_tokens: modelConfig.max_tokens,
  103. top_p: modelConfig.top_p === 1 ? 0.99 : modelConfig.top_p, // qwen top_p is should be < 1
  104. },
  105. };
  106. const controller = new AbortController();
  107. options.onController?.(controller);
  108. try {
  109. const chatPath = this.path(Alibaba.ChatPath);
  110. const chatPayload = {
  111. method: "POST",
  112. body: JSON.stringify(requestPayload),
  113. signal: controller.signal,
  114. headers: {
  115. ...getHeaders(),
  116. "X-DashScope-SSE": shouldStream ? "enable" : "disable",
  117. },
  118. };
  119. // make a fetch request
  120. const requestTimeoutId = setTimeout(
  121. () => controller.abort(),
  122. REQUEST_TIMEOUT_MS,
  123. );
  124. if (shouldStream) {
  125. let responseText = "";
  126. let remainText = "";
  127. let finished = false;
  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);
  153. }
  154. };
  155. controller.signal.onabort = finish;
  156. fetchEventSource(chatPath, {
  157. ...chatPayload,
  158. async onopen(res) {
  159. clearTimeout(requestTimeoutId);
  160. const contentType = res.headers.get("content-type");
  161. console.log(
  162. "[Alibaba] request response content type: ",
  163. contentType,
  164. );
  165. if (contentType?.startsWith("text/plain")) {
  166. responseText = await res.clone().text();
  167. return finish();
  168. }
  169. if (
  170. !res.ok ||
  171. !res.headers
  172. .get("content-type")
  173. ?.startsWith(EventStreamContentType) ||
  174. res.status !== 200
  175. ) {
  176. const responseTexts = [responseText];
  177. let extraInfo = await res.clone().text();
  178. try {
  179. const resJson = await res.clone().json();
  180. extraInfo = prettyObject(resJson);
  181. } catch {}
  182. if (res.status === 401) {
  183. responseTexts.push(Locale.Error.Unauthorized);
  184. }
  185. if (extraInfo) {
  186. responseTexts.push(extraInfo);
  187. }
  188. responseText = responseTexts.join("\n\n");
  189. return finish();
  190. }
  191. },
  192. onmessage(msg) {
  193. if (msg.data === "[DONE]" || finished) {
  194. return finish();
  195. }
  196. const text = msg.data;
  197. try {
  198. const json = JSON.parse(text);
  199. const choices = json.output.choices as Array<{
  200. message: { content: string };
  201. }>;
  202. const delta = choices[0]?.message?.content;
  203. if (delta) {
  204. remainText += delta;
  205. }
  206. } catch (e) {
  207. console.error("[Request] parse error", text, msg);
  208. }
  209. },
  210. onclose() {
  211. finish();
  212. },
  213. onerror(e) {
  214. options.onError?.(e);
  215. throw e;
  216. },
  217. openWhenHidden: true,
  218. });
  219. } else {
  220. const res = await fetch(chatPath, chatPayload);
  221. clearTimeout(requestTimeoutId);
  222. const resJson = await res.json();
  223. const message = this.extractMessage(resJson);
  224. options.onFinish(message);
  225. }
  226. } catch (e) {
  227. console.log("[Request] failed to make a chat request", e);
  228. options.onError?.(e as Error);
  229. }
  230. }
  231. async usage() {
  232. return {
  233. used: 0,
  234. total: 0,
  235. };
  236. }
  237. async models(): Promise<LLMModel[]> {
  238. return [];
  239. }
  240. }
  241. export { Alibaba };