baidu.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. } 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 RequestPayload {
  34. messages: {
  35. role: "system" | "user" | "assistant";
  36. content: string | MultimodalContent[];
  37. }[];
  38. stream?: boolean;
  39. model: string;
  40. temperature: number;
  41. presence_penalty: number;
  42. frequency_penalty: number;
  43. top_p: number;
  44. max_tokens?: number;
  45. }
  46. export class ErnieApi implements LLMApi {
  47. path(path: string): string {
  48. const accessStore = useAccessStore.getState();
  49. let baseUrl = "";
  50. if (accessStore.useCustomConfig) {
  51. baseUrl = accessStore.baiduUrl;
  52. }
  53. if (baseUrl.length === 0) {
  54. const isApp = !!getClientConfig()?.isApp;
  55. // do not use proxy for baidubce api
  56. baseUrl = isApp ? BAIDU_BASE_URL : ApiPath.Baidu;
  57. }
  58. if (baseUrl.endsWith("/")) {
  59. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  60. }
  61. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Baidu)) {
  62. baseUrl = "https://" + baseUrl;
  63. }
  64. console.log("[Proxy Endpoint] ", baseUrl, path);
  65. return [baseUrl, path].join("/");
  66. }
  67. async chat(options: ChatOptions) {
  68. const messages = options.messages.map((v) => ({
  69. role: v.role,
  70. content: getMessageTextContent(v),
  71. }));
  72. // "error_code": 336006, "error_msg": "the length of messages must be an odd number",
  73. if (messages.length % 2 === 0) {
  74. messages.unshift({
  75. role: "user",
  76. content: " ",
  77. });
  78. }
  79. const modelConfig = {
  80. ...useAppConfig.getState().modelConfig,
  81. ...useChatStore.getState().currentSession().mask.modelConfig,
  82. ...{
  83. model: options.config.model,
  84. },
  85. };
  86. const shouldStream = !!options.config.stream;
  87. const requestPayload: RequestPayload = {
  88. messages,
  89. stream: shouldStream,
  90. model: modelConfig.model,
  91. temperature: modelConfig.temperature,
  92. presence_penalty: modelConfig.presence_penalty,
  93. frequency_penalty: modelConfig.frequency_penalty,
  94. top_p: modelConfig.top_p,
  95. };
  96. console.log("[Request] Baidu payload: ", requestPayload);
  97. const controller = new AbortController();
  98. options.onController?.(controller);
  99. try {
  100. let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
  101. // getAccessToken can not run in browser, because cors error
  102. if (!!getClientConfig()?.isApp) {
  103. const accessStore = useAccessStore.getState();
  104. if (accessStore.useCustomConfig) {
  105. if (accessStore.isValidBaidu()) {
  106. const { access_token } = await getAccessToken(
  107. accessStore.baiduApiKey,
  108. accessStore.baiduSecretKey,
  109. );
  110. chatPath = `${chatPath}${
  111. chatPath.includes("?") ? "&" : "?"
  112. }access_token=${access_token}`;
  113. }
  114. }
  115. }
  116. const chatPayload = {
  117. method: "POST",
  118. body: JSON.stringify(requestPayload),
  119. signal: controller.signal,
  120. headers: getHeaders(),
  121. };
  122. // make a fetch request
  123. const requestTimeoutId = setTimeout(
  124. () => controller.abort(),
  125. REQUEST_TIMEOUT_MS,
  126. );
  127. if (shouldStream) {
  128. let responseText = "";
  129. let remainText = "";
  130. let finished = false;
  131. // animate response to make it looks smooth
  132. function animateResponseText() {
  133. if (finished || controller.signal.aborted) {
  134. responseText += remainText;
  135. console.log("[Response Animation] finished");
  136. if (responseText?.length === 0) {
  137. options.onError?.(new Error("empty response from server"));
  138. }
  139. return;
  140. }
  141. if (remainText.length > 0) {
  142. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  143. const fetchText = remainText.slice(0, fetchCount);
  144. responseText += fetchText;
  145. remainText = remainText.slice(fetchCount);
  146. options.onUpdate?.(responseText, fetchText);
  147. }
  148. requestAnimationFrame(animateResponseText);
  149. }
  150. // start animaion
  151. animateResponseText();
  152. const finish = () => {
  153. if (!finished) {
  154. finished = true;
  155. options.onFinish(responseText + remainText);
  156. }
  157. };
  158. controller.signal.onabort = finish;
  159. fetchEventSource(chatPath, {
  160. ...chatPayload,
  161. async onopen(res) {
  162. clearTimeout(requestTimeoutId);
  163. const contentType = res.headers.get("content-type");
  164. console.log("[Baidu] request response content type: ", contentType);
  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 delta = json?.result;
  200. if (delta) {
  201. remainText += delta;
  202. }
  203. } catch (e) {
  204. console.error("[Request] parse error", text, msg);
  205. }
  206. },
  207. onclose() {
  208. finish();
  209. },
  210. onerror(e) {
  211. options.onError?.(e);
  212. throw e;
  213. },
  214. openWhenHidden: true,
  215. });
  216. } else {
  217. const res = await fetch(chatPath, chatPayload);
  218. clearTimeout(requestTimeoutId);
  219. const resJson = await res.json();
  220. const message = resJson?.result;
  221. options.onFinish(message);
  222. }
  223. } catch (e) {
  224. console.log("[Request] failed to make a chat request", e);
  225. options.onError?.(e as Error);
  226. }
  227. }
  228. async usage() {
  229. return {
  230. used: 0,
  231. total: 0,
  232. };
  233. }
  234. async models(): Promise<LLMModel[]> {
  235. return [];
  236. }
  237. }
  238. export { Baidu };