alibaba.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. // 预处理图片内容,将base64转换为阿里云API格式
  25. async function preProcessImageContent(content: string | MultimodalContent[]) {
  26. if (typeof content === "string") {
  27. return content;
  28. }
  29. const processedContent: any[] = [];
  30. for (const item of content) {
  31. if (item.type === "text") {
  32. processedContent.push({
  33. text: item.text
  34. });
  35. } else if (item.type === "image_url") {
  36. // 阿里云API支持URL和base64格式的图片
  37. let imageData = item.image_url?.url || "";
  38. if (imageData.startsWith("data:image/")) {
  39. // 提取base64部分
  40. const base64Match = imageData.match(/data:image\/[^;]+;base64,(.+)/);
  41. if (base64Match) {
  42. imageData = base64Match[1];
  43. }
  44. processedContent.push({
  45. image: imageData
  46. });
  47. } else if (imageData.startsWith("http")) {
  48. // 直接使用URL
  49. processedContent.push({
  50. image: imageData
  51. });
  52. } else {
  53. // 假设是纯base64
  54. processedContent.push({
  55. image: imageData
  56. });
  57. }
  58. }
  59. }
  60. return processedContent;
  61. }
  62. export interface OpenAIListModelResponse {
  63. object: string;
  64. data: Array<{
  65. id: string;
  66. object: string;
  67. root: string;
  68. }>;
  69. }
  70. interface RequestInput {
  71. messages: {
  72. role: "system" | "user" | "assistant";
  73. content: string | MultimodalContent[];
  74. }[];
  75. }
  76. interface RequestParam {
  77. result_format: string;
  78. incremental_output?: boolean;
  79. temperature: number;
  80. repetition_penalty?: number;
  81. top_p: number;
  82. max_tokens?: number;
  83. }
  84. interface RequestPayload {
  85. model: string;
  86. input: RequestInput;
  87. parameters: RequestParam;
  88. }
  89. export class QwenApi implements LLMApi {
  90. path(path: string): string {
  91. const accessStore = useAccessStore.getState();
  92. let baseUrl = "";
  93. if (accessStore.useCustomConfig) {
  94. baseUrl = accessStore.alibabaUrl;
  95. }
  96. if (baseUrl.length === 0) {
  97. const isApp = !!getClientConfig()?.isApp;
  98. baseUrl = isApp ? ALIBABA_BASE_URL : ApiPath.Alibaba;
  99. }
  100. if (baseUrl.endsWith("/")) {
  101. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  102. }
  103. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Alibaba)) {
  104. baseUrl = "https://" + baseUrl;
  105. }
  106. console.log("[Proxy Endpoint] ", baseUrl, path);
  107. return [baseUrl, path].join("/");
  108. }
  109. extractMessage(res: any) {
  110. return res?.output?.choices?.at(0)?.message?.content ?? "";
  111. }
  112. async chat(options: ChatOptions) {
  113. const modelConfig = {
  114. ...useAppConfig.getState().modelConfig,
  115. ...useChatStore.getState().currentSession().mask.modelConfig,
  116. ...{
  117. model: options.config.model,
  118. },
  119. };
  120. const visionModel = isVisionModel(options.config.model);
  121. const messages: any[] = [];
  122. for (const v of options.messages) {
  123. const content = visionModel
  124. ? await preProcessImageContent(v.content)
  125. : getMessageTextContent(v);
  126. messages.push({ role: v.role, content });
  127. }
  128. const shouldStream = !!options.config.stream;
  129. const requestPayload: RequestPayload = {
  130. model: modelConfig.model,
  131. input: {
  132. messages,
  133. },
  134. parameters: {
  135. result_format: "message",
  136. incremental_output: shouldStream,
  137. temperature: modelConfig.temperature,
  138. // max_tokens: modelConfig.max_tokens,
  139. top_p: modelConfig.top_p === 1 ? 0.99 : modelConfig.top_p, // qwen top_p is should be < 1
  140. },
  141. };
  142. const controller = new AbortController();
  143. options.onController?.(controller);
  144. try {
  145. // 根据模型类型选择不同的端点
  146. let chatPath = this.path(Alibaba.ChatPath);
  147. if (visionModel) {
  148. chatPath = this.path('/services/aigc/multimodal-generation/generation');
  149. }
  150. const chatPayload = {
  151. method: "POST",
  152. body: JSON.stringify(requestPayload),
  153. signal: controller.signal,
  154. headers: {
  155. ...getHeaders(),
  156. "X-DashScope-SSE": shouldStream ? "enable" : "disable",
  157. },
  158. };
  159. // make a fetch request
  160. const requestTimeoutId = setTimeout(
  161. () => controller.abort(),
  162. REQUEST_TIMEOUT_MS,
  163. );
  164. if (shouldStream) {
  165. let responseText = "";
  166. let remainText = "";
  167. let finished = false;
  168. // animate response to make it looks smooth
  169. function animateResponseText() {
  170. if (finished || controller.signal.aborted) {
  171. responseText += remainText;
  172. console.log("[Response Animation] finished");
  173. if (responseText?.length === 0) {
  174. options.onError?.(new Error("empty response from server"));
  175. }
  176. return;
  177. }
  178. if (remainText.length > 0) {
  179. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  180. const fetchText = remainText.slice(0, fetchCount);
  181. responseText += fetchText;
  182. remainText = remainText.slice(fetchCount);
  183. options.onUpdate?.(responseText, fetchText);
  184. }
  185. requestAnimationFrame(animateResponseText);
  186. }
  187. // start animaion
  188. animateResponseText();
  189. const finish = () => {
  190. if (!finished) {
  191. finished = true;
  192. options.onFinish(responseText + remainText);
  193. }
  194. };
  195. controller.signal.onabort = finish;
  196. fetchEventSource(chatPath, {
  197. ...chatPayload,
  198. async onopen(res) {
  199. clearTimeout(requestTimeoutId);
  200. const contentType = res.headers.get("content-type");
  201. console.log(
  202. "[Alibaba] request response content type: ",
  203. contentType,
  204. );
  205. if (contentType?.startsWith("text/plain")) {
  206. responseText = await res.clone().text();
  207. return finish();
  208. }
  209. if (
  210. !res.ok ||
  211. !res.headers
  212. .get("content-type")
  213. ?.startsWith(EventStreamContentType) ||
  214. res.status !== 200
  215. ) {
  216. const responseTexts = [responseText];
  217. let extraInfo = await res.clone().text();
  218. try {
  219. const resJson = await res.clone().json();
  220. extraInfo = prettyObject(resJson);
  221. } catch {}
  222. if (res.status === 401) {
  223. responseTexts.push(Locale.Error.Unauthorized);
  224. }
  225. if (extraInfo) {
  226. responseTexts.push(extraInfo);
  227. }
  228. responseText = responseTexts.join("\n\n");
  229. return finish();
  230. }
  231. },
  232. onmessage(msg) {
  233. if (msg.data === "[DONE]" || finished) {
  234. return finish();
  235. }
  236. const text = msg.data;
  237. try {
  238. const json = JSON.parse(text);
  239. const choices = json.output.choices as Array<{
  240. message: { content: string };
  241. }>;
  242. const delta = choices[0]?.message?.content;
  243. if (delta) {
  244. remainText += delta;
  245. }
  246. } catch (e) {
  247. console.error("[Request] parse error", text, msg);
  248. }
  249. },
  250. onclose() {
  251. finish();
  252. },
  253. onerror(e) {
  254. options.onError?.(e);
  255. throw e;
  256. },
  257. openWhenHidden: true,
  258. });
  259. } else {
  260. const res = await fetch(chatPath, chatPayload);
  261. clearTimeout(requestTimeoutId);
  262. const resJson = await res.json();
  263. const message = this.extractMessage(resJson);
  264. options.onFinish(message);
  265. }
  266. } catch (e) {
  267. console.log("[Request] failed to make a chat request", e);
  268. options.onError?.(e as Error);
  269. }
  270. }
  271. async usage() {
  272. return {
  273. used: 0,
  274. total: 0,
  275. };
  276. }
  277. async models(): Promise<LLMModel[]> {
  278. return [];
  279. }
  280. }
  281. export { Alibaba };