openai.ts 13 KB

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