baidu.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. "use client";
  2. import {
  3. ApiPath,
  4. Baidu,
  5. BAIDU_BASE_URL,
  6. REQUEST_TIMEOUT_MS,
  7. } from "@/app/constant";
  8. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  9. import { getAccessToken } from "@/app/utils/baidu";
  10. import {
  11. ChatOptions,
  12. getHeaders,
  13. LLMApi,
  14. LLMModel,
  15. MultimodalContent,
  16. SpeechOptions,
  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. import { fetch } from "@/app/utils/stream";
  27. export interface OpenAIListModelResponse {
  28. object: string;
  29. data: Array<{
  30. id: string;
  31. object: string;
  32. root: string;
  33. }>;
  34. }
  35. interface RequestPayload {
  36. messages: {
  37. role: "system" | "user" | "assistant";
  38. content: string | MultimodalContent[];
  39. }[];
  40. stream?: boolean;
  41. model: string;
  42. temperature: number;
  43. presence_penalty: number;
  44. frequency_penalty: number;
  45. top_p: number;
  46. max_tokens?: number;
  47. }
  48. export class ErnieApi implements LLMApi {
  49. path(path: string): string {
  50. const accessStore = useAccessStore.getState();
  51. let baseUrl = "";
  52. if (accessStore.useCustomConfig) {
  53. baseUrl = accessStore.baiduUrl;
  54. }
  55. if (baseUrl.length === 0) {
  56. const isApp = !!getClientConfig()?.isApp;
  57. // do not use proxy for baidubce api
  58. baseUrl = isApp ? BAIDU_BASE_URL : ApiPath.Baidu;
  59. }
  60. if (baseUrl.endsWith("/")) {
  61. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  62. }
  63. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Baidu)) {
  64. baseUrl = "https://" + baseUrl;
  65. }
  66. console.log("[Proxy Endpoint] ", baseUrl, path);
  67. return [baseUrl, path].join("/");
  68. }
  69. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  70. throw new Error("Method not implemented.");
  71. }
  72. async chat(options: ChatOptions) {
  73. const messages = options.messages.map((v) => ({
  74. // "error_code": 336006, "error_msg": "the role of message with even index in the messages must be user or function",
  75. role: v.role === "system" ? "user" : v.role,
  76. content: getMessageTextContent(v),
  77. }));
  78. // "error_code": 336006, "error_msg": "the length of messages must be an odd number",
  79. if (messages.length % 2 === 0) {
  80. if (messages.at(0)?.role === "user") {
  81. messages.splice(1, 0, {
  82. role: "assistant",
  83. content: " ",
  84. });
  85. } else {
  86. messages.unshift({
  87. role: "user",
  88. content: " ",
  89. });
  90. }
  91. }
  92. const modelConfig = {
  93. ...useAppConfig.getState().modelConfig,
  94. ...useChatStore.getState().currentSession().mask.modelConfig,
  95. ...{
  96. model: options.config.model,
  97. },
  98. };
  99. const shouldStream = !!options.config.stream;
  100. const requestPayload: RequestPayload = {
  101. messages,
  102. stream: shouldStream,
  103. model: modelConfig.model,
  104. temperature: modelConfig.temperature,
  105. presence_penalty: modelConfig.presence_penalty,
  106. frequency_penalty: modelConfig.frequency_penalty,
  107. top_p: modelConfig.top_p,
  108. };
  109. console.log("[Request] Baidu payload: ", requestPayload);
  110. const controller = new AbortController();
  111. options.onController?.(controller);
  112. try {
  113. let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
  114. // getAccessToken can not run in browser, because cors error
  115. if (!!getClientConfig()?.isApp) {
  116. const accessStore = useAccessStore.getState();
  117. if (accessStore.useCustomConfig) {
  118. if (accessStore.isValidBaidu()) {
  119. const { access_token } = await getAccessToken(
  120. accessStore.baiduApiKey,
  121. accessStore.baiduSecretKey,
  122. );
  123. chatPath = `${chatPath}${
  124. chatPath.includes("?") ? "&" : "?"
  125. }access_token=${access_token}`;
  126. }
  127. }
  128. }
  129. const chatPayload = {
  130. method: "POST",
  131. body: JSON.stringify(requestPayload),
  132. signal: controller.signal,
  133. headers: getHeaders(),
  134. };
  135. // make a fetch request
  136. const requestTimeoutId = setTimeout(
  137. () => controller.abort(),
  138. REQUEST_TIMEOUT_MS,
  139. );
  140. if (shouldStream) {
  141. let responseText = "";
  142. let remainText = "";
  143. let finished = false;
  144. let responseRes: Response;
  145. // animate response to make it looks smooth
  146. function animateResponseText() {
  147. if (finished || controller.signal.aborted) {
  148. responseText += remainText;
  149. console.log("[Response Animation] finished");
  150. if (responseText?.length === 0) {
  151. options.onError?.(new Error("empty response from server"));
  152. }
  153. return;
  154. }
  155. if (remainText.length > 0) {
  156. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  157. const fetchText = remainText.slice(0, fetchCount);
  158. responseText += fetchText;
  159. remainText = remainText.slice(fetchCount);
  160. options.onUpdate?.(responseText, fetchText);
  161. }
  162. requestAnimationFrame(animateResponseText);
  163. }
  164. // start animaion
  165. animateResponseText();
  166. const finish = () => {
  167. if (!finished) {
  168. finished = true;
  169. options.onFinish(responseText + remainText, responseRes);
  170. }
  171. };
  172. controller.signal.onabort = finish;
  173. fetchEventSource(chatPath, {
  174. fetch: fetch as any,
  175. ...chatPayload,
  176. async onopen(res) {
  177. clearTimeout(requestTimeoutId);
  178. const contentType = res.headers.get("content-type");
  179. console.log("[Baidu] request response content type: ", contentType);
  180. responseRes = res;
  181. if (contentType?.startsWith("text/plain")) {
  182. responseText = await res.clone().text();
  183. return finish();
  184. }
  185. if (
  186. !res.ok ||
  187. !res.headers
  188. .get("content-type")
  189. ?.startsWith(EventStreamContentType) ||
  190. res.status !== 200
  191. ) {
  192. const responseTexts = [responseText];
  193. let extraInfo = await res.clone().text();
  194. try {
  195. const resJson = await res.clone().json();
  196. extraInfo = prettyObject(resJson);
  197. } catch {}
  198. if (res.status === 401) {
  199. responseTexts.push(Locale.Error.Unauthorized);
  200. }
  201. if (extraInfo) {
  202. responseTexts.push(extraInfo);
  203. }
  204. responseText = responseTexts.join("\n\n");
  205. return finish();
  206. }
  207. },
  208. onmessage(msg) {
  209. if (msg.data === "[DONE]" || finished) {
  210. return finish();
  211. }
  212. const text = msg.data;
  213. try {
  214. const json = JSON.parse(text);
  215. const delta = json?.result;
  216. if (delta) {
  217. remainText += delta;
  218. }
  219. } catch (e) {
  220. console.error("[Request] parse error", text, msg);
  221. }
  222. },
  223. onclose() {
  224. finish();
  225. },
  226. onerror(e) {
  227. options.onError?.(e);
  228. throw e;
  229. },
  230. openWhenHidden: true,
  231. });
  232. } else {
  233. const res = await fetch(chatPath, chatPayload);
  234. clearTimeout(requestTimeoutId);
  235. const resJson = await res.json();
  236. const message = resJson?.result;
  237. options.onFinish(message, res);
  238. }
  239. } catch (e) {
  240. console.log("[Request] failed to make a chat request", e);
  241. options.onError?.(e as Error);
  242. }
  243. }
  244. async usage() {
  245. return {
  246. used: 0,
  247. total: 0,
  248. };
  249. }
  250. async models(): Promise<LLMModel[]> {
  251. return [];
  252. }
  253. }
  254. export { Baidu };