openai.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import {
  2. DEFAULT_API_HOST,
  3. OpenaiPath,
  4. REQUEST_TIMEOUT_MS,
  5. } from "@/app/constant";
  6. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  7. import { ChatOptions, getHeaders, LLMApi, LLMUsage } from "../api";
  8. import Locale from "../../locales";
  9. import {
  10. EventStreamContentType,
  11. fetchEventSource,
  12. } from "@fortaine/fetch-event-source";
  13. import { prettyObject } from "@/app/utils/format";
  14. export class ChatGPTApi implements LLMApi {
  15. path(path: string): string {
  16. let openaiUrl = useAccessStore.getState().openaiUrl;
  17. if (openaiUrl.length === 0) {
  18. openaiUrl = DEFAULT_API_HOST;
  19. }
  20. if (openaiUrl.endsWith("/")) {
  21. openaiUrl = openaiUrl.slice(0, openaiUrl.length - 1);
  22. }
  23. return [openaiUrl, path].join("/");
  24. }
  25. extractMessage(res: any) {
  26. return res.choices?.at(0)?.message?.content ?? "";
  27. }
  28. async chat(options: ChatOptions) {
  29. const messages = options.messages.map((v) => ({
  30. role: v.role,
  31. content: v.content,
  32. }));
  33. const modelConfig = {
  34. ...useAppConfig.getState().modelConfig,
  35. ...useChatStore.getState().currentSession().mask.modelConfig,
  36. ...{
  37. model: options.config.model,
  38. },
  39. };
  40. const requestPayload = {
  41. messages,
  42. stream: options.config.stream,
  43. model: modelConfig.model,
  44. temperature: modelConfig.temperature,
  45. presence_penalty: modelConfig.presence_penalty,
  46. frequency_penalty: modelConfig.frequency_penalty,
  47. };
  48. console.log("[Request] openai payload: ", requestPayload);
  49. const shouldStream = !!options.config.stream;
  50. const controller = new AbortController();
  51. options.onController?.(controller);
  52. try {
  53. const chatPath = this.path(OpenaiPath.ChatPath);
  54. const chatPayload = {
  55. method: "POST",
  56. body: JSON.stringify(requestPayload),
  57. signal: controller.signal,
  58. headers: getHeaders(),
  59. };
  60. // make a fetch request
  61. const requestTimeoutId = setTimeout(
  62. () => controller.abort(),
  63. REQUEST_TIMEOUT_MS,
  64. );
  65. if (shouldStream) {
  66. let responseText = "";
  67. let finished = false;
  68. const finish = () => {
  69. if (!finished) {
  70. options.onFinish(responseText);
  71. finished = true;
  72. }
  73. };
  74. controller.signal.onabort = finish;
  75. fetchEventSource(chatPath, {
  76. ...chatPayload,
  77. async onopen(res) {
  78. clearTimeout(requestTimeoutId);
  79. const contentType = res.headers.get("content-type");
  80. console.log(
  81. "[OpenAI] request response content type: ",
  82. contentType,
  83. );
  84. if (contentType?.startsWith("text/plain")) {
  85. responseText = await res.clone().text();
  86. return finish();
  87. }
  88. if (
  89. !res.ok ||
  90. !res.headers
  91. .get("content-type")
  92. ?.startsWith(EventStreamContentType) ||
  93. res.status !== 200
  94. ) {
  95. const responseTexts = [responseText];
  96. let extraInfo = await res.clone().text();
  97. try {
  98. const resJson = await res.clone().json();
  99. extraInfo = prettyObject(resJson);
  100. } catch {}
  101. if (res.status === 401) {
  102. responseTexts.push(Locale.Error.Unauthorized);
  103. }
  104. if (extraInfo) {
  105. responseTexts.push(extraInfo);
  106. }
  107. responseText = responseTexts.join("\n\n");
  108. return finish();
  109. }
  110. },
  111. onmessage(msg) {
  112. if (msg.data === "[DONE]" || finished) {
  113. return finish();
  114. }
  115. const text = msg.data;
  116. try {
  117. const json = JSON.parse(text);
  118. const delta = json.choices[0].delta.content;
  119. if (delta) {
  120. responseText += delta;
  121. options.onUpdate?.(responseText, delta);
  122. }
  123. } catch (e) {
  124. console.error("[Request] parse error", text, msg);
  125. }
  126. },
  127. onclose() {
  128. finish();
  129. },
  130. onerror(e) {
  131. options.onError?.(e);
  132. throw e;
  133. },
  134. openWhenHidden: true,
  135. });
  136. } else {
  137. const res = await fetch(chatPath, chatPayload);
  138. clearTimeout(requestTimeoutId);
  139. const resJson = await res.json();
  140. const message = this.extractMessage(resJson);
  141. options.onFinish(message);
  142. }
  143. } catch (e) {
  144. console.log("[Request] failed to make a chat reqeust", e);
  145. options.onError?.(e as Error);
  146. }
  147. }
  148. async usage() {
  149. const formatDate = (d: Date) =>
  150. `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
  151. .getDate()
  152. .toString()
  153. .padStart(2, "0")}`;
  154. const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
  155. const now = new Date();
  156. const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  157. const startDate = formatDate(startOfMonth);
  158. const endDate = formatDate(new Date(Date.now() + ONE_DAY));
  159. const [used, subs] = await Promise.all([
  160. fetch(
  161. this.path(
  162. `${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
  163. ),
  164. {
  165. method: "GET",
  166. headers: getHeaders(),
  167. },
  168. ),
  169. fetch(this.path(OpenaiPath.SubsPath), {
  170. method: "GET",
  171. headers: getHeaders(),
  172. }),
  173. ]);
  174. if (used.status === 401) {
  175. throw new Error(Locale.Error.Unauthorized);
  176. }
  177. if (!used.ok || !subs.ok) {
  178. throw new Error("Failed to query usage from openai");
  179. }
  180. const response = (await used.json()) as {
  181. total_usage?: number;
  182. error?: {
  183. type: string;
  184. message: string;
  185. };
  186. };
  187. const total = (await subs.json()) as {
  188. hard_limit_usd?: number;
  189. };
  190. if (response.error && response.error.type) {
  191. throw Error(response.error.message);
  192. }
  193. if (response.total_usage) {
  194. response.total_usage = Math.round(response.total_usage) / 100;
  195. }
  196. if (total.hard_limit_usd) {
  197. total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
  198. }
  199. return {
  200. used: response.total_usage,
  201. total: total.hard_limit_usd,
  202. } as LLMUsage;
  203. }
  204. }
  205. export { OpenaiPath };