baidu.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. // "error_code": 336006, "error_msg": "the role of message with odd index in the messages must be assistant",
  70. role: v.role === "system" ? "assistant" : v.role,
  71. content: getMessageTextContent(v),
  72. }));
  73. // "error_code": 336006, "error_msg": "the length of messages must be an odd number",
  74. if (messages.length % 2 === 0) {
  75. messages.unshift({
  76. role: "user",
  77. content: " ",
  78. });
  79. }
  80. const modelConfig = {
  81. ...useAppConfig.getState().modelConfig,
  82. ...useChatStore.getState().currentSession().mask.modelConfig,
  83. ...{
  84. model: options.config.model,
  85. },
  86. };
  87. const shouldStream = !!options.config.stream;
  88. const requestPayload: RequestPayload = {
  89. messages,
  90. stream: shouldStream,
  91. model: modelConfig.model,
  92. temperature: modelConfig.temperature,
  93. presence_penalty: modelConfig.presence_penalty,
  94. frequency_penalty: modelConfig.frequency_penalty,
  95. top_p: modelConfig.top_p,
  96. };
  97. console.log("[Request] Baidu payload: ", requestPayload);
  98. const controller = new AbortController();
  99. options.onController?.(controller);
  100. try {
  101. let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
  102. // getAccessToken can not run in browser, because cors error
  103. if (!!getClientConfig()?.isApp) {
  104. const accessStore = useAccessStore.getState();
  105. if (accessStore.useCustomConfig) {
  106. if (accessStore.isValidBaidu()) {
  107. const { access_token } = await getAccessToken(
  108. accessStore.baiduApiKey,
  109. accessStore.baiduSecretKey,
  110. );
  111. chatPath = `${chatPath}${
  112. chatPath.includes("?") ? "&" : "?"
  113. }access_token=${access_token}`;
  114. }
  115. }
  116. }
  117. const chatPayload = {
  118. method: "POST",
  119. body: JSON.stringify(requestPayload),
  120. signal: controller.signal,
  121. headers: getHeaders(),
  122. };
  123. // make a fetch request
  124. const requestTimeoutId = setTimeout(
  125. () => controller.abort(),
  126. REQUEST_TIMEOUT_MS,
  127. );
  128. if (shouldStream) {
  129. let responseText = "";
  130. let remainText = "";
  131. let finished = false;
  132. // animate response to make it looks smooth
  133. function animateResponseText() {
  134. if (finished || controller.signal.aborted) {
  135. responseText += remainText;
  136. console.log("[Response Animation] finished");
  137. if (responseText?.length === 0) {
  138. options.onError?.(new Error("empty response from server"));
  139. }
  140. return;
  141. }
  142. if (remainText.length > 0) {
  143. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  144. const fetchText = remainText.slice(0, fetchCount);
  145. responseText += fetchText;
  146. remainText = remainText.slice(fetchCount);
  147. options.onUpdate?.(responseText, fetchText);
  148. }
  149. requestAnimationFrame(animateResponseText);
  150. }
  151. // start animaion
  152. animateResponseText();
  153. const finish = () => {
  154. if (!finished) {
  155. finished = true;
  156. options.onFinish(responseText + remainText);
  157. }
  158. };
  159. controller.signal.onabort = finish;
  160. fetchEventSource(chatPath, {
  161. ...chatPayload,
  162. async onopen(res) {
  163. clearTimeout(requestTimeoutId);
  164. const contentType = res.headers.get("content-type");
  165. console.log("[Baidu] request response content type: ", contentType);
  166. if (contentType?.startsWith("text/plain")) {
  167. responseText = await res.clone().text();
  168. return finish();
  169. }
  170. if (
  171. !res.ok ||
  172. !res.headers
  173. .get("content-type")
  174. ?.startsWith(EventStreamContentType) ||
  175. res.status !== 200
  176. ) {
  177. const responseTexts = [responseText];
  178. let extraInfo = await res.clone().text();
  179. try {
  180. const resJson = await res.clone().json();
  181. extraInfo = prettyObject(resJson);
  182. } catch {}
  183. if (res.status === 401) {
  184. responseTexts.push(Locale.Error.Unauthorized);
  185. }
  186. if (extraInfo) {
  187. responseTexts.push(extraInfo);
  188. }
  189. responseText = responseTexts.join("\n\n");
  190. return finish();
  191. }
  192. },
  193. onmessage(msg) {
  194. if (msg.data === "[DONE]" || finished) {
  195. return finish();
  196. }
  197. const text = msg.data;
  198. try {
  199. const json = JSON.parse(text);
  200. const delta = json?.result;
  201. if (delta) {
  202. remainText += delta;
  203. }
  204. } catch (e) {
  205. console.error("[Request] parse error", text, msg);
  206. }
  207. },
  208. onclose() {
  209. finish();
  210. },
  211. onerror(e) {
  212. options.onError?.(e);
  213. throw e;
  214. },
  215. openWhenHidden: true,
  216. });
  217. } else {
  218. const res = await fetch(chatPath, chatPayload);
  219. clearTimeout(requestTimeoutId);
  220. const resJson = await res.json();
  221. const message = resJson?.result;
  222. options.onFinish(message);
  223. }
  224. } catch (e) {
  225. console.log("[Request] failed to make a chat request", e);
  226. options.onError?.(e as Error);
  227. }
  228. }
  229. async usage() {
  230. return {
  231. used: 0,
  232. total: 0,
  233. };
  234. }
  235. async models(): Promise<LLMModel[]> {
  236. return [];
  237. }
  238. }
  239. export { Baidu };