openai.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. "use client";
  2. // azure and openai, using same models. so using same LLMApi.
  3. import {
  4. ApiPath,
  5. DEFAULT_API_HOST,
  6. DEFAULT_MODELS,
  7. OpenaiPath,
  8. Azure,
  9. REQUEST_TIMEOUT_MS,
  10. ServiceProvider,
  11. } from "@/app/constant";
  12. import {
  13. ChatMessageTool,
  14. useAccessStore,
  15. useAppConfig,
  16. useChatStore,
  17. } from "@/app/store";
  18. import { collectModelsWithDefaultModel } from "@/app/utils/model";
  19. import {
  20. preProcessImageContent,
  21. uploadImage,
  22. base64Image2Blob,
  23. } from "@/app/utils/chat";
  24. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  25. import { DalleSize, DalleQuality, DalleStyle } from "@/app/typing";
  26. import {
  27. ChatOptions,
  28. getHeaders,
  29. LLMApi,
  30. LLMModel,
  31. LLMUsage,
  32. MultimodalContent,
  33. } from "../api";
  34. import Locale from "../../locales";
  35. import {
  36. EventStreamContentType,
  37. fetchEventSource,
  38. } from "@fortaine/fetch-event-source";
  39. import { prettyObject } from "@/app/utils/format";
  40. import { getClientConfig } from "@/app/config/client";
  41. import {
  42. getMessageTextContent,
  43. getMessageImages,
  44. isVisionModel,
  45. isDalle3 as _isDalle3,
  46. } from "@/app/utils";
  47. export interface OpenAIListModelResponse {
  48. object: string;
  49. data: Array<{
  50. id: string;
  51. object: string;
  52. root: string;
  53. }>;
  54. }
  55. export interface RequestPayload {
  56. messages: {
  57. role: "system" | "user" | "assistant";
  58. content: string | MultimodalContent[];
  59. }[];
  60. stream?: boolean;
  61. model: string;
  62. temperature: number;
  63. presence_penalty: number;
  64. frequency_penalty: number;
  65. top_p: number;
  66. max_tokens?: number;
  67. }
  68. export interface DalleRequestPayload {
  69. model: string;
  70. prompt: string;
  71. response_format: "url" | "b64_json";
  72. n: number;
  73. size: DalleSize;
  74. quality: DalleQuality;
  75. style: DalleStyle;
  76. }
  77. export class ChatGPTApi implements LLMApi {
  78. private disableListModels = true;
  79. path(path: string): string {
  80. const accessStore = useAccessStore.getState();
  81. let baseUrl = "";
  82. const isAzure = path.includes("deployments");
  83. if (accessStore.useCustomConfig) {
  84. if (isAzure && !accessStore.isValidAzure()) {
  85. throw Error(
  86. "incomplete azure config, please check it in your settings page",
  87. );
  88. }
  89. baseUrl = isAzure ? accessStore.azureUrl : accessStore.openaiUrl;
  90. }
  91. if (baseUrl.length === 0) {
  92. const isApp = !!getClientConfig()?.isApp;
  93. const apiPath = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
  94. baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
  95. }
  96. if (baseUrl.endsWith("/")) {
  97. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  98. }
  99. if (
  100. !baseUrl.startsWith("http") &&
  101. !isAzure &&
  102. !baseUrl.startsWith(ApiPath.OpenAI)
  103. ) {
  104. baseUrl = "https://" + baseUrl;
  105. }
  106. console.log("[Proxy Endpoint] ", baseUrl, path);
  107. // try rebuild url, when using cloudflare ai gateway in client
  108. return cloudflareAIGatewayUrl([baseUrl, path].join("/"));
  109. }
  110. async extractMessage(res: any) {
  111. if (res.error) {
  112. return "```\n" + JSON.stringify(res, null, 4) + "\n```";
  113. }
  114. // dalle3 model return url, using url create image message
  115. if (res.data) {
  116. let url = res.data?.at(0)?.url ?? "";
  117. const b64_json = res.data?.at(0)?.b64_json ?? "";
  118. if (!url && b64_json) {
  119. // uploadImage
  120. url = await uploadImage(base64Image2Blob(b64_json, "image/png"));
  121. }
  122. return [
  123. {
  124. type: "image_url",
  125. image_url: {
  126. url,
  127. },
  128. },
  129. ];
  130. }
  131. return res.choices?.at(0)?.message?.content ?? res;
  132. }
  133. async chat(options: ChatOptions) {
  134. const modelConfig = {
  135. ...useAppConfig.getState().modelConfig,
  136. ...useChatStore.getState().currentSession().mask.modelConfig,
  137. ...{
  138. model: options.config.model,
  139. providerName: options.config.providerName,
  140. },
  141. };
  142. let requestPayload: RequestPayload | DalleRequestPayload;
  143. const isDalle3 = _isDalle3(options.config.model);
  144. if (isDalle3) {
  145. const prompt = getMessageTextContent(
  146. options.messages.slice(-1)?.pop() as any,
  147. );
  148. requestPayload = {
  149. model: options.config.model,
  150. prompt,
  151. // URLs are only valid for 60 minutes after the image has been generated.
  152. response_format: "b64_json", // using b64_json, and save image in CacheStorage
  153. n: 1,
  154. size: options.config?.size ?? "1024x1024",
  155. quality: options.config?.quality ?? "standard",
  156. style: options.config?.style ?? "vivid",
  157. };
  158. } else {
  159. const visionModel = isVisionModel(options.config.model);
  160. const messages: ChatOptions["messages"] = [];
  161. for (const v of options.messages) {
  162. const content = visionModel
  163. ? await preProcessImageContent(v.content)
  164. : getMessageTextContent(v);
  165. messages.push({ role: v.role, content });
  166. }
  167. requestPayload = {
  168. messages,
  169. stream: options.config.stream,
  170. model: modelConfig.model,
  171. temperature: modelConfig.temperature,
  172. presence_penalty: modelConfig.presence_penalty,
  173. frequency_penalty: modelConfig.frequency_penalty,
  174. top_p: modelConfig.top_p,
  175. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  176. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  177. };
  178. // add max_tokens to vision model
  179. if (visionModel && modelConfig.model.includes("preview")) {
  180. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  181. }
  182. }
  183. console.log("[Request] openai payload: ", requestPayload);
  184. const shouldStream = !isDalle3 && !!options.config.stream;
  185. const controller = new AbortController();
  186. options.onController?.(controller);
  187. try {
  188. let chatPath = "";
  189. if (modelConfig.providerName === ServiceProvider.Azure) {
  190. // find model, and get displayName as deployName
  191. const { models: configModels, customModels: configCustomModels } =
  192. useAppConfig.getState();
  193. const {
  194. defaultModel,
  195. customModels: accessCustomModels,
  196. useCustomConfig,
  197. } = useAccessStore.getState();
  198. const models = collectModelsWithDefaultModel(
  199. configModels,
  200. [configCustomModels, accessCustomModels].join(","),
  201. defaultModel,
  202. );
  203. const model = models.find(
  204. (model) =>
  205. model.name === modelConfig.model &&
  206. model?.provider?.providerName === ServiceProvider.Azure,
  207. );
  208. chatPath = this.path(
  209. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  210. (model?.displayName ?? model?.name) as string,
  211. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  212. ),
  213. );
  214. } else {
  215. chatPath = this.path(
  216. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  217. );
  218. }
  219. const chatPayload = {
  220. method: "POST",
  221. body: JSON.stringify(requestPayload),
  222. signal: controller.signal,
  223. headers: getHeaders(),
  224. };
  225. // make a fetch request
  226. const requestTimeoutId = setTimeout(
  227. () => controller.abort(),
  228. isDalle3 ? REQUEST_TIMEOUT_MS * 2 : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
  229. );
  230. if (shouldStream) {
  231. let responseText = "";
  232. let remainText = "";
  233. let finished = false;
  234. let running = false;
  235. let runTools: ChatMessageTool[] = [];
  236. // animate response to make it looks smooth
  237. function animateResponseText() {
  238. if (finished || controller.signal.aborted) {
  239. responseText += remainText;
  240. console.log("[Response Animation] finished");
  241. if (responseText?.length === 0) {
  242. options.onError?.(new Error("empty response from server"));
  243. }
  244. return;
  245. }
  246. if (remainText.length > 0) {
  247. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  248. const fetchText = remainText.slice(0, fetchCount);
  249. responseText += fetchText;
  250. remainText = remainText.slice(fetchCount);
  251. options.onUpdate?.(responseText, fetchText);
  252. }
  253. requestAnimationFrame(animateResponseText);
  254. }
  255. // start animaion
  256. animateResponseText();
  257. // TODO 后面这里是从选择的plugins中获取function列表
  258. const funcs = {
  259. get_current_weather: (args: any) => {
  260. console.log("call get_current_weather", args);
  261. return "30";
  262. },
  263. };
  264. const finish = () => {
  265. if (!finished) {
  266. console.log("try run tools", runTools.length, finished, running);
  267. if (!running && runTools.length > 0) {
  268. const toolCallMessage = {
  269. role: "assistant",
  270. tool_calls: [...runTools],
  271. };
  272. running = true;
  273. runTools.splice(0, runTools.length); // empty runTools
  274. return Promise.all(
  275. toolCallMessage.tool_calls.map((tool) => {
  276. options?.onBeforeTool?.(tool);
  277. return Promise.resolve(
  278. // @ts-ignore
  279. funcs[tool.function.name](
  280. // @ts-ignore
  281. JSON.parse(tool.function.arguments),
  282. ),
  283. )
  284. .then((content) => {
  285. options?.onAfterTool?.({
  286. ...tool,
  287. content,
  288. isError: false,
  289. });
  290. return content;
  291. })
  292. .catch((e) => {
  293. options?.onAfterTool?.({ ...tool, isError: true });
  294. return e.toString();
  295. })
  296. .then((content) => ({
  297. role: "tool",
  298. content,
  299. tool_call_id: tool.id,
  300. }));
  301. }),
  302. ).then((toolCallResult) => {
  303. console.log("end runTools", toolCallMessage, toolCallResult);
  304. // @ts-ignore
  305. requestPayload?.messages?.splice(
  306. // @ts-ignore
  307. requestPayload?.messages?.length,
  308. 0,
  309. toolCallMessage,
  310. ...toolCallResult,
  311. );
  312. requestAnimationFrame(() => {
  313. // call again
  314. console.log("start again");
  315. running = false;
  316. chatApi(chatPath, requestPayload as RequestPayload); // call fetchEventSource
  317. });
  318. });
  319. console.log("try run tools", runTools.length, finished);
  320. return;
  321. }
  322. if (running) {
  323. return;
  324. }
  325. finished = true;
  326. options.onFinish(responseText + remainText);
  327. }
  328. };
  329. controller.signal.onabort = finish;
  330. function chatApi(chatPath: string, requestPayload: RequestPayload) {
  331. const chatPayload = {
  332. method: "POST",
  333. body: JSON.stringify({
  334. ...requestPayload,
  335. // TODO 这里暂时写死的,后面从store.tools中按照当前session中选择的获取
  336. tools: [
  337. {
  338. type: "function",
  339. function: {
  340. name: "get_current_weather",
  341. description: "Get the current weather",
  342. parameters: {
  343. type: "object",
  344. properties: {
  345. location: {
  346. type: "string",
  347. description:
  348. "The city and country, eg. San Francisco, USA",
  349. },
  350. format: {
  351. type: "string",
  352. enum: ["celsius", "fahrenheit"],
  353. },
  354. },
  355. required: ["location", "format"],
  356. },
  357. },
  358. },
  359. ],
  360. }),
  361. signal: controller.signal,
  362. headers: getHeaders(),
  363. };
  364. console.log("chatApi", chatPath, requestPayload, chatPayload);
  365. fetchEventSource(chatPath, {
  366. ...chatPayload,
  367. async onopen(res) {
  368. clearTimeout(requestTimeoutId);
  369. const contentType = res.headers.get("content-type");
  370. console.log(
  371. "[OpenAI] request response content type: ",
  372. contentType,
  373. );
  374. if (contentType?.startsWith("text/plain")) {
  375. responseText = await res.clone().text();
  376. return finish();
  377. }
  378. if (
  379. !res.ok ||
  380. !res.headers
  381. .get("content-type")
  382. ?.startsWith(EventStreamContentType) ||
  383. res.status !== 200
  384. ) {
  385. const responseTexts = [responseText];
  386. let extraInfo = await res.clone().text();
  387. try {
  388. const resJson = await res.clone().json();
  389. extraInfo = prettyObject(resJson);
  390. } catch {}
  391. if (res.status === 401) {
  392. responseTexts.push(Locale.Error.Unauthorized);
  393. }
  394. if (extraInfo) {
  395. responseTexts.push(extraInfo);
  396. }
  397. responseText = responseTexts.join("\n\n");
  398. return finish();
  399. }
  400. },
  401. onmessage(msg) {
  402. if (msg.data === "[DONE]" || finished) {
  403. return finish();
  404. }
  405. const text = msg.data;
  406. try {
  407. const json = JSON.parse(text);
  408. const choices = json.choices as Array<{
  409. delta: {
  410. content: string;
  411. tool_calls: ChatMessageTool[];
  412. };
  413. }>;
  414. console.log("choices", choices);
  415. const delta = choices[0]?.delta?.content;
  416. const tool_calls = choices[0]?.delta?.tool_calls;
  417. const textmoderation = json?.prompt_filter_results;
  418. if (delta) {
  419. remainText += delta;
  420. }
  421. if (tool_calls?.length > 0) {
  422. const index = tool_calls[0]?.index;
  423. const id = tool_calls[0]?.id;
  424. const args = tool_calls[0]?.function?.arguments;
  425. if (id) {
  426. runTools.push({
  427. id,
  428. type: tool_calls[0]?.type,
  429. function: {
  430. name: tool_calls[0]?.function?.name as string,
  431. arguments: args,
  432. },
  433. });
  434. } else {
  435. // @ts-ignore
  436. runTools[index]["function"]["arguments"] += args;
  437. }
  438. }
  439. console.log("runTools", runTools);
  440. if (
  441. textmoderation &&
  442. textmoderation.length > 0 &&
  443. ServiceProvider.Azure
  444. ) {
  445. const contentFilterResults =
  446. textmoderation[0]?.content_filter_results;
  447. console.log(
  448. `[${ServiceProvider.Azure}] [Text Moderation] flagged categories result:`,
  449. contentFilterResults,
  450. );
  451. }
  452. } catch (e) {
  453. console.error("[Request] parse error", text, msg);
  454. }
  455. },
  456. onclose() {
  457. finish();
  458. },
  459. onerror(e) {
  460. options.onError?.(e);
  461. throw e;
  462. },
  463. openWhenHidden: true,
  464. });
  465. }
  466. chatApi(chatPath, requestPayload as RequestPayload); // call fetchEventSource
  467. } else {
  468. const res = await fetch(chatPath, chatPayload);
  469. clearTimeout(requestTimeoutId);
  470. const resJson = await res.json();
  471. const message = await this.extractMessage(resJson);
  472. options.onFinish(message);
  473. }
  474. } catch (e) {
  475. console.log("[Request] failed to make a chat request", e);
  476. options.onError?.(e as Error);
  477. }
  478. }
  479. async usage() {
  480. const formatDate = (d: Date) =>
  481. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  482. .getDate()
  483. .toString()
  484. .padStart(2, "0")}`;
  485. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  486. const now = new Date();
  487. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  488. const startDate = formatDate(startOfMonth);
  489. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  490. const [used, subs] = await Promise.all([
  491. fetch(
  492. this.path(
  493. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  494. ),
  495. {
  496. method: "GET",
  497. headers: getHeaders(),
  498. },
  499. ),
  500. fetch(this.path(OpenaiPath.SubsPath), {
  501. method: "GET",
  502. headers: getHeaders(),
  503. }),
  504. ]);
  505. if (used.status === 401) {
  506. throw new Error(Locale.Error.Unauthorized);
  507. }
  508. if (!used.ok || !subs.ok) {
  509. throw new Error("Failed to query usage from openai");
  510. }
  511. const response = (await used.json()) as {
  512. total_usage?: number;
  513. error?: {
  514. type: string;
  515. message: string;
  516. };
  517. };
  518. const total = (await subs.json()) as {
  519. hard_limit_usd?: number;
  520. };
  521. if (response.error && response.error.type) {
  522. throw Error(response.error.message);
  523. }
  524. if (response.total_usage) {
  525. response.total_usage = Math.round(response.total_usage) / 100;
  526. }
  527. if (total.hard_limit_usd) {
  528. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  529. }
  530. return {
  531. used: response.total_usage,
  532. total: total.hard_limit_usd,
  533. } as LLMUsage;
  534. }
  535. async models(): Promise<LLMModel[]> {
  536. if (this.disableListModels) {
  537. return DEFAULT_MODELS.slice();
  538. }
  539. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  540. method: "GET",
  541. headers: {
  542. ...getHeaders(),
  543. },
  544. });
  545. const resJson = (await res.json()) as OpenAIListModelResponse;
  546. const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
  547. console.log("[Models]", chatModels);
  548. if (!chatModels) {
  549. return [];
  550. }
  551. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  552. let seq = 1000; //同 Constant.ts 中的排序保持一致
  553. return chatModels.map((m) => ({
  554. name: m.id,
  555. available: true,
  556. sorted: seq++,
  557. provider: {
  558. id: "openai",
  559. providerName: "OpenAI",
  560. providerType: "openai",
  561. sorted: 1,
  562. },
  563. }));
  564. }
  565. }
  566. export { OpenaiPath };