openai.ts 12 KB

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