openai.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. if (isDalle3) {
  147. const prompt = getMessageTextContent(
  148. options.messages.slice(-1)?.pop() as any,
  149. );
  150. requestPayload = {
  151. model: options.config.model,
  152. prompt,
  153. // URLs are only valid for 60 minutes after the image has been generated.
  154. response_format: "b64_json", // using b64_json, and save image in CacheStorage
  155. n: 1,
  156. size: options.config?.size ?? "1024x1024",
  157. quality: options.config?.quality ?? "standard",
  158. style: options.config?.style ?? "vivid",
  159. };
  160. } else {
  161. const visionModel = isVisionModel(options.config.model);
  162. const messages: ChatOptions["messages"] = [];
  163. for (const v of options.messages) {
  164. const content = visionModel
  165. ? await preProcessImageContent(v.content)
  166. : getMessageTextContent(v);
  167. messages.push({ role: v.role, content });
  168. }
  169. requestPayload = {
  170. messages,
  171. stream: options.config.stream,
  172. model: modelConfig.model,
  173. temperature: modelConfig.temperature,
  174. presence_penalty: modelConfig.presence_penalty,
  175. frequency_penalty: modelConfig.frequency_penalty,
  176. top_p: modelConfig.top_p,
  177. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  178. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  179. };
  180. // add max_tokens to vision model
  181. if (visionModel && modelConfig.model.includes("preview")) {
  182. requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
  183. }
  184. }
  185. console.log("[Request] openai payload: ", requestPayload);
  186. const shouldStream = !isDalle3 && !!options.config.stream;
  187. const controller = new AbortController();
  188. options.onController?.(controller);
  189. try {
  190. let chatPath = "";
  191. if (modelConfig.providerName === ServiceProvider.Azure) {
  192. // find model, and get displayName as deployName
  193. const { models: configModels, customModels: configCustomModels } =
  194. useAppConfig.getState();
  195. const {
  196. defaultModel,
  197. customModels: accessCustomModels,
  198. useCustomConfig,
  199. } = useAccessStore.getState();
  200. const models = collectModelsWithDefaultModel(
  201. configModels,
  202. [configCustomModels, accessCustomModels].join(","),
  203. defaultModel,
  204. );
  205. const model = models.find(
  206. (model) =>
  207. model.name === modelConfig.model &&
  208. model?.provider?.providerName === ServiceProvider.Azure,
  209. );
  210. chatPath = this.path(
  211. (isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
  212. (model?.displayName ?? model?.name) as string,
  213. useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
  214. ),
  215. );
  216. } else {
  217. chatPath = this.path(
  218. isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
  219. );
  220. }
  221. if (shouldStream) {
  222. const [tools, funcs] = usePluginStore
  223. .getState()
  224. .getAsTools(
  225. useChatStore.getState().currentSession().mask?.plugin as string[],
  226. );
  227. // console.log("getAsTools", tools, funcs);
  228. stream(
  229. chatPath,
  230. requestPayload,
  231. getHeaders(),
  232. tools as any,
  233. funcs,
  234. controller,
  235. // parseSSE
  236. (text: string, runTools: ChatMessageTool[]) => {
  237. // console.log("parseSSE", text, runTools);
  238. const json = JSON.parse(text);
  239. const choices = json.choices as Array<{
  240. delta: {
  241. content: string;
  242. tool_calls: ChatMessageTool[];
  243. };
  244. }>;
  245. const tool_calls = choices[0]?.delta?.tool_calls;
  246. if (tool_calls?.length > 0) {
  247. const index = tool_calls[0]?.index;
  248. const id = tool_calls[0]?.id;
  249. const args = tool_calls[0]?.function?.arguments;
  250. if (id) {
  251. runTools.push({
  252. id,
  253. type: tool_calls[0]?.type,
  254. function: {
  255. name: tool_calls[0]?.function?.name as string,
  256. arguments: args,
  257. },
  258. });
  259. } else {
  260. // @ts-ignore
  261. runTools[index]["function"]["arguments"] += args;
  262. }
  263. }
  264. return choices[0]?.delta?.content;
  265. },
  266. // processToolMessage, include tool_calls message and tool call results
  267. (
  268. requestPayload: RequestPayload,
  269. toolCallMessage: any,
  270. toolCallResult: any[],
  271. ) => {
  272. // @ts-ignore
  273. requestPayload?.messages?.splice(
  274. // @ts-ignore
  275. requestPayload?.messages?.length,
  276. 0,
  277. toolCallMessage,
  278. ...toolCallResult,
  279. );
  280. },
  281. options,
  282. );
  283. } else {
  284. const chatPayload = {
  285. method: "POST",
  286. body: JSON.stringify(requestPayload),
  287. signal: controller.signal,
  288. headers: getHeaders(),
  289. };
  290. // make a fetch request
  291. const requestTimeoutId = setTimeout(
  292. () => controller.abort(),
  293. isDalle3 ? REQUEST_TIMEOUT_MS * 2 : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
  294. );
  295. const res = await fetch(chatPath, chatPayload);
  296. clearTimeout(requestTimeoutId);
  297. const resJson = await res.json();
  298. const message = await this.extractMessage(resJson);
  299. options.onFinish(message);
  300. }
  301. } catch (e) {
  302. console.log("[Request] failed to make a chat request", e);
  303. options.onError?.(e as Error);
  304. }
  305. }
  306. async usage() {
  307. const formatDate = (d: Date) =>
  308. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  309. .getDate()
  310. .toString()
  311. .padStart(2, "0")}`;
  312. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  313. const now = new Date();
  314. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  315. const startDate = formatDate(startOfMonth);
  316. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  317. const [used, subs] = await Promise.all([
  318. fetch(
  319. this.path(
  320. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  321. ),
  322. {
  323. method: "GET",
  324. headers: getHeaders(),
  325. },
  326. ),
  327. fetch(this.path(OpenaiPath.SubsPath), {
  328. method: "GET",
  329. headers: getHeaders(),
  330. }),
  331. ]);
  332. if (used.status === 401) {
  333. throw new Error(Locale.Error.Unauthorized);
  334. }
  335. if (!used.ok || !subs.ok) {
  336. throw new Error("Failed to query usage from openai");
  337. }
  338. const response = (await used.json()) as {
  339. total_usage?: number;
  340. error?: {
  341. type: string;
  342. message: string;
  343. };
  344. };
  345. const total = (await subs.json()) as {
  346. hard_limit_usd?: number;
  347. };
  348. if (response.error && response.error.type) {
  349. throw Error(response.error.message);
  350. }
  351. if (response.total_usage) {
  352. response.total_usage = Math.round(response.total_usage) / 100;
  353. }
  354. if (total.hard_limit_usd) {
  355. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  356. }
  357. return {
  358. used: response.total_usage,
  359. total: total.hard_limit_usd,
  360. } as LLMUsage;
  361. }
  362. async models(): Promise<LLMModel[]> {
  363. if (this.disableListModels) {
  364. return DEFAULT_MODELS.slice();
  365. }
  366. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  367. method: "GET",
  368. headers: {
  369. ...getHeaders(),
  370. },
  371. });
  372. const resJson = (await res.json()) as OpenAIListModelResponse;
  373. const chatModels = resJson.data?.filter(
  374. (m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
  375. );
  376. console.log("[Models]", chatModels);
  377. if (!chatModels) {
  378. return [];
  379. }
  380. //由于目前 OpenAI 的 disableListModels 默认为 true,所以当前实际不会运行到这场
  381. let seq = 1000; //同 Constant.ts 中的排序保持一致
  382. return chatModels.map((m) => ({
  383. name: m.id,
  384. available: true,
  385. sorted: seq++,
  386. provider: {
  387. id: "openai",
  388. providerName: "OpenAI",
  389. providerType: "openai",
  390. sorted: 1,
  391. },
  392. }));
  393. }
  394. }
  395. export { OpenaiPath };