openai.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import { REQUEST_TIMEOUT_MS } from "@/app/constant";
  2. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  3. import { ChatOptions, getHeaders, LLMApi, LLMUsage } from "../api";
  4. import Locale from "../../locales";
  5. import { fetchEventSource } from "@microsoft/fetch-event-source";
  6. export class ChatGPTApi implements LLMApi {
  7. public ChatPath = "v1/chat/completions";
  8. public UsagePath = "dashboard/billing/usage";
  9. public SubsPath = "dashboard/billing/subscription";
  10. path(path: string): string {
  11. let openaiUrl = useAccessStore.getState().openaiUrl;
  12. if (openaiUrl.endsWith("/")) {
  13. openaiUrl = openaiUrl.slice(0, openaiUrl.length - 1);
  14. }
  15. return [openaiUrl, path].join("/");
  16. }
  17. extractMessage(res: any) {
  18. return res.choices?.at(0)?.message?.content ?? "";
  19. }
  20. async chat(options: ChatOptions) {
  21. const messages = options.messages.map((v) => ({
  22. role: v.role,
  23. content: v.content,
  24. }));
  25. const modelConfig = {
  26. ...useAppConfig.getState().modelConfig,
  27. ...useChatStore.getState().currentSession().mask.modelConfig,
  28. ...{
  29. model: options.config.model,
  30. },
  31. };
  32. const requestPayload = {
  33. messages,
  34. stream: options.config.stream,
  35. model: modelConfig.model,
  36. temperature: modelConfig.temperature,
  37. presence_penalty: modelConfig.presence_penalty,
  38. };
  39. console.log("[Request] openai payload: ", requestPayload);
  40. const shouldStream = !!options.config.stream;
  41. const controller = new AbortController();
  42. options.onController?.(controller);
  43. try {
  44. const chatPath = this.path(this.ChatPath);
  45. const chatPayload = {
  46. method: "POST",
  47. body: JSON.stringify(requestPayload),
  48. signal: controller.signal,
  49. headers: getHeaders(),
  50. };
  51. // make a fetch request
  52. const requestTimeoutId = setTimeout(
  53. () => controller.abort(),
  54. REQUEST_TIMEOUT_MS,
  55. );
  56. if (shouldStream) {
  57. let responseText = "";
  58. const finish = () => {
  59. options.onFinish(responseText);
  60. };
  61. fetchEventSource(chatPath, {
  62. ...chatPayload,
  63. async onopen(res) {
  64. clearTimeout(requestTimeoutId);
  65. if (res.status === 401) {
  66. responseText += "\n\n" + Locale.Error.Unauthorized;
  67. return finish();
  68. }
  69. },
  70. onmessage(msg) {
  71. if (msg.data === "[DONE]") {
  72. return finish();
  73. }
  74. const text = msg.data;
  75. try {
  76. const json = JSON.parse(text);
  77. const delta = json.choices[0].delta.content;
  78. if (delta) {
  79. responseText += delta;
  80. options.onUpdate?.(responseText, delta);
  81. }
  82. } catch (e) {
  83. console.error("[Request] parse error", text, msg);
  84. }
  85. },
  86. onclose() {
  87. finish();
  88. },
  89. onerror(e) {
  90. options.onError?.(e);
  91. },
  92. });
  93. } else {
  94. const res = await fetch(chatPath, chatPayload);
  95. clearTimeout(requestTimeoutId);
  96. const resJson = await res.json();
  97. const message = this.extractMessage(resJson);
  98. options.onFinish(message);
  99. }
  100. } catch (e) {
  101. console.log("[Request] failed to make a chat reqeust", e);
  102. options.onError?.(e as Error);
  103. }
  104. }
  105. async usage() {
  106. const formatDate = (d: Date) =>
  107. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  108. .getDate()
  109. .toString()
  110. .padStart(2, "0")}`;
  111. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  112. const now = new Date();
  113. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  114. const startDate = formatDate(startOfMonth);
  115. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  116. const [used, subs] = await Promise.all([
  117. fetch(
  118. this.path(
  119. `${this.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  120. ),
  121. {
  122. method: "GET",
  123. headers: getHeaders(),
  124. },
  125. ),
  126. fetch(this.path(this.SubsPath), {
  127. method: "GET",
  128. headers: getHeaders(),
  129. }),
  130. ]);
  131. if (!used.ok || !subs.ok || used.status === 401) {
  132. throw new Error(Locale.Error.Unauthorized);
  133. }
  134. const response = (await used.json()) as {
  135. total_usage?: number;
  136. error?: {
  137. type: string;
  138. message: string;
  139. };
  140. };
  141. const total = (await subs.json()) as {
  142. hard_limit_usd?: number;
  143. };
  144. if (response.error && response.error.type) {
  145. throw Error(response.error.message);
  146. }
  147. if (response.total_usage) {
  148. response.total_usage = Math.round(response.total_usage) / 100;
  149. }
  150. if (total.hard_limit_usd) {
  151. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  152. }
  153. return {
  154. used: response.total_usage,
  155. total: total.hard_limit_usd,
  156. } as LLMUsage;
  157. }
  158. }