openai.ts 6.1 KB

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