openai.ts 5.7 KB

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