tencent.ts 7.1 KB

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