openai.ts 12 KB

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