openai.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 new Promise((resolve) => {
  262. setTimeout(() => resolve("30"), 3000);
  263. });
  264. },
  265. };
  266. const finish = () => {
  267. if (!finished) {
  268. console.log("try run tools", runTools.length, finished, running);
  269. if (!running && runTools.length > 0) {
  270. const toolCallMessage = {
  271. role: "assistant",
  272. tool_calls: [...runTools],
  273. };
  274. running = true;
  275. runTools.splice(0, runTools.length); // empty runTools
  276. return Promise.all(
  277. toolCallMessage.tool_calls.map((tool) => {
  278. options?.onBeforeTool?.(tool);
  279. return Promise.resolve(
  280. // @ts-ignore
  281. funcs[tool.function.name](
  282. // @ts-ignore
  283. JSON.parse(tool.function.arguments),
  284. ),
  285. )
  286. .then((content) => {
  287. options?.onAfterTool?.({
  288. ...tool,
  289. content,
  290. isError: false,
  291. });
  292. return content;
  293. })
  294. .catch((e) => {
  295. options?.onAfterTool?.({ ...tool, isError: true });
  296. return e.toString();
  297. })
  298. .then((content) => ({
  299. role: "tool",
  300. content,
  301. tool_call_id: tool.id,
  302. }));
  303. }),
  304. ).then((toolCallResult) => {
  305. console.log("end runTools", toolCallMessage, toolCallResult);
  306. // @ts-ignore
  307. requestPayload?.messages?.splice(
  308. // @ts-ignore
  309. requestPayload?.messages?.length,
  310. 0,
  311. toolCallMessage,
  312. ...toolCallResult,
  313. );
  314. setTimeout(() => {
  315. // call again
  316. console.log("start again");
  317. running = false;
  318. chatApi(chatPath, requestPayload as RequestPayload); // call fetchEventSource
  319. }, 60);
  320. });
  321. console.log("try run tools", runTools.length, finished);
  322. return;
  323. }
  324. if (running) {
  325. return;
  326. }
  327. finished = true;
  328. options.onFinish(responseText + remainText);
  329. }
  330. };
  331. controller.signal.onabort = finish;
  332. function chatApi(chatPath: string, requestPayload: RequestPayload) {
  333. const chatPayload = {
  334. method: "POST",
  335. body: JSON.stringify({
  336. ...requestPayload,
  337. // TODO 这里暂时写死的,后面从store.tools中按照当前session中选择的获取
  338. tools: [
  339. {
  340. type: "function",
  341. function: {
  342. name: "get_current_weather",
  343. description: "Get the current weather",
  344. parameters: {
  345. type: "object",
  346. properties: {
  347. location: {
  348. type: "string",
  349. description:
  350. "The city and country, eg. San Francisco, USA",
  351. },
  352. format: {
  353. type: "string",
  354. enum: ["celsius", "fahrenheit"],
  355. },
  356. },
  357. required: ["location", "format"],
  358. },
  359. },
  360. },
  361. ],
  362. }),
  363. signal: controller.signal,
  364. headers: getHeaders(),
  365. };
  366. console.log("chatApi", chatPath, requestPayload, chatPayload);
  367. fetchEventSource(chatPath, {
  368. ...chatPayload,
  369. async onopen(res) {
  370. clearTimeout(requestTimeoutId);
  371. const contentType = res.headers.get("content-type");
  372. console.log(
  373. "[OpenAI] request response content type: ",
  374. contentType,
  375. );
  376. if (contentType?.startsWith("text/plain")) {
  377. responseText = await res.clone().text();
  378. return finish();
  379. }
  380. if (
  381. !res.ok ||
  382. !res.headers
  383. .get("content-type")
  384. ?.startsWith(EventStreamContentType) ||
  385. res.status !== 200
  386. ) {
  387. const responseTexts = [responseText];
  388. let extraInfo = await res.clone().text();
  389. try {
  390. const resJson = await res.clone().json();
  391. extraInfo = prettyObject(resJson);
  392. } catch {}
  393. if (res.status === 401) {
  394. responseTexts.push(Locale.Error.Unauthorized);
  395. }
  396. if (extraInfo) {
  397. responseTexts.push(extraInfo);
  398. }
  399. responseText = responseTexts.join("\n\n");
  400. return finish();
  401. }
  402. },
  403. onmessage(msg) {
  404. if (msg.data === "[DONE]" || finished) {
  405. return finish();
  406. }
  407. const text = msg.data;
  408. try {
  409. const json = JSON.parse(text);
  410. const choices = json.choices as Array<{
  411. delta: {
  412. content: string;
  413. tool_calls: ChatMessageTool[];
  414. };
  415. }>;
  416. console.log("choices", choices);
  417. const delta = choices[0]?.delta?.content;
  418. const tool_calls = choices[0]?.delta?.tool_calls;
  419. const textmoderation = json?.prompt_filter_results;
  420. if (delta) {
  421. remainText += delta;
  422. }
  423. if (tool_calls?.length > 0) {
  424. const index = tool_calls[0]?.index;
  425. const id = tool_calls[0]?.id;
  426. const args = tool_calls[0]?.function?.arguments;
  427. if (id) {
  428. runTools.push({
  429. id,
  430. type: tool_calls[0]?.type,
  431. function: {
  432. name: tool_calls[0]?.function?.name as string,
  433. arguments: args,
  434. },
  435. });
  436. } else {
  437. // @ts-ignore
  438. runTools[index]["function"]["arguments"] += args;
  439. }
  440. }
  441. console.log("runTools", runTools);
  442. if (
  443. textmoderation &&
  444. textmoderation.length > 0 &&
  445. ServiceProvider.Azure
  446. ) {
  447. const contentFilterResults =
  448. textmoderation[0]?.content_filter_results;
  449. console.log(
  450. `[${ServiceProvider.Azure}] [Text Moderation] flagged categories result:`,
  451. contentFilterResults,
  452. );
  453. }
  454. } catch (e) {
  455. console.error("[Request] parse error", text, msg);
  456. }
  457. },
  458. onclose() {
  459. finish();
  460. },
  461. onerror(e) {
  462. options.onError?.(e);
  463. throw e;
  464. },
  465. openWhenHidden: true,
  466. });
  467. }
  468. chatApi(chatPath, requestPayload as RequestPayload); // call fetchEventSource
  469. } else {
  470. const res = await fetch(chatPath, chatPayload);
  471. clearTimeout(requestTimeoutId);
  472. const resJson = await res.json();
  473. const message = await this.extractMessage(resJson);
  474. options.onFinish(message);
  475. }
  476. } catch (e) {
  477. console.log("[Request] failed to make a chat request", e);
  478. options.onError?.(e as Error);
  479. }
  480. }
  481. async usage() {
  482. const formatDate = (d: Date) =>
  483. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  484. .getDate()
  485. .toString()
  486. .padStart(2, "0")}`;
  487. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  488. const now = new Date();
  489. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  490. const startDate = formatDate(startOfMonth);
  491. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  492. const [used, subs] = await Promise.all([
  493. fetch(
  494. this.path(
  495. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  496. ),
  497. {
  498. method: "GET",
  499. headers: getHeaders(),
  500. },
  501. ),
  502. fetch(this.path(OpenaiPath.SubsPath), {
  503. method: "GET",
  504. headers: getHeaders(),
  505. }),
  506. ]);
  507. if (used.status === 401) {
  508. throw new Error(Locale.Error.Unauthorized);
  509. }
  510. if (!used.ok || !subs.ok) {
  511. throw new Error("Failed to query usage from openai");
  512. }
  513. const response = (await used.json()) as {
  514. total_usage?: number;
  515. error?: {
  516. type: string;
  517. message: string;
  518. };
  519. };
  520. const total = (await subs.json()) as {
  521. hard_limit_usd?: number;
  522. };
  523. if (response.error && response.error.type) {
  524. throw Error(response.error.message);
  525. }
  526. if (response.total_usage) {
  527. response.total_usage = Math.round(response.total_usage) / 100;
  528. }
  529. if (total.hard_limit_usd) {
  530. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  531. }
  532. return {
  533. used: response.total_usage,
  534. total: total.hard_limit_usd,
  535. } as LLMUsage;
  536. }
  537. async models(): Promise<LLMModel[]> {
  538. if (this.disableListModels) {
  539. return DEFAULT_MODELS.slice();
  540. }
  541. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  542. method: "GET",
  543. headers: {
  544. ...getHeaders(),
  545. },
  546. });
  547. const resJson = (await res.json()) as OpenAIListModelResponse;
  548. const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
  549. console.log("[Models]", chatModels);
  550. if (!chatModels) {
  551. return [];
  552. }
  553. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  554. let seq = 1000; //同 Constant.ts 中的排序保持一致
  555. return chatModels.map((m) => ({
  556. name: m.id,
  557. available: true,
  558. sorted: seq++,
  559. provider: {
  560. id: "openai",
  561. providerName: "OpenAI",
  562. providerType: "openai",
  563. sorted: 1,
  564. },
  565. }));
  566. }
  567. }
  568. export { OpenaiPath };