openai.ts 13 KB

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