tencent.ts 7.2 KB

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