openai.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. usePluginStore,
  18. } from "@/app/store";
  19. import { collectModelsWithDefaultModel } from "@/app/utils/model";
  20. import {
  21. preProcessImageContent,
  22. uploadImage,
  23. base64Image2Blob,
  24. stream,
  25. } from "@/app/utils/chat";
  26. import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
  27. import { DalleSize, 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. } from "@/app/utils";
  44. export interface OpenAIListModelResponse {
  45. object: string;
  46. data: Array<{
  47. id: string;
  48. object: string;
  49. root: string;
  50. }>;
  51. }
  52. export interface RequestPayload {
  53. messages: {
  54. role: "system" | "user" | "assistant";
  55. content: string | MultimodalContent[];
  56. }[];
  57. stream?: boolean;
  58. model: string;
  59. temperature: number;
  60. presence_penalty: number;
  61. frequency_penalty: number;
  62. top_p: number;
  63. max_tokens?: number;
  64. }
  65. export interface DalleRequestPayload {
  66. model: string;
  67. prompt: string;
  68. response_format: "url" | "b64_json";
  69. n: number;
  70. size: DalleSize;
  71. quality: DalleQuality;
  72. style: DalleStyle;
  73. }
  74. export class ChatGPTApi implements LLMApi {
  75. private disableListModels = true;
  76. path(path: string): string {
  77. const accessStore = useAccessStore.getState();
  78. let baseUrl = "";
  79. const isAzure = path.includes("deployments");
  80. if (accessStore.useCustomConfig) {
  81. if (isAzure && !accessStore.isValidAzure()) {
  82. throw Error(
  83. "incomplete azure config, please check it in your settings page",
  84. );
  85. }
  86. baseUrl = isAzure ? accessStore.azureUrl : accessStore.openaiUrl;
  87. }
  88. if (baseUrl.length === 0) {
  89. const isApp = !!getClientConfig()?.isApp;
  90. const apiPath = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
  91. baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
  92. }
  93. if (baseUrl.endsWith("/")) {
  94. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  95. }
  96. if (
  97. !baseUrl.startsWith("http") &&
  98. !isAzure &&
  99. !baseUrl.startsWith(ApiPath.OpenAI)
  100. ) {
  101. baseUrl = "https://" + baseUrl;
  102. }
  103. console.log("[Proxy Endpoint] ", baseUrl, path);
  104. // try rebuild url, when using cloudflare ai gateway in client
  105. return cloudflareAIGatewayUrl([baseUrl, path].join("/"));
  106. }
  107. async extractMessage(res: any) {
  108. if (res.error) {
  109. return "```\n" + JSON.stringify(res, null, 4) + "\n```";
  110. }
  111. // dalle3 model return url, using url create image message
  112. if (res.data) {
  113. let url = res.data?.at(0)?.url ?? "";
  114. const b64_json = res.data?.at(0)?.b64_json ?? "";
  115. if (!url && b64_json) {
  116. // uploadImage
  117. url = await uploadImage(base64Image2Blob(b64_json, "image/png"));
  118. }
  119. return [
  120. {
  121. type: "image_url",
  122. image_url: {
  123. url,
  124. },
  125. },
  126. ];
  127. }
  128. return res.choices?.at(0)?.message?.content ?? res;
  129. }
  130. async speech(options: SpeechOptions): Promise<ArrayBuffer> {
  131. const requestPayload = {
  132. model: options.model,
  133. input: options.input,
  134. voice: options.voice,
  135. response_format: options.response_format,
  136. speed: options.speed,
  137. };
  138. console.log("[Request] openai speech payload: ", requestPayload);
  139. const controller = new AbortController();
  140. options.onController?.(controller);
  141. try {
  142. const speechPath = this.path(OpenaiPath.SpeechPath);
  143. const speechPayload = {
  144. method: "POST",
  145. body: JSON.stringify(requestPayload),
  146. signal: controller.signal,
  147. headers: getHeaders(),
  148. };
  149. // make a fetch request
  150. const requestTimeoutId = setTimeout(
  151. () => controller.abort(),
  152. REQUEST_TIMEOUT_MS,
  153. );
  154. const res = await fetch(speechPath, speechPayload);
  155. clearTimeout(requestTimeoutId);
  156. return await res.arrayBuffer();
  157. } catch (e) {
  158. console.log("[Request] failed to make a speech request", e);
  159. throw e;
  160. }
  161. }
  162. async chat(options: ChatOptions) {
  163. const modelConfig = {
  164. ...useAppConfig.getState().modelConfig,
  165. ...useChatStore.getState().currentSession().mask.modelConfig,
  166. ...{
  167. model: options.config.model,
  168. providerName: options.config.providerName,
  169. },
  170. };
  171. let requestPayload: RequestPayload | DalleRequestPayload;
  172. const isDalle3 = _isDalle3(options.config.model);
  173. const isO1 = options.config.model.startsWith("o1");
  174. if (isDalle3) {
  175. const prompt = getMessageTextContent(
  176. options.messages.slice(-1)?.pop() as any,
  177. );
  178. requestPayload = {
  179. model: options.config.model,
  180. prompt,
  181. // URLs are only valid for 60 minutes after the image has been generated.
  182. response_format: "b64_json", // using b64_json, and save image in CacheStorage
  183. n: 1,
  184. size: options.config?.size ?? "1024x1024",
  185. quality: options.config?.quality ?? "standard",
  186. style: options.config?.style ?? "vivid",
  187. };
  188. } else {
  189. const visionModel = isVisionModel(options.config.model);
  190. const messages: ChatOptions["messages"] = [];
  191. for (const v of options.messages) {
  192. const content = visionModel
  193. ? await preProcessImageContent(v.content)
  194. : getMessageTextContent(v);
  195. if (!(isO1 && v.role === "system"))
  196. messages.push({ role: v.role, content });
  197. }
  198. // O1 not support image, tools (plugin in ChatGPTNextWeb) and system, stream, logprobs, temperature, top_p, n, presence_penalty, frequency_penalty yet.
  199. requestPayload = {
  200. messages,
  201. stream: !isO1 ? options.config.stream : false,
  202. model: modelConfig.model,
  203. temperature: !isO1 ? modelConfig.temperature : 1,
  204. presence_penalty: !isO1 ? modelConfig.presence_penalty : 0,
  205. frequency_penalty: !isO1 ? modelConfig.frequency_penalty : 0,
  206. top_p: !isO1 ? modelConfig.top_p : 1,
  207. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  208. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  209. };
  210. // add max_tokens to vision model
  211. if (visionModel) {
  212. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  213. }
  214. }
  215. console.log("[Request] openai payload: ", requestPayload);
  216. const shouldStream = !isDalle3 && !!options.config.stream && !isO1;
  217. const controller = new AbortController();
  218. options.onController?.(controller);
  219. try {
  220. let chatPath = "";
  221. if (modelConfig.providerName === ServiceProvider.Azure) {
  222. // find model, and get displayName as deployName
  223. const { models: configModels, customModels: configCustomModels } =
  224. useAppConfig.getState();
  225. const {
  226. defaultModel,
  227. customModels: accessCustomModels,
  228. useCustomConfig,
  229. } = useAccessStore.getState();
  230. const models = collectModelsWithDefaultModel(
  231. configModels,
  232. [configCustomModels, accessCustomModels].join(","),
  233. defaultModel,
  234. );
  235. const model = models.find(
  236. (model) =>
  237. model.name === modelConfig.model &&
  238. model?.provider?.providerName === ServiceProvider.Azure,
  239. );
  240. chatPath = this.path(
  241. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  242. (model?.displayName ?? model?.name) as string,
  243. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  244. ),
  245. );
  246. } else {
  247. chatPath = this.path(
  248. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  249. );
  250. }
  251. if (shouldStream) {
  252. let index = -1;
  253. const [tools, funcs] = usePluginStore
  254. .getState()
  255. .getAsTools(
  256. useChatStore.getState().currentSession().mask?.plugin || [],
  257. );
  258. // console.log("getAsTools", tools, funcs);
  259. stream(
  260. chatPath,
  261. requestPayload,
  262. getHeaders(),
  263. tools as any,
  264. funcs,
  265. controller,
  266. // parseSSE
  267. (text: string, runTools: ChatMessageTool[]) => {
  268. // console.log("parseSSE", text, runTools);
  269. const json = JSON.parse(text);
  270. const choices = json.choices as Array<{
  271. delta: {
  272. content: string;
  273. tool_calls: ChatMessageTool[];
  274. };
  275. }>;
  276. const tool_calls = choices[0]?.delta?.tool_calls;
  277. if (tool_calls?.length > 0) {
  278. const id = tool_calls[0]?.id;
  279. const args = tool_calls[0]?.function?.arguments;
  280. if (id) {
  281. index += 1;
  282. runTools.push({
  283. id,
  284. type: tool_calls[0]?.type,
  285. function: {
  286. name: tool_calls[0]?.function?.name as string,
  287. arguments: args,
  288. },
  289. });
  290. } else {
  291. // @ts-ignore
  292. runTools[index]["function"]["arguments"] += args;
  293. }
  294. }
  295. return choices[0]?.delta?.content;
  296. },
  297. // processToolMessage, include tool_calls message and tool call results
  298. (
  299. requestPayload: RequestPayload,
  300. toolCallMessage: any,
  301. toolCallResult: any[],
  302. ) => {
  303. // reset index value
  304. index = -1;
  305. // @ts-ignore
  306. requestPayload?.messages?.splice(
  307. // @ts-ignore
  308. requestPayload?.messages?.length,
  309. 0,
  310. toolCallMessage,
  311. ...toolCallResult,
  312. );
  313. },
  314. options,
  315. );
  316. } else {
  317. const chatPayload = {
  318. method: "POST",
  319. body: JSON.stringify(requestPayload),
  320. signal: controller.signal,
  321. headers: getHeaders(),
  322. };
  323. // make a fetch request
  324. const requestTimeoutId = setTimeout(
  325. () => controller.abort(),
  326. isDalle3 || isO1 ? REQUEST_TIMEOUT_MS * 2 : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
  327. );
  328. const res = await fetch(chatPath, chatPayload);
  329. clearTimeout(requestTimeoutId);
  330. const resJson = await res.json();
  331. const message = await this.extractMessage(resJson);
  332. options.onFinish(message);
  333. }
  334. } catch (e) {
  335. console.log("[Request] failed to make a chat request", e);
  336. options.onError?.(e as Error);
  337. }
  338. }
  339. async usage() {
  340. const formatDate = (d: Date) =>
  341. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  342. .getDate()
  343. .toString()
  344. .padStart(2, "0")}`;
  345. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  346. const now = new Date();
  347. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  348. const startDate = formatDate(startOfMonth);
  349. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  350. const [used, subs] = await Promise.all([
  351. fetch(
  352. this.path(
  353. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  354. ),
  355. {
  356. method: "GET",
  357. headers: getHeaders(),
  358. },
  359. ),
  360. fetch(this.path(OpenaiPath.SubsPath), {
  361. method: "GET",
  362. headers: getHeaders(),
  363. }),
  364. ]);
  365. if (used.status === 401) {
  366. throw new Error(Locale.Error.Unauthorized);
  367. }
  368. if (!used.ok || !subs.ok) {
  369. throw new Error("Failed to query usage from openai");
  370. }
  371. const response = (await used.json()) as {
  372. total_usage?: number;
  373. error?: {
  374. type: string;
  375. message: string;
  376. };
  377. };
  378. const total = (await subs.json()) as {
  379. hard_limit_usd?: number;
  380. };
  381. if (response.error && response.error.type) {
  382. throw Error(response.error.message);
  383. }
  384. if (response.total_usage) {
  385. response.total_usage = Math.round(response.total_usage) / 100;
  386. }
  387. if (total.hard_limit_usd) {
  388. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  389. }
  390. return {
  391. used: response.total_usage,
  392. total: total.hard_limit_usd,
  393. } as LLMUsage;
  394. }
  395. async models(): Promise<LLMModel[]> {
  396. if (this.disableListModels) {
  397. return DEFAULT_MODELS.slice();
  398. }
  399. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  400. method: "GET",
  401. headers: {
  402. ...getHeaders(),
  403. },
  404. });
  405. const resJson = (await res.json()) as OpenAIListModelResponse;
  406. const chatModels = resJson.data?.filter(
  407. (m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
  408. );
  409. console.log("[Models]", chatModels);
  410. if (!chatModels) {
  411. return [];
  412. }
  413. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  414. let seq = 1000; //同 Constant.ts 中的排序保持一致
  415. return chatModels.map((m) => ({
  416. name: m.id,
  417. available: true,
  418. sorted: seq++,
  419. provider: {
  420. id: "openai",
  421. providerName: "OpenAI",
  422. providerType: "openai",
  423. sorted: 1,
  424. },
  425. }));
  426. }
  427. }
  428. export { OpenaiPath };