openai.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. "use client";
  2. // azure and openai, using same models. so using same LLMApi.
  3. import {
  4. ApiPath,
  5. OPENAI_BASE_URL,
  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. usePluginStore,
  18. } from "@/app/store";
  19. import { collectModelsWithDefaultModel } from "@/app/utils/model";
  20. import {
  21. preProcessImageContent,
  22. uploadImage,
  23. base64Image2Blob,
  24. streamWithThink,
  25. } from "@/app/utils/chat";
  26. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  27. import { ModelSize, DalleQuality, DalleStyle } from "@/app/typing";
  28. import {
  29. ChatOptions,
  30. getHeaders,
  31. LLMApi,
  32. LLMModel,
  33. LLMUsage,
  34. MultimodalContent,
  35. SpeechOptions,
  36. } from "../api";
  37. import Locale from "../../locales";
  38. import { getClientConfig } from "@/app/config/client";
  39. import {
  40. getMessageTextContent,
  41. isVisionModel,
  42. isDalle3 as _isDalle3,
  43. getTimeoutMSByModel,
  44. } from "@/app/utils";
  45. import { fetch } from "@/app/utils/stream";
  46. export interface OpenAIListModelResponse {
  47. object: string;
  48. data: Array<{
  49. id: string;
  50. object: string;
  51. root: string;
  52. }>;
  53. }
  54. export interface RequestPayload {
  55. messages: {
  56. role: "developer" | "system" | "user" | "assistant";
  57. content: string | MultimodalContent[];
  58. }[];
  59. stream?: boolean;
  60. model: string;
  61. temperature: number;
  62. presence_penalty: number;
  63. frequency_penalty: number;
  64. top_p: number;
  65. max_tokens?: number;
  66. max_completion_tokens?: number;
  67. }
  68. export interface DalleRequestPayload {
  69. model: string;
  70. prompt: string;
  71. response_format: "url" | "b64_json";
  72. n: number;
  73. size: ModelSize;
  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 ? OPENAI_BASE_URL : 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 speech(options: SpeechOptions): Promise<ArrayBuffer> {
  134. const requestPayload = {
  135. model: options.model,
  136. input: options.input,
  137. voice: options.voice,
  138. response_format: options.response_format,
  139. speed: options.speed,
  140. };
  141. console.log("[Request] openai speech payload: ", requestPayload);
  142. const controller = new AbortController();
  143. options.onController?.(controller);
  144. try {
  145. const speechPath = this.path(OpenaiPath.SpeechPath);
  146. const speechPayload = {
  147. method: "POST",
  148. body: JSON.stringify(requestPayload),
  149. signal: controller.signal,
  150. headers: getHeaders(),
  151. };
  152. // make a fetch request
  153. const requestTimeoutId = setTimeout(
  154. () => controller.abort(),
  155. REQUEST_TIMEOUT_MS,
  156. );
  157. const res = await fetch(speechPath, speechPayload);
  158. clearTimeout(requestTimeoutId);
  159. return await res.arrayBuffer();
  160. } catch (e) {
  161. console.log("[Request] failed to make a speech request", e);
  162. throw e;
  163. }
  164. }
  165. async chat(options: ChatOptions) {
  166. const modelConfig = {
  167. ...useAppConfig.getState().modelConfig,
  168. ...useChatStore.getState().currentSession().mask.modelConfig,
  169. ...{
  170. model: options.config.model,
  171. providerName: options.config.providerName,
  172. },
  173. };
  174. let requestPayload: RequestPayload | DalleRequestPayload;
  175. const isDalle3 = _isDalle3(options.config.model);
  176. const isO1OrO3 =
  177. options.config.model.startsWith("o1") ||
  178. options.config.model.startsWith("o3");
  179. if (isDalle3) {
  180. const prompt = getMessageTextContent(
  181. options.messages.slice(-1)?.pop() as any,
  182. );
  183. requestPayload = {
  184. model: options.config.model,
  185. prompt,
  186. // URLs are only valid for 60 minutes after the image has been generated.
  187. response_format: "b64_json", // using b64_json, and save image in CacheStorage
  188. n: 1,
  189. size: options.config?.size ?? "1024x1024",
  190. quality: options.config?.quality ?? "standard",
  191. style: options.config?.style ?? "vivid",
  192. };
  193. } else {
  194. const visionModel = isVisionModel(options.config.model);
  195. const messages: ChatOptions["messages"] = [];
  196. for (const v of options.messages) {
  197. const content = visionModel
  198. ? await preProcessImageContent(v.content)
  199. : getMessageTextContent(v);
  200. if (!(isO1OrO3 && v.role === "system"))
  201. messages.push({ role: v.role, content });
  202. }
  203. // O1 not support image, tools (plugin in ChatGPTNextWeb) and system, stream, logprobs, temperature, top_p, n, presence_penalty, frequency_penalty yet.
  204. requestPayload = {
  205. messages,
  206. stream: options.config.stream,
  207. model: modelConfig.model,
  208. temperature: !isO1OrO3 ? modelConfig.temperature : 1,
  209. presence_penalty: !isO1OrO3 ? modelConfig.presence_penalty : 0,
  210. frequency_penalty: !isO1OrO3 ? modelConfig.frequency_penalty : 0,
  211. top_p: !isO1OrO3 ? modelConfig.top_p : 1,
  212. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  213. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  214. };
  215. if (isO1OrO3) {
  216. // by default the o1/o3 models will not attempt to produce output that includes markdown formatting
  217. // manually add "Formatting re-enabled" developer message to encourage markdown inclusion in model responses
  218. // (https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/reasoning?tabs=python-secure#markdown-output)
  219. requestPayload["messages"].unshift({
  220. role: "developer",
  221. content: "Formatting re-enabled",
  222. });
  223. // o1/o3 uses max_completion_tokens to control the number of tokens (https://platform.openai.com/docs/guides/reasoning#controlling-costs)
  224. requestPayload["max_completion_tokens"] = modelConfig.max_tokens;
  225. }
  226. // add max_tokens to vision model
  227. if (visionModel) {
  228. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  229. }
  230. }
  231. console.log("[Request] openai payload: ", requestPayload);
  232. const shouldStream = !isDalle3 && !!options.config.stream;
  233. const controller = new AbortController();
  234. options.onController?.(controller);
  235. try {
  236. let chatPath = "";
  237. if (modelConfig.providerName === ServiceProvider.Azure) {
  238. // find model, and get displayName as deployName
  239. const { models: configModels, customModels: configCustomModels } =
  240. useAppConfig.getState();
  241. const {
  242. defaultModel,
  243. customModels: accessCustomModels,
  244. useCustomConfig,
  245. } = useAccessStore.getState();
  246. const models = collectModelsWithDefaultModel(
  247. configModels,
  248. [configCustomModels, accessCustomModels].join(","),
  249. defaultModel,
  250. );
  251. const model = models.find(
  252. (model) =>
  253. model.name === modelConfig.model &&
  254. model?.provider?.providerName === ServiceProvider.Azure,
  255. );
  256. chatPath = this.path(
  257. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  258. (model?.displayName ?? model?.name) as string,
  259. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  260. ),
  261. );
  262. } else {
  263. chatPath = this.path(
  264. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  265. );
  266. }
  267. if (shouldStream) {
  268. let index = -1;
  269. const [tools, funcs] = usePluginStore
  270. .getState()
  271. .getAsTools(
  272. useChatStore.getState().currentSession().mask?.plugin || [],
  273. );
  274. // console.log("getAsTools", tools, funcs);
  275. streamWithThink(
  276. chatPath,
  277. requestPayload,
  278. getHeaders(),
  279. tools as any,
  280. funcs,
  281. controller,
  282. // parseSSE
  283. (text: string, runTools: ChatMessageTool[]) => {
  284. // console.log("parseSSE", text, runTools);
  285. const json = JSON.parse(text);
  286. const choices = json.choices as Array<{
  287. delta: {
  288. content: string;
  289. tool_calls: ChatMessageTool[];
  290. reasoning_content: string | null;
  291. };
  292. }>;
  293. if (!choices?.length) return { isThinking: false, content: "" };
  294. const tool_calls = choices[0]?.delta?.tool_calls;
  295. if (tool_calls?.length > 0) {
  296. const id = tool_calls[0]?.id;
  297. const args = tool_calls[0]?.function?.arguments;
  298. if (id) {
  299. index += 1;
  300. runTools.push({
  301. id,
  302. type: tool_calls[0]?.type,
  303. function: {
  304. name: tool_calls[0]?.function?.name as string,
  305. arguments: args,
  306. },
  307. });
  308. } else {
  309. // @ts-ignore
  310. runTools[index]["function"]["arguments"] += args;
  311. }
  312. }
  313. const reasoning = choices[0]?.delta?.reasoning_content;
  314. const content = choices[0]?.delta?.content;
  315. // Skip if both content and reasoning_content are empty or null
  316. if (
  317. (!reasoning || reasoning.length === 0) &&
  318. (!content || content.length === 0)
  319. ) {
  320. return {
  321. isThinking: false,
  322. content: "",
  323. };
  324. }
  325. if (reasoning && reasoning.length > 0) {
  326. return {
  327. isThinking: true,
  328. content: reasoning,
  329. };
  330. } else if (content && content.length > 0) {
  331. return {
  332. isThinking: false,
  333. content: content,
  334. };
  335. }
  336. return {
  337. isThinking: false,
  338. content: "",
  339. };
  340. },
  341. // processToolMessage, include tool_calls message and tool call results
  342. (
  343. requestPayload: RequestPayload,
  344. toolCallMessage: any,
  345. toolCallResult: any[],
  346. ) => {
  347. // reset index value
  348. index = -1;
  349. // @ts-ignore
  350. requestPayload?.messages?.splice(
  351. // @ts-ignore
  352. requestPayload?.messages?.length,
  353. 0,
  354. toolCallMessage,
  355. ...toolCallResult,
  356. );
  357. },
  358. options,
  359. );
  360. } else {
  361. const chatPayload = {
  362. method: "POST",
  363. body: JSON.stringify(requestPayload),
  364. signal: controller.signal,
  365. headers: getHeaders(),
  366. };
  367. // make a fetch request
  368. const requestTimeoutId = setTimeout(
  369. () => controller.abort(),
  370. getTimeoutMSByModel(options.config.model),
  371. );
  372. const res = await fetch(chatPath, chatPayload);
  373. clearTimeout(requestTimeoutId);
  374. const resJson = await res.json();
  375. const message = await this.extractMessage(resJson);
  376. options.onFinish(message, res);
  377. }
  378. } catch (e) {
  379. console.log("[Request] failed to make a chat request", e);
  380. options.onError?.(e as Error);
  381. }
  382. }
  383. async usage() {
  384. const formatDate = (d: Date) =>
  385. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  386. .getDate()
  387. .toString()
  388. .padStart(2, "0")}`;
  389. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  390. const now = new Date();
  391. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  392. const startDate = formatDate(startOfMonth);
  393. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  394. const [used, subs] = await Promise.all([
  395. fetch(
  396. this.path(
  397. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  398. ),
  399. {
  400. method: "GET",
  401. headers: getHeaders(),
  402. },
  403. ),
  404. fetch(this.path(OpenaiPath.SubsPath), {
  405. method: "GET",
  406. headers: getHeaders(),
  407. }),
  408. ]);
  409. if (used.status === 401) {
  410. throw new Error(Locale.Error.Unauthorized);
  411. }
  412. if (!used.ok || !subs.ok) {
  413. throw new Error("Failed to query usage from openai");
  414. }
  415. const response = (await used.json()) as {
  416. total_usage?: number;
  417. error?: {
  418. type: string;
  419. message: string;
  420. };
  421. };
  422. const total = (await subs.json()) as {
  423. hard_limit_usd?: number;
  424. };
  425. if (response.error && response.error.type) {
  426. throw Error(response.error.message);
  427. }
  428. if (response.total_usage) {
  429. response.total_usage = Math.round(response.total_usage) / 100;
  430. }
  431. if (total.hard_limit_usd) {
  432. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  433. }
  434. return {
  435. used: response.total_usage,
  436. total: total.hard_limit_usd,
  437. } as LLMUsage;
  438. }
  439. async models(): Promise<LLMModel[]> {
  440. if (this.disableListModels) {
  441. return DEFAULT_MODELS.slice();
  442. }
  443. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  444. method: "GET",
  445. headers: {
  446. ...getHeaders(),
  447. },
  448. });
  449. const resJson = (await res.json()) as OpenAIListModelResponse;
  450. const chatModels = resJson.data?.filter(
  451. (m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
  452. );
  453. console.log("[Models]", chatModels);
  454. if (!chatModels) {
  455. return [];
  456. }
  457. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  458. let seq = 1000; //同 Constant.ts 中的排序保持一致
  459. return chatModels.map((m) => ({
  460. name: m.id,
  461. available: true,
  462. sorted: seq++,
  463. provider: {
  464. id: "openai",
  465. providerName: "OpenAI",
  466. providerType: "openai",
  467. sorted: 1,
  468. },
  469. }));
  470. }
  471. }
  472. export { OpenaiPath };