baidu.ts 7.7 KB

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