openai.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. const finish = () => {
  63. options.onFinish(responseText);
  64. };
  65. controller.signal.onabort = finish;
  66. fetchEventSource(chatPath, {
  67. ...chatPayload,
  68. async onopen(res) {
  69. clearTimeout(requestTimeoutId);
  70. if (
  71. res.ok &&
  72. res.headers.get("content-type") !== EventStreamContentType
  73. ) {
  74. responseText += await res.clone().json();
  75. return finish();
  76. }
  77. if (res.status === 401) {
  78. let extraInfo = { error: undefined };
  79. try {
  80. extraInfo = await res.clone().json();
  81. } catch {}
  82. responseText += "\n\n" + Locale.Error.Unauthorized;
  83. if (extraInfo.error) {
  84. responseText += "\n\n" + prettyObject(extraInfo);
  85. }
  86. return finish();
  87. }
  88. },
  89. onmessage(msg) {
  90. if (msg.data === "[DONE]") {
  91. return finish();
  92. }
  93. const text = msg.data;
  94. try {
  95. const json = JSON.parse(text);
  96. const delta = json.choices[0].delta.content;
  97. if (delta) {
  98. responseText += delta;
  99. options.onUpdate?.(responseText, delta);
  100. }
  101. } catch (e) {
  102. console.error("[Request] parse error", text, msg);
  103. }
  104. },
  105. onclose() {
  106. finish();
  107. },
  108. onerror(e) {
  109. options.onError?.(e);
  110. },
  111. });
  112. } else {
  113. const res = await fetch(chatPath, chatPayload);
  114. clearTimeout(requestTimeoutId);
  115. const resJson = await res.json();
  116. const message = this.extractMessage(resJson);
  117. options.onFinish(message);
  118. }
  119. } catch (e) {
  120. console.log("[Request] failed to make a chat reqeust", e);
  121. options.onError?.(e as Error);
  122. }
  123. }
  124. async usage() {
  125. const formatDate = (d: Date) =>
  126. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  127. .getDate()
  128. .toString()
  129. .padStart(2, "0")}`;
  130. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  131. const now = new Date();
  132. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  133. const startDate = formatDate(startOfMonth);
  134. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  135. const [used, subs] = await Promise.all([
  136. fetch(
  137. this.path(
  138. `${this.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  139. ),
  140. {
  141. method: "GET",
  142. headers: getHeaders(),
  143. },
  144. ),
  145. fetch(this.path(this.SubsPath), {
  146. method: "GET",
  147. headers: getHeaders(),
  148. }),
  149. ]);
  150. if (!used.ok || !subs.ok || used.status === 401) {
  151. throw new Error(Locale.Error.Unauthorized);
  152. }
  153. const response = (await used.json()) as {
  154. total_usage?: number;
  155. error?: {
  156. type: string;
  157. message: string;
  158. };
  159. };
  160. const total = (await subs.json()) as {
  161. hard_limit_usd?: number;
  162. };
  163. if (response.error && response.error.type) {
  164. throw Error(response.error.message);
  165. }
  166. if (response.total_usage) {
  167. response.total_usage = Math.round(response.total_usage) / 100;
  168. }
  169. if (total.hard_limit_usd) {
  170. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  171. }
  172. return {
  173. used: response.total_usage,
  174. total: total.hard_limit_usd,
  175. } as LLMUsage;
  176. }
  177. }