openai.ts 9.1 KB

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