tencent.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. "use client";
  2. import { ApiPath, DEFAULT_API_HOST, REQUEST_TIMEOUT_MS } from "@/app/constant";
  3. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  4. import {
  5. ChatOptions,
  6. getHeaders,
  7. LLMApi,
  8. LLMModel,
  9. MultimodalContent,
  10. } from "../api";
  11. import Locale from "../../locales";
  12. import {
  13. EventStreamContentType,
  14. fetchEventSource,
  15. } from "@fortaine/fetch-event-source";
  16. import { prettyObject } from "@/app/utils/format";
  17. import { getClientConfig } from "@/app/config/client";
  18. import { getMessageTextContent, isVisionModel } from "@/app/utils";
  19. // @ts-ignore
  20. import mapKeys from "lodash-es/mapKeys";
  21. // @ts-ignore
  22. import mapValues from "lodash-es/mapValues";
  23. // @ts-ignore
  24. import isArray from "lodash-es/isArray";
  25. // @ts-ignore
  26. import isObject from "lodash-es/isObject";
  27. export interface OpenAIListModelResponse {
  28. object: string;
  29. data: Array<{
  30. id: string;
  31. object: string;
  32. root: string;
  33. }>;
  34. }
  35. interface RequestPayload {
  36. Messages: {
  37. Role: "system" | "user" | "assistant";
  38. Content: string | MultimodalContent[];
  39. }[];
  40. Stream?: boolean;
  41. Model: string;
  42. Temperature: number;
  43. TopP: number;
  44. }
  45. function capitalizeKeys(obj: any): any {
  46. if (isArray(obj)) {
  47. return obj.map(capitalizeKeys);
  48. } else if (isObject(obj)) {
  49. return mapValues(
  50. mapKeys(obj, (value: any, key: string) =>
  51. key.replace(/(^|_)(\w)/g, (m, $1, $2) => $2.toUpperCase()),
  52. ),
  53. capitalizeKeys,
  54. );
  55. } else {
  56. return obj;
  57. }
  58. }
  59. export class HunyuanApi implements LLMApi {
  60. path(): string {
  61. const accessStore = useAccessStore.getState();
  62. let baseUrl = "";
  63. if (accessStore.useCustomConfig) {
  64. baseUrl = accessStore.tencentUrl;
  65. }
  66. if (baseUrl.length === 0) {
  67. const isApp = !!getClientConfig()?.isApp;
  68. baseUrl = isApp
  69. ? DEFAULT_API_HOST + "/api/proxy/tencent"
  70. : ApiPath.Tencent;
  71. }
  72. if (baseUrl.endsWith("/")) {
  73. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  74. }
  75. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Tencent)) {
  76. baseUrl = "https://" + baseUrl;
  77. }
  78. console.log("[Proxy Endpoint] ", baseUrl);
  79. return baseUrl;
  80. }
  81. extractMessage(res: any) {
  82. return res.Choices?.at(0)?.Message?.Content ?? "";
  83. }
  84. async chat(options: ChatOptions) {
  85. const visionModel = isVisionModel(options.config.model);
  86. const messages = options.messages.map((v) => ({
  87. role: v.role,
  88. content: visionModel ? v.content : getMessageTextContent(v),
  89. }));
  90. const modelConfig = {
  91. ...useAppConfig.getState().modelConfig,
  92. ...useChatStore.getState().currentSession().mask.modelConfig,
  93. ...{
  94. model: options.config.model,
  95. },
  96. };
  97. const requestPayload: RequestPayload = capitalizeKeys({
  98. model: modelConfig.model,
  99. messages,
  100. temperature: modelConfig.temperature,
  101. top_p: modelConfig.top_p,
  102. stream: options.config.stream,
  103. });
  104. console.log("[Request] Tencent payload: ", requestPayload);
  105. const shouldStream = !!options.config.stream;
  106. const controller = new AbortController();
  107. options.onController?.(controller);
  108. try {
  109. const chatPath = this.path();
  110. const chatPayload = {
  111. method: "POST",
  112. body: JSON.stringify(requestPayload),
  113. signal: controller.signal,
  114. headers: getHeaders(),
  115. };
  116. // make a fetch request
  117. const requestTimeoutId = setTimeout(
  118. () => controller.abort(),
  119. REQUEST_TIMEOUT_MS,
  120. );
  121. if (shouldStream) {
  122. let responseText = "";
  123. let remainText = "";
  124. let finished = false;
  125. // animate response to make it looks smooth
  126. function animateResponseText() {
  127. if (finished || controller.signal.aborted) {
  128. responseText += remainText;
  129. console.log("[Response Animation] finished");
  130. if (responseText?.length === 0) {
  131. options.onError?.(new Error("empty response from server"));
  132. }
  133. return;
  134. }
  135. if (remainText.length > 0) {
  136. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  137. const fetchText = remainText.slice(0, fetchCount);
  138. responseText += fetchText;
  139. remainText = remainText.slice(fetchCount);
  140. options.onUpdate?.(responseText, fetchText);
  141. }
  142. requestAnimationFrame(animateResponseText);
  143. }
  144. // start animaion
  145. animateResponseText();
  146. const finish = () => {
  147. if (!finished) {
  148. finished = true;
  149. options.onFinish(responseText + remainText);
  150. }
  151. };
  152. controller.signal.onabort = finish;
  153. fetchEventSource(chatPath, {
  154. ...chatPayload,
  155. async onopen(res) {
  156. clearTimeout(requestTimeoutId);
  157. const contentType = res.headers.get("content-type");
  158. console.log(
  159. "[Tencent] request response content type: ",
  160. contentType,
  161. );
  162. if (contentType?.startsWith("text/plain")) {
  163. responseText = await res.clone().text();
  164. return finish();
  165. }
  166. if (
  167. !res.ok ||
  168. !res.headers
  169. .get("content-type")
  170. ?.startsWith(EventStreamContentType) ||
  171. res.status !== 200
  172. ) {
  173. const responseTexts = [responseText];
  174. let extraInfo = await res.clone().text();
  175. try {
  176. const resJson = await res.clone().json();
  177. extraInfo = prettyObject(resJson);
  178. } catch {}
  179. if (res.status === 401) {
  180. responseTexts.push(Locale.Error.Unauthorized);
  181. }
  182. if (extraInfo) {
  183. responseTexts.push(extraInfo);
  184. }
  185. responseText = responseTexts.join("\n\n");
  186. return finish();
  187. }
  188. },
  189. onmessage(msg) {
  190. if (msg.data === "[DONE]" || finished) {
  191. return finish();
  192. }
  193. const text = msg.data;
  194. try {
  195. const json = JSON.parse(text);
  196. const choices = json.Choices as Array<{
  197. Delta: { Content: string };
  198. }>;
  199. const delta = choices[0]?.Delta?.Content;
  200. if (delta) {
  201. remainText += delta;
  202. }
  203. } catch (e) {
  204. console.error("[Request] parse error", text, msg);
  205. }
  206. },
  207. onclose() {
  208. finish();
  209. },
  210. onerror(e) {
  211. options.onError?.(e);
  212. throw e;
  213. },
  214. openWhenHidden: true,
  215. });
  216. } else {
  217. const res = await fetch(chatPath, chatPayload);
  218. clearTimeout(requestTimeoutId);
  219. const resJson = await res.json();
  220. const message = this.extractMessage(resJson);
  221. options.onFinish(message);
  222. }
  223. } catch (e) {
  224. console.log("[Request] failed to make a chat request", e);
  225. options.onError?.(e as Error);
  226. }
  227. }
  228. async usage() {
  229. return {
  230. used: 0,
  231. total: 0,
  232. };
  233. }
  234. async models(): Promise<LLMModel[]> {
  235. return [];
  236. }
  237. }