openai.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import {
  2. DEFAULT_API_HOST,
  3. OpenaiPath,
  4. REQUEST_TIMEOUT_MS,
  5. } from "@/app/constant";
  6. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  7. import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
  8. import Locale from "../../locales";
  9. import {
  10. EventStreamContentType,
  11. fetchEventSource,
  12. } from "@fortaine/fetch-event-source";
  13. import { prettyObject } from "@/app/utils/format";
  14. export interface OpenAIListModelResponse {
  15. object: string;
  16. data: Array<{
  17. id: string;
  18. object: string;
  19. root: string;
  20. }>;
  21. }
  22. export class ChatGPTApi implements LLMApi {
  23. path(path: string): string {
  24. let openaiUrl = useAccessStore.getState().openaiUrl;
  25. if (openaiUrl.length === 0) {
  26. openaiUrl = DEFAULT_API_HOST;
  27. }
  28. if (openaiUrl.endsWith("/")) {
  29. openaiUrl = openaiUrl.slice(0, openaiUrl.length - 1);
  30. }
  31. if (!openaiUrl.startsWith("http") && !openaiUrl.startsWith("/api/openai")) {
  32. openaiUrl = "https://" + openaiUrl;
  33. }
  34. return [openaiUrl, path].join("/");
  35. }
  36. extractMessage(res: any) {
  37. return res.choices?.at(0)?.message?.content ?? "";
  38. }
  39. async chat(options: ChatOptions) {
  40. const messages = options.messages.map((v) => ({
  41. role: v.role,
  42. content: v.content,
  43. }));
  44. const modelConfig = {
  45. ...useAppConfig.getState().modelConfig,
  46. ...useChatStore.getState().currentSession().mask.modelConfig,
  47. ...{
  48. model: options.config.model,
  49. },
  50. };
  51. const requestPayload = {
  52. messages,
  53. stream: options.config.stream,
  54. model: modelConfig.model,
  55. temperature: modelConfig.temperature,
  56. presence_penalty: modelConfig.presence_penalty,
  57. frequency_penalty: modelConfig.frequency_penalty,
  58. top_p: modelConfig.top_p,
  59. };
  60. console.log("[Request] openai payload: ", requestPayload);
  61. const shouldStream = !!options.config.stream;
  62. const controller = new AbortController();
  63. options.onController?.(controller);
  64. try {
  65. const chatPath = this.path(OpenaiPath.ChatPath);
  66. const chatPayload = {
  67. method: "POST",
  68. body: JSON.stringify(requestPayload),
  69. signal: controller.signal,
  70. headers: getHeaders(),
  71. };
  72. // make a fetch request
  73. const requestTimeoutId = setTimeout(
  74. () => controller.abort(),
  75. REQUEST_TIMEOUT_MS,
  76. );
  77. if (shouldStream) {
  78. let responseText = "";
  79. let finished = false;
  80. const finish = () => {
  81. if (!finished) {
  82. options.onFinish(responseText);
  83. finished = true;
  84. }
  85. };
  86. controller.signal.onabort = finish;
  87. fetchEventSource(chatPath, {
  88. ...chatPayload,
  89. async onopen(res) {
  90. clearTimeout(requestTimeoutId);
  91. const contentType = res.headers.get("content-type");
  92. console.log(
  93. "[OpenAI] request response content type: ",
  94. contentType,
  95. );
  96. if (contentType?.startsWith("text/plain")) {
  97. responseText = await res.clone().text();
  98. return finish();
  99. }
  100. if (
  101. !res.ok ||
  102. !res.headers
  103. .get("content-type")
  104. ?.startsWith(EventStreamContentType) ||
  105. res.status !== 200
  106. ) {
  107. const responseTexts = [responseText];
  108. let extraInfo = await res.clone().text();
  109. try {
  110. const resJson = await res.clone().json();
  111. extraInfo = prettyObject(resJson);
  112. } catch {}
  113. if (res.status === 401) {
  114. responseTexts.push(Locale.Error.Unauthorized);
  115. }
  116. if (extraInfo) {
  117. responseTexts.push(extraInfo);
  118. }
  119. responseText = responseTexts.join("\n\n");
  120. return finish();
  121. }
  122. },
  123. onmessage(msg) {
  124. if (msg.data === "[DONE]" || finished) {
  125. return finish();
  126. }
  127. const text = msg.data;
  128. try {
  129. const json = JSON.parse(text);
  130. const delta = json.choices[0].delta.content;
  131. if (delta) {
  132. responseText += delta;
  133. options.onUpdate?.(responseText, delta);
  134. }
  135. } catch (e) {
  136. console.error("[Request] parse error", text, msg);
  137. }
  138. },
  139. onclose() {
  140. finish();
  141. },
  142. onerror(e) {
  143. options.onError?.(e);
  144. throw e;
  145. },
  146. openWhenHidden: true,
  147. });
  148. } else {
  149. const res = await fetch(chatPath, chatPayload);
  150. clearTimeout(requestTimeoutId);
  151. const resJson = await res.json();
  152. const message = this.extractMessage(resJson);
  153. options.onFinish(message);
  154. }
  155. } catch (e) {
  156. console.log("[Request] failed to make a chat reqeust", e);
  157. options.onError?.(e as Error);
  158. }
  159. }
  160. async usage() {
  161. const formatDate = (d: Date) =>
  162. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  163. .getDate()
  164. .toString()
  165. .padStart(2, "0")}`;
  166. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  167. const now = new Date();
  168. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  169. const startDate = formatDate(startOfMonth);
  170. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  171. const [used, subs] = await Promise.all([
  172. fetch(
  173. this.path(
  174. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  175. ),
  176. {
  177. method: "GET",
  178. headers: getHeaders(),
  179. },
  180. ),
  181. fetch(this.path(OpenaiPath.SubsPath), {
  182. method: "GET",
  183. headers: getHeaders(),
  184. }),
  185. ]);
  186. if (used.status === 401) {
  187. throw new Error(Locale.Error.Unauthorized);
  188. }
  189. if (!used.ok || !subs.ok) {
  190. throw new Error("Failed to query usage from openai");
  191. }
  192. const response = (await used.json()) as {
  193. total_usage?: number;
  194. error?: {
  195. type: string;
  196. message: string;
  197. };
  198. };
  199. const total = (await subs.json()) as {
  200. hard_limit_usd?: number;
  201. };
  202. if (response.error && response.error.type) {
  203. throw Error(response.error.message);
  204. }
  205. if (response.total_usage) {
  206. response.total_usage = Math.round(response.total_usage) / 100;
  207. }
  208. if (total.hard_limit_usd) {
  209. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  210. }
  211. return {
  212. used: response.total_usage,
  213. total: total.hard_limit_usd,
  214. } as LLMUsage;
  215. }
  216. async models(): Promise<LLMModel[]> {
  217. const res = await fetch(this.path(OpenaiPath.ListModelPath), {
  218. method: "GET",
  219. headers: {
  220. ...getHeaders(),
  221. },
  222. });
  223. const resJson = (await res.json()) as OpenAIListModelResponse;
  224. const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
  225. console.log("[Models]", chatModels);
  226. return (
  227. chatModels?.map((m) => ({
  228. name: m.id,
  229. available: true,
  230. })) || []
  231. );
  232. }
  233. }
  234. export { OpenaiPath };