openai.ts 6.4 KB

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