openai.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. REQUEST_TIMEOUT_MS_FOR_THINKING,
  12. } from "@/app/constant";
  13. import {
  14. ChatMessageTool,
  15. useAccessStore,
  16. useAppConfig,
  17. useChatStore,
  18. usePluginStore,
  19. } from "@/app/store";
  20. import { collectModelsWithDefaultModel } from "@/app/utils/model";
  21. import {
  22. preProcessImageContent,
  23. uploadImage,
  24. base64Image2Blob,
  25. stream,
  26. } from "@/app/utils/chat";
  27. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  28. import { ModelSize, DalleQuality, DalleStyle } from "@/app/typing";
  29. import {
  30. ChatOptions,
  31. getHeaders,
  32. LLMApi,
  33. LLMModel,
  34. LLMUsage,
  35. MultimodalContent,
  36. SpeechOptions,
  37. } from "../api";
  38. import Locale from "../../locales";
  39. import { getClientConfig } from "@/app/config/client";
  40. import {
  41. getMessageTextContent,
  42. isVisionModel,
  43. isDalle3 as _isDalle3,
  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. 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. // O1 使用 max_completion_tokens 控制token数 (https://platform.openai.com/docs/guides/reasoning#controlling-costs)
  216. if (isO1OrO3) {
  217. requestPayload["max_completion_tokens"] = modelConfig.max_tokens;
  218. }
  219. // add max_tokens to vision model
  220. if (visionModel) {
  221. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  222. }
  223. }
  224. console.log("[Request] openai payload: ", requestPayload);
  225. const shouldStream = !isDalle3 && !!options.config.stream;
  226. const controller = new AbortController();
  227. options.onController?.(controller);
  228. try {
  229. let chatPath = "";
  230. if (modelConfig.providerName === ServiceProvider.Azure) {
  231. // find model, and get displayName as deployName
  232. const { models: configModels, customModels: configCustomModels } =
  233. useAppConfig.getState();
  234. const {
  235. defaultModel,
  236. customModels: accessCustomModels,
  237. useCustomConfig,
  238. } = useAccessStore.getState();
  239. const models = collectModelsWithDefaultModel(
  240. configModels,
  241. [configCustomModels, accessCustomModels].join(","),
  242. defaultModel,
  243. );
  244. const model = models.find(
  245. (model) =>
  246. model.name === modelConfig.model &&
  247. model?.provider?.providerName === ServiceProvider.Azure,
  248. );
  249. chatPath = this.path(
  250. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  251. (model?.displayName ?? model?.name) as string,
  252. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  253. ),
  254. );
  255. } else {
  256. chatPath = this.path(
  257. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  258. );
  259. }
  260. if (shouldStream) {
  261. let index = -1;
  262. const [tools, funcs] = usePluginStore
  263. .getState()
  264. .getAsTools(
  265. useChatStore.getState().currentSession().mask?.plugin || [],
  266. );
  267. // console.log("getAsTools", tools, funcs);
  268. stream(
  269. chatPath,
  270. requestPayload,
  271. getHeaders(),
  272. tools as any,
  273. funcs,
  274. controller,
  275. // parseSSE
  276. (text: string, runTools: ChatMessageTool[]) => {
  277. // console.log("parseSSE", text, runTools);
  278. const json = JSON.parse(text);
  279. const choices = json.choices as Array<{
  280. delta: {
  281. content: string;
  282. tool_calls: ChatMessageTool[];
  283. };
  284. }>;
  285. const tool_calls = choices[0]?.delta?.tool_calls;
  286. if (tool_calls?.length > 0) {
  287. const id = tool_calls[0]?.id;
  288. const args = tool_calls[0]?.function?.arguments;
  289. if (id) {
  290. index += 1;
  291. runTools.push({
  292. id,
  293. type: tool_calls[0]?.type,
  294. function: {
  295. name: tool_calls[0]?.function?.name as string,
  296. arguments: args,
  297. },
  298. });
  299. } else {
  300. // @ts-ignore
  301. runTools[index]["function"]["arguments"] += args;
  302. }
  303. }
  304. return choices[0]?.delta?.content;
  305. },
  306. // processToolMessage, include tool_calls message and tool call results
  307. (
  308. requestPayload: RequestPayload,
  309. toolCallMessage: any,
  310. toolCallResult: any[],
  311. ) => {
  312. // reset index value
  313. index = -1;
  314. // @ts-ignore
  315. requestPayload?.messages?.splice(
  316. // @ts-ignore
  317. requestPayload?.messages?.length,
  318. 0,
  319. toolCallMessage,
  320. ...toolCallResult,
  321. );
  322. },
  323. options,
  324. );
  325. } else {
  326. const chatPayload = {
  327. method: "POST",
  328. body: JSON.stringify(requestPayload),
  329. signal: controller.signal,
  330. headers: getHeaders(),
  331. };
  332. // make a fetch request
  333. const requestTimeoutId = setTimeout(
  334. () => controller.abort(),
  335. isDalle3 || isO1OrO3
  336. ? REQUEST_TIMEOUT_MS_FOR_THINKING
  337. : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
  338. );
  339. const res = await fetch(chatPath, chatPayload);
  340. clearTimeout(requestTimeoutId);
  341. const resJson = await res.json();
  342. const message = await this.extractMessage(resJson);
  343. options.onFinish(message, res);
  344. }
  345. } catch (e) {
  346. console.log("[Request] failed to make a chat request", e);
  347. options.onError?.(e as Error);
  348. }
  349. }
  350. async usage() {
  351. const formatDate = (d: Date) =>
  352. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  353. .getDate()
  354. .toString()
  355. .padStart(2, "0")}`;
  356. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  357. const now = new Date();
  358. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  359. const startDate = formatDate(startOfMonth);
  360. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  361. const [used, subs] = await Promise.all([
  362. fetch(
  363. this.path(
  364. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  365. ),
  366. {
  367. method: "GET",
  368. headers: getHeaders(),
  369. },
  370. ),
  371. fetch(this.path(OpenaiPath.SubsPath), {
  372. method: "GET",
  373. headers: getHeaders(),
  374. }),
  375. ]);
  376. if (used.status === 401) {
  377. throw new Error(Locale.Error.Unauthorized);
  378. }
  379. if (!used.ok || !subs.ok) {
  380. throw new Error("Failed to query usage from openai");
  381. }
  382. const response = (await used.json()) as {
  383. total_usage?: number;
  384. error?: {
  385. type: string;
  386. message: string;
  387. };
  388. };
  389. const total = (await subs.json()) as {
  390. hard_limit_usd?: number;
  391. };
  392. if (response.error && response.error.type) {
  393. throw Error(response.error.message);
  394. }
  395. if (response.total_usage) {
  396. response.total_usage = Math.round(response.total_usage) / 100;
  397. }
  398. if (total.hard_limit_usd) {
  399. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  400. }
  401. return {
  402. used: response.total_usage,
  403. total: total.hard_limit_usd,
  404. } as LLMUsage;
  405. }
  406. async models(): Promise<LLMModel[]> {
  407. if (this.disableListModels) {
  408. return DEFAULT_MODELS.slice();
  409. }
  410. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  411. method: "GET",
  412. headers: {
  413. ...getHeaders(),
  414. },
  415. });
  416. const resJson = (await res.json()) as OpenAIListModelResponse;
  417. const chatModels = resJson.data?.filter(
  418. (m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
  419. );
  420. console.log("[Models]", chatModels);
  421. if (!chatModels) {
  422. return [];
  423. }
  424. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  425. let seq = 1000; //同 Constant.ts 中的排序保持一致
  426. return chatModels.map((m) => ({
  427. name: m.id,
  428. available: true,
  429. sorted: seq++,
  430. provider: {
  431. id: "openai",
  432. providerName: "OpenAI",
  433. providerType: "openai",
  434. sorted: 1,
  435. },
  436. }));
  437. }
  438. }
  439. export { OpenaiPath };