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