openai.ts 19 KB

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