openai.ts 6.3 KB

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