openai.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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: "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. options.config.model.startsWith("o4-mini");
  180. if (isDalle3) {
  181. const prompt = getMessageTextContent(
  182. options.messages.slice(-1)?.pop() as any,
  183. );
  184. requestPayload = {
  185. model: options.config.model,
  186. prompt,
  187. // URLs are only valid for 60 minutes after the image has been generated.
  188. response_format: "b64_json", // using b64_json, and save image in CacheStorage
  189. n: 1,
  190. size: options.config?.size ?? "1024x1024",
  191. quality: options.config?.quality ?? "standard",
  192. style: options.config?.style ?? "vivid",
  193. };
  194. } else {
  195. const visionModel = isVisionModel(options.config.model);
  196. const messages: ChatOptions["messages"] = [];
  197. for (const v of options.messages) {
  198. const content = visionModel
  199. ? await preProcessImageContent(v.content)
  200. : getMessageTextContent(v);
  201. if (!(isO1OrO3 && v.role === "system"))
  202. messages.push({ role: v.role, content });
  203. }
  204. // O1 not support image, tools (plugin in ChatGPTNextWeb) and system, stream, logprobs, temperature, top_p, n, presence_penalty, frequency_penalty yet.
  205. requestPayload = {
  206. messages,
  207. stream: options.config.stream,
  208. model: modelConfig.model,
  209. temperature: !isO1OrO3 ? modelConfig.temperature : 1,
  210. presence_penalty: !isO1OrO3 ? modelConfig.presence_penalty : 0,
  211. frequency_penalty: !isO1OrO3 ? modelConfig.frequency_penalty : 0,
  212. top_p: !isO1OrO3 ? modelConfig.top_p : 1,
  213. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  214. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  215. };
  216. // O1 使用 max_completion_tokens 控制token数 (https://platform.openai.com/docs/guides/reasoning#controlling-costs)
  217. if (isO1OrO3) {
  218. requestPayload["max_completion_tokens"] = modelConfig.max_tokens;
  219. }
  220. // add max_tokens to vision model
  221. if (visionModel && !isO1OrO3) {
  222. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  223. }
  224. }
  225. console.log("[Request] openai payload: ", requestPayload);
  226. const shouldStream = !isDalle3 && !!options.config.stream;
  227. const controller = new AbortController();
  228. options.onController?.(controller);
  229. try {
  230. let chatPath = "";
  231. if (modelConfig.providerName === ServiceProvider.Azure) {
  232. // find model, and get displayName as deployName
  233. const { models: configModels, customModels: configCustomModels } =
  234. useAppConfig.getState();
  235. const {
  236. defaultModel,
  237. customModels: accessCustomModels,
  238. useCustomConfig,
  239. } = useAccessStore.getState();
  240. const models = collectModelsWithDefaultModel(
  241. configModels,
  242. [configCustomModels, accessCustomModels].join(","),
  243. defaultModel,
  244. );
  245. const model = models.find(
  246. (model) =>
  247. model.name === modelConfig.model &&
  248. model?.provider?.providerName === ServiceProvider.Azure,
  249. );
  250. chatPath = this.path(
  251. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  252. (model?.displayName ?? model?.name) as string,
  253. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  254. ),
  255. );
  256. } else {
  257. chatPath = this.path(
  258. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  259. );
  260. }
  261. if (shouldStream) {
  262. let index = -1;
  263. const [tools, funcs] = usePluginStore
  264. .getState()
  265. .getAsTools(
  266. useChatStore.getState().currentSession().mask?.plugin || [],
  267. );
  268. // console.log("getAsTools", tools, funcs);
  269. streamWithThink(
  270. chatPath,
  271. requestPayload,
  272. getHeaders(),
  273. tools as any,
  274. funcs,
  275. controller,
  276. // parseSSE
  277. (text: string, runTools: ChatMessageTool[]) => {
  278. // console.log("parseSSE", text, runTools);
  279. const json = JSON.parse(text);
  280. const choices = json.choices as Array<{
  281. delta: {
  282. content: string;
  283. tool_calls: ChatMessageTool[];
  284. reasoning_content: string | null;
  285. };
  286. }>;
  287. if (!choices?.length) return { isThinking: false, content: "" };
  288. const tool_calls = choices[0]?.delta?.tool_calls;
  289. if (tool_calls?.length > 0) {
  290. const id = tool_calls[0]?.id;
  291. const args = tool_calls[0]?.function?.arguments;
  292. if (id) {
  293. index += 1;
  294. runTools.push({
  295. id,
  296. type: tool_calls[0]?.type,
  297. function: {
  298. name: tool_calls[0]?.function?.name as string,
  299. arguments: args,
  300. },
  301. });
  302. } else {
  303. // @ts-ignore
  304. runTools[index]["function"]["arguments"] += args;
  305. }
  306. }
  307. const reasoning = choices[0]?.delta?.reasoning_content;
  308. const content = choices[0]?.delta?.content;
  309. // Skip if both content and reasoning_content are empty or null
  310. if (
  311. (!reasoning || reasoning.length === 0) &&
  312. (!content || content.length === 0)
  313. ) {
  314. return {
  315. isThinking: false,
  316. content: "",
  317. };
  318. }
  319. if (reasoning && reasoning.length > 0) {
  320. return {
  321. isThinking: true,
  322. content: reasoning,
  323. };
  324. } else if (content && content.length > 0) {
  325. return {
  326. isThinking: false,
  327. content: content,
  328. };
  329. }
  330. return {
  331. isThinking: false,
  332. content: "",
  333. };
  334. },
  335. // processToolMessage, include tool_calls message and tool call results
  336. (
  337. requestPayload: RequestPayload,
  338. toolCallMessage: any,
  339. toolCallResult: any[],
  340. ) => {
  341. // reset index value
  342. index = -1;
  343. // @ts-ignore
  344. requestPayload?.messages?.splice(
  345. // @ts-ignore
  346. requestPayload?.messages?.length,
  347. 0,
  348. toolCallMessage,
  349. ...toolCallResult,
  350. );
  351. },
  352. options,
  353. );
  354. } else {
  355. const chatPayload = {
  356. method: "POST",
  357. body: JSON.stringify(requestPayload),
  358. signal: controller.signal,
  359. headers: getHeaders(),
  360. };
  361. // make a fetch request
  362. const requestTimeoutId = setTimeout(
  363. () => controller.abort(),
  364. getTimeoutMSByModel(options.config.model),
  365. );
  366. const res = await fetch(chatPath, chatPayload);
  367. clearTimeout(requestTimeoutId);
  368. const resJson = await res.json();
  369. const message = await this.extractMessage(resJson);
  370. options.onFinish(message, res);
  371. }
  372. } catch (e) {
  373. console.log("[Request] failed to make a chat request", e);
  374. options.onError?.(e as Error);
  375. }
  376. }
  377. async usage() {
  378. const formatDate = (d: Date) =>
  379. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  380. .getDate()
  381. .toString()
  382. .padStart(2, "0")}`;
  383. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  384. const now = new Date();
  385. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  386. const startDate = formatDate(startOfMonth);
  387. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  388. const [used, subs] = await Promise.all([
  389. fetch(
  390. this.path(
  391. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  392. ),
  393. {
  394. method: "GET",
  395. headers: getHeaders(),
  396. },
  397. ),
  398. fetch(this.path(OpenaiPath.SubsPath), {
  399. method: "GET",
  400. headers: getHeaders(),
  401. }),
  402. ]);
  403. if (used.status === 401) {
  404. throw new Error(Locale.Error.Unauthorized);
  405. }
  406. if (!used.ok || !subs.ok) {
  407. throw new Error("Failed to query usage from openai");
  408. }
  409. const response = (await used.json()) as {
  410. total_usage?: number;
  411. error?: {
  412. type: string;
  413. message: string;
  414. };
  415. };
  416. const total = (await subs.json()) as {
  417. hard_limit_usd?: number;
  418. };
  419. if (response.error && response.error.type) {
  420. throw Error(response.error.message);
  421. }
  422. if (response.total_usage) {
  423. response.total_usage = Math.round(response.total_usage) / 100;
  424. }
  425. if (total.hard_limit_usd) {
  426. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  427. }
  428. return {
  429. used: response.total_usage,
  430. total: total.hard_limit_usd,
  431. } as LLMUsage;
  432. }
  433. async models(): Promise<LLMModel[]> {
  434. if (this.disableListModels) {
  435. return DEFAULT_MODELS.slice();
  436. }
  437. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  438. method: "GET",
  439. headers: {
  440. ...getHeaders(),
  441. },
  442. });
  443. const resJson = (await res.json()) as OpenAIListModelResponse;
  444. const chatModels = resJson.data?.filter(
  445. (m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
  446. );
  447. console.log("[Models]", chatModels);
  448. if (!chatModels) {
  449. return [];
  450. }
  451. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  452. let seq = 1000; //同 Constant.ts 中的排序保持一致
  453. return chatModels.map((m) => ({
  454. name: m.id,
  455. available: true,
  456. sorted: seq++,
  457. provider: {
  458. id: "openai",
  459. providerName: "OpenAI",
  460. providerType: "openai",
  461. sorted: 1,
  462. },
  463. }));
  464. }
  465. }
  466. export { OpenaiPath };