openai.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. "use client";
  2. import {
  3. ApiPath,
  4. DEFAULT_API_HOST,
  5. DEFAULT_MODELS,
  6. OpenaiPath,
  7. REQUEST_TIMEOUT_MS,
  8. ServiceProvider,
  9. } from "@/app/constant";
  10. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  11. import {
  12. ChatOptions,
  13. getHeaders,
  14. LLMApi,
  15. LLMModel,
  16. LLMUsage,
  17. MultimodalContent,
  18. } from "../api";
  19. import Locale from "../../locales";
  20. import {
  21. EventStreamContentType,
  22. fetchEventSource,
  23. } from "@fortaine/fetch-event-source";
  24. import { prettyObject } from "@/app/utils/format";
  25. import { getClientConfig } from "@/app/config/client";
  26. import { makeAzurePath } from "@/app/azure";
  27. import {
  28. getMessageTextContent,
  29. getMessageImages,
  30. isVisionModel,
  31. } from "@/app/utils";
  32. export interface OpenAIListModelResponse {
  33. object: string;
  34. data: Array<{
  35. id: string;
  36. object: string;
  37. root: string;
  38. }>;
  39. }
  40. export class ChatGPTApi implements LLMApi {
  41. private disableListModels = true;
  42. path(path: string): string {
  43. const accessStore = useAccessStore.getState();
  44. const isAzure = accessStore.provider === ServiceProvider.Azure;
  45. if (isAzure && !accessStore.isValidAzure()) {
  46. throw Error(
  47. "incomplete azure config, please check it in your settings page",
  48. );
  49. }
  50. let baseUrl = isAzure ? accessStore.azureUrl : accessStore.openaiUrl;
  51. if (baseUrl.length === 0) {
  52. const isApp = !!getClientConfig()?.isApp;
  53. baseUrl = isApp
  54. ? DEFAULT_API_HOST + "/proxy" + ApiPath.OpenAI
  55. : ApiPath.OpenAI;
  56. }
  57. if (baseUrl.endsWith("/")) {
  58. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  59. }
  60. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.OpenAI)) {
  61. baseUrl = "https://" + baseUrl;
  62. }
  63. if (isAzure) {
  64. path = makeAzurePath(path, accessStore.azureApiVersion);
  65. }
  66. console.log("[Proxy Endpoint] ", baseUrl, path);
  67. return [baseUrl, path].join("/");
  68. }
  69. extractMessage(res: any) {
  70. return res.choices?.at(0)?.message?.content ?? "";
  71. }
  72. async chat(options: ChatOptions) {
  73. const visionModel = isVisionModel(options.config.model);
  74. const messages = options.messages.map((v) => ({
  75. role: v.role,
  76. content: visionModel ? v.content : getMessageTextContent(v),
  77. }));
  78. const modelConfig = {
  79. ...useAppConfig.getState().modelConfig,
  80. ...useChatStore.getState().currentSession().mask.modelConfig,
  81. ...{
  82. model: options.config.model,
  83. },
  84. };
  85. const requestPayload = {
  86. messages,
  87. stream: options.config.stream,
  88. model: modelConfig.model,
  89. temperature: modelConfig.temperature,
  90. presence_penalty: modelConfig.presence_penalty,
  91. frequency_penalty: modelConfig.frequency_penalty,
  92. top_p: modelConfig.top_p,
  93. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  94. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  95. };
  96. console.log("[Request] openai payload: ", requestPayload);
  97. const shouldStream = !!options.config.stream;
  98. const controller = new AbortController();
  99. options.onController?.(controller);
  100. try {
  101. const chatPath = this.path(OpenaiPath.ChatPath);
  102. const chatPayload = {
  103. method: "POST",
  104. body: JSON.stringify(requestPayload),
  105. signal: controller.signal,
  106. headers: getHeaders(),
  107. };
  108. // make a fetch request
  109. const requestTimeoutId = setTimeout(
  110. () => controller.abort(),
  111. REQUEST_TIMEOUT_MS,
  112. );
  113. if (shouldStream) {
  114. let responseText = "";
  115. let remainText = "";
  116. let finished = false;
  117. // animate response to make it looks smooth
  118. function animateResponseText() {
  119. if (finished || controller.signal.aborted) {
  120. responseText += remainText;
  121. console.log("[Response Animation] finished");
  122. return;
  123. }
  124. if (remainText.length > 0) {
  125. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  126. const fetchText = remainText.slice(0, fetchCount);
  127. responseText += fetchText;
  128. remainText = remainText.slice(fetchCount);
  129. options.onUpdate?.(responseText, fetchText);
  130. }
  131. requestAnimationFrame(animateResponseText);
  132. }
  133. // start animaion
  134. animateResponseText();
  135. const finish = () => {
  136. if (!finished) {
  137. finished = true;
  138. options.onFinish(responseText + remainText);
  139. }
  140. };
  141. controller.signal.onabort = finish;
  142. fetchEventSource(chatPath, {
  143. ...chatPayload,
  144. async onopen(res) {
  145. clearTimeout(requestTimeoutId);
  146. const contentType = res.headers.get("content-type");
  147. console.log(
  148. "[OpenAI] request response content type: ",
  149. contentType,
  150. );
  151. if (contentType?.startsWith("text/plain")) {
  152. responseText = await res.clone().text();
  153. return finish();
  154. }
  155. if (
  156. !res.ok ||
  157. !res.headers
  158. .get("content-type")
  159. ?.startsWith(EventStreamContentType) ||
  160. res.status !== 200
  161. ) {
  162. const responseTexts = [responseText];
  163. let extraInfo = await res.clone().text();
  164. try {
  165. const resJson = await res.clone().json();
  166. extraInfo = prettyObject(resJson);
  167. } catch {}
  168. if (res.status === 401) {
  169. responseTexts.push(Locale.Error.Unauthorized);
  170. }
  171. if (extraInfo) {
  172. responseTexts.push(extraInfo);
  173. }
  174. responseText = responseTexts.join("\n\n");
  175. return finish();
  176. }
  177. },
  178. onmessage(msg) {
  179. if (msg.data === "[DONE]" || finished) {
  180. return finish();
  181. }
  182. const text = msg.data;
  183. try {
  184. const json = JSON.parse(text) as {
  185. choices: Array<{
  186. delta: {
  187. content: string;
  188. };
  189. }>;
  190. };
  191. const delta = json.choices[0]?.delta?.content;
  192. if (delta) {
  193. remainText += delta;
  194. }
  195. } catch (e) {
  196. console.error("[Request] parse error", text);
  197. }
  198. },
  199. onclose() {
  200. finish();
  201. },
  202. onerror(e) {
  203. options.onError?.(e);
  204. throw e;
  205. },
  206. openWhenHidden: true,
  207. });
  208. } else {
  209. const res = await fetch(chatPath, chatPayload);
  210. clearTimeout(requestTimeoutId);
  211. const resJson = await res.json();
  212. const message = this.extractMessage(resJson);
  213. options.onFinish(message);
  214. }
  215. } catch (e) {
  216. console.log("[Request] failed to make a chat request", e);
  217. options.onError?.(e as Error);
  218. }
  219. }
  220. async usage() {
  221. const formatDate = (d: Date) =>
  222. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  223. .getDate()
  224. .toString()
  225. .padStart(2, "0")}`;
  226. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  227. const now = new Date();
  228. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  229. const startDate = formatDate(startOfMonth);
  230. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  231. const [used, subs] = await Promise.all([
  232. fetch(
  233. this.path(
  234. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  235. ),
  236. {
  237. method: "GET",
  238. headers: getHeaders(),
  239. },
  240. ),
  241. fetch(this.path(OpenaiPath.SubsPath), {
  242. method: "GET",
  243. headers: getHeaders(),
  244. }),
  245. ]);
  246. if (used.status === 401) {
  247. throw new Error(Locale.Error.Unauthorized);
  248. }
  249. if (!used.ok || !subs.ok) {
  250. throw new Error("Failed to query usage from openai");
  251. }
  252. const response = (await used.json()) as {
  253. total_usage?: number;
  254. error?: {
  255. type: string;
  256. message: string;
  257. };
  258. };
  259. const total = (await subs.json()) as {
  260. hard_limit_usd?: number;
  261. };
  262. if (response.error && response.error.type) {
  263. throw Error(response.error.message);
  264. }
  265. if (response.total_usage) {
  266. response.total_usage = Math.round(response.total_usage) / 100;
  267. }
  268. if (total.hard_limit_usd) {
  269. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  270. }
  271. return {
  272. used: response.total_usage,
  273. total: total.hard_limit_usd,
  274. } as LLMUsage;
  275. }
  276. async models(): Promise<LLMModel[]> {
  277. if (this.disableListModels) {
  278. return DEFAULT_MODELS.slice();
  279. }
  280. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  281. method: "GET",
  282. headers: {
  283. ...getHeaders(),
  284. },
  285. });
  286. const resJson = (await res.json()) as OpenAIListModelResponse;
  287. const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
  288. console.log("[Models]", chatModels);
  289. if (!chatModels) {
  290. return [];
  291. }
  292. return chatModels.map((m) => ({
  293. name: m.id,
  294. available: true,
  295. provider: {
  296. id: "openai",
  297. providerName: "OpenAI",
  298. providerType: "openai",
  299. },
  300. }));
  301. }
  302. }
  303. export { OpenaiPath };