openai.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import { OpenaiPath, 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. path(path: string): string {
  12. let openaiUrl = useAccessStore.getState().openaiUrl;
  13. if (openaiUrl.endsWith("/")) {
  14. openaiUrl = openaiUrl.slice(0, openaiUrl.length - 1);
  15. }
  16. return [openaiUrl, path].join("/");
  17. }
  18. extractMessage(res: any) {
  19. return res.choices?.at(0)?.message?.content ?? "";
  20. }
  21. async chat(options: ChatOptions) {
  22. const messages = options.messages.map((v) => ({
  23. role: v.role,
  24. content: v.content,
  25. }));
  26. const modelConfig = {
  27. ...useAppConfig.getState().modelConfig,
  28. ...useChatStore.getState().currentSession().mask.modelConfig,
  29. ...{
  30. model: options.config.model,
  31. },
  32. };
  33. const requestPayload = {
  34. messages,
  35. stream: options.config.stream,
  36. model: modelConfig.model,
  37. temperature: modelConfig.temperature,
  38. presence_penalty: modelConfig.presence_penalty,
  39. };
  40. console.log("[Request] openai payload: ", requestPayload);
  41. const shouldStream = !!options.config.stream;
  42. const controller = new AbortController();
  43. options.onController?.(controller);
  44. try {
  45. const chatPath = this.path(OpenaiPath.ChatPath);
  46. const chatPayload = {
  47. method: "POST",
  48. body: JSON.stringify(requestPayload),
  49. signal: controller.signal,
  50. headers: getHeaders(),
  51. };
  52. // make a fetch request
  53. const requestTimeoutId = setTimeout(
  54. () => controller.abort(),
  55. REQUEST_TIMEOUT_MS,
  56. );
  57. if (shouldStream) {
  58. let responseText = "";
  59. let finished = false;
  60. const finish = () => {
  61. if (!finished) {
  62. options.onFinish(responseText);
  63. finished = true;
  64. }
  65. };
  66. controller.signal.onabort = finish;
  67. fetchEventSource(chatPath, {
  68. ...chatPayload,
  69. async onopen(res) {
  70. clearTimeout(requestTimeoutId);
  71. const contentType = res.headers.get("content-type");
  72. console.log(
  73. "[OpenAI] request response content type: ",
  74. contentType,
  75. );
  76. if (contentType?.startsWith("text/plain")) {
  77. responseText = await res.clone().text();
  78. return finish();
  79. }
  80. if (
  81. !res.ok ||
  82. !res.headers
  83. .get("content-type")
  84. ?.startsWith(EventStreamContentType) ||
  85. res.status !== 200
  86. ) {
  87. const responseTexts = [responseText];
  88. let extraInfo = await res.clone().text();
  89. try {
  90. const resJson = await res.clone().json();
  91. extraInfo = prettyObject(resJson);
  92. } catch {}
  93. if (res.status === 401) {
  94. responseTexts.push(Locale.Error.Unauthorized);
  95. }
  96. if (extraInfo) {
  97. responseTexts.push(extraInfo);
  98. }
  99. responseText = responseTexts.join("\n\n");
  100. return finish();
  101. }
  102. },
  103. onmessage(msg) {
  104. if (msg.data === "[DONE]" || finished) {
  105. return finish();
  106. }
  107. const text = msg.data;
  108. try {
  109. const json = JSON.parse(text);
  110. const delta = json.choices[0].delta.content;
  111. if (delta) {
  112. responseText += delta;
  113. options.onUpdate?.(responseText, delta);
  114. }
  115. } catch (e) {
  116. console.error("[Request] parse error", text, msg);
  117. }
  118. },
  119. onclose() {
  120. finish();
  121. },
  122. onerror(e) {
  123. options.onError?.(e);
  124. throw 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. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  155. ),
  156. {
  157. method: "GET",
  158. headers: getHeaders(),
  159. },
  160. ),
  161. fetch(this.path(OpenaiPath.SubsPath), {
  162. method: "GET",
  163. headers: getHeaders(),
  164. }),
  165. ]);
  166. if (used.status === 401) {
  167. throw new Error(Locale.Error.Unauthorized);
  168. }
  169. if (!used.ok || !subs.ok) {
  170. throw new Error("Failed to query usage from openai");
  171. }
  172. const response = (await used.json()) as {
  173. total_usage?: number;
  174. error?: {
  175. type: string;
  176. message: string;
  177. };
  178. };
  179. const total = (await subs.json()) as {
  180. hard_limit_usd?: number;
  181. };
  182. if (response.error && response.error.type) {
  183. throw Error(response.error.message);
  184. }
  185. if (response.total_usage) {
  186. response.total_usage = Math.round(response.total_usage) / 100;
  187. }
  188. if (total.hard_limit_usd) {
  189. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  190. }
  191. return {
  192. used: response.total_usage,
  193. total: total.hard_limit_usd,
  194. } as LLMUsage;
  195. }
  196. }
  197. export { OpenaiPath };