openai.ts 6.3 KB

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