baidu.ts 7.8 KB

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