alibaba.ts 7.2 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. TranscriptionOptions,
  16. MultimodalContent,
  17. } from "../api";
  18. import Locale from "../../locales";
  19. import {
  20. EventStreamContentType,
  21. fetchEventSource,
  22. } from "@fortaine/fetch-event-source";
  23. import { prettyObject } from "@/app/utils/format";
  24. import { getClientConfig } from "@/app/config/client";
  25. import { getMessageTextContent } from "@/app/utils";
  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. transcription(options: TranscriptionOptions): Promise<string> {
  80. throw new Error("Method not implemented.");
  81. }
  82. async chat(options: ChatOptions) {
  83. const messages = options.messages.map((v) => ({
  84. role: v.role,
  85. content: getMessageTextContent(v),
  86. }));
  87. const modelConfig = {
  88. ...useAppConfig.getState().modelConfig,
  89. ...useChatStore.getState().currentSession().mask.modelConfig,
  90. ...{
  91. model: options.config.model,
  92. },
  93. };
  94. const shouldStream = !!options.config.stream;
  95. const requestPayload: RequestPayload = {
  96. model: modelConfig.model,
  97. input: {
  98. messages,
  99. },
  100. parameters: {
  101. result_format: "message",
  102. incremental_output: shouldStream,
  103. temperature: modelConfig.temperature,
  104. // max_tokens: modelConfig.max_tokens,
  105. top_p: modelConfig.top_p === 1 ? 0.99 : modelConfig.top_p, // qwen top_p is should be < 1
  106. },
  107. };
  108. const controller = new AbortController();
  109. options.onController?.(controller);
  110. try {
  111. const chatPath = this.path(Alibaba.ChatPath);
  112. const chatPayload = {
  113. method: "POST",
  114. body: JSON.stringify(requestPayload),
  115. signal: controller.signal,
  116. headers: {
  117. ...getHeaders(),
  118. "X-DashScope-SSE": shouldStream ? "enable" : "disable",
  119. },
  120. };
  121. // make a fetch request
  122. const requestTimeoutId = setTimeout(
  123. () => controller.abort(),
  124. REQUEST_TIMEOUT_MS,
  125. );
  126. if (shouldStream) {
  127. let responseText = "";
  128. let remainText = "";
  129. let finished = false;
  130. // animate response to make it looks smooth
  131. function animateResponseText() {
  132. if (finished || controller.signal.aborted) {
  133. responseText += remainText;
  134. console.log("[Response Animation] finished");
  135. if (responseText?.length === 0) {
  136. options.onError?.(new Error("empty response from server"));
  137. }
  138. return;
  139. }
  140. if (remainText.length > 0) {
  141. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  142. const fetchText = remainText.slice(0, fetchCount);
  143. responseText += fetchText;
  144. remainText = remainText.slice(fetchCount);
  145. options.onUpdate?.(responseText, fetchText);
  146. }
  147. requestAnimationFrame(animateResponseText);
  148. }
  149. // start animaion
  150. animateResponseText();
  151. const finish = () => {
  152. if (!finished) {
  153. finished = true;
  154. options.onFinish(responseText + remainText);
  155. }
  156. };
  157. controller.signal.onabort = finish;
  158. fetchEventSource(chatPath, {
  159. ...chatPayload,
  160. async onopen(res) {
  161. clearTimeout(requestTimeoutId);
  162. const contentType = res.headers.get("content-type");
  163. console.log(
  164. "[Alibaba] request response content type: ",
  165. contentType,
  166. );
  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);
  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 };