baidu.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. TranscriptionOptions,
  18. } from "../api";
  19. import Locale from "../../locales";
  20. import {
  21. EventStreamContentType,
  22. fetchEventSource,
  23. } from "@fortaine/fetch-event-source";
  24. import { prettyObject } from "@/app/utils/format";
  25. import { getClientConfig } from "@/app/config/client";
  26. import { getMessageTextContent } from "@/app/utils";
  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. transcription(options: TranscriptionOptions): Promise<string> {
  73. throw new Error("Method not implemented.");
  74. }
  75. async chat(options: ChatOptions) {
  76. const messages = options.messages.map((v) => ({
  77. // "error_code": 336006, "error_msg": "the role of message with even index in the messages must be user or function",
  78. role: v.role === "system" ? "user" : v.role,
  79. content: getMessageTextContent(v),
  80. }));
  81. // "error_code": 336006, "error_msg": "the length of messages must be an odd number",
  82. if (messages.length % 2 === 0) {
  83. if (messages.at(0)?.role === "user") {
  84. messages.splice(1, 0, {
  85. role: "assistant",
  86. content: " ",
  87. });
  88. } else {
  89. messages.unshift({
  90. role: "user",
  91. content: " ",
  92. });
  93. }
  94. }
  95. const modelConfig = {
  96. ...useAppConfig.getState().modelConfig,
  97. ...useChatStore.getState().currentSession().mask.modelConfig,
  98. ...{
  99. model: options.config.model,
  100. },
  101. };
  102. const shouldStream = !!options.config.stream;
  103. const requestPayload: RequestPayload = {
  104. messages,
  105. stream: shouldStream,
  106. model: modelConfig.model,
  107. temperature: modelConfig.temperature,
  108. presence_penalty: modelConfig.presence_penalty,
  109. frequency_penalty: modelConfig.frequency_penalty,
  110. top_p: modelConfig.top_p,
  111. };
  112. console.log("[Request] Baidu payload: ", requestPayload);
  113. const controller = new AbortController();
  114. options.onController?.(controller);
  115. try {
  116. let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
  117. // getAccessToken can not run in browser, because cors error
  118. if (!!getClientConfig()?.isApp) {
  119. const accessStore = useAccessStore.getState();
  120. if (accessStore.useCustomConfig) {
  121. if (accessStore.isValidBaidu()) {
  122. const { access_token } = await getAccessToken(
  123. accessStore.baiduApiKey,
  124. accessStore.baiduSecretKey,
  125. );
  126. chatPath = `${chatPath}${
  127. chatPath.includes("?") ? "&" : "?"
  128. }access_token=${access_token}`;
  129. }
  130. }
  131. }
  132. const chatPayload = {
  133. method: "POST",
  134. body: JSON.stringify(requestPayload),
  135. signal: controller.signal,
  136. headers: getHeaders(),
  137. };
  138. // make a fetch request
  139. const requestTimeoutId = setTimeout(
  140. () => controller.abort(),
  141. REQUEST_TIMEOUT_MS,
  142. );
  143. if (shouldStream) {
  144. let responseText = "";
  145. let remainText = "";
  146. let finished = false;
  147. // animate response to make it looks smooth
  148. function animateResponseText() {
  149. if (finished || controller.signal.aborted) {
  150. responseText += remainText;
  151. console.log("[Response Animation] finished");
  152. if (responseText?.length === 0) {
  153. options.onError?.(new Error("empty response from server"));
  154. }
  155. return;
  156. }
  157. if (remainText.length > 0) {
  158. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  159. const fetchText = remainText.slice(0, fetchCount);
  160. responseText += fetchText;
  161. remainText = remainText.slice(fetchCount);
  162. options.onUpdate?.(responseText, fetchText);
  163. }
  164. requestAnimationFrame(animateResponseText);
  165. }
  166. // start animaion
  167. animateResponseText();
  168. const finish = () => {
  169. if (!finished) {
  170. finished = true;
  171. options.onFinish(responseText + remainText);
  172. }
  173. };
  174. controller.signal.onabort = finish;
  175. fetchEventSource(chatPath, {
  176. ...chatPayload,
  177. async onopen(res) {
  178. clearTimeout(requestTimeoutId);
  179. const contentType = res.headers.get("content-type");
  180. console.log("[Baidu] request response content type: ", contentType);
  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);
  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 };