baidu.ts 7.6 KB

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