tencent.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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, index) => ({
  83. // "Messages 中 system 角色必须位于列表的最开始"
  84. role: index !== 0 && v.role === "system" ? "user" : v.role,
  85. content: visionModel ? v.content : getMessageTextContent(v),
  86. }));
  87. const modelConfig = {
  88. ...useAppConfig.getState().modelConfig,
  89. ...useChatStore.getState().currentSession().mask.modelConfig,
  90. ...{
  91. model: options.config.model,
  92. },
  93. };
  94. const requestPayload: RequestPayload = capitalizeKeys({
  95. model: modelConfig.model,
  96. messages,
  97. temperature: modelConfig.temperature,
  98. top_p: modelConfig.top_p,
  99. stream: options.config.stream,
  100. });
  101. console.log("[Request] Tencent payload: ", requestPayload);
  102. const shouldStream = !!options.config.stream;
  103. const controller = new AbortController();
  104. options.onController?.(controller);
  105. try {
  106. const chatPath = this.path();
  107. const chatPayload = {
  108. method: "POST",
  109. body: JSON.stringify(requestPayload),
  110. signal: controller.signal,
  111. headers: getHeaders(),
  112. };
  113. // make a fetch request
  114. const requestTimeoutId = setTimeout(
  115. () => controller.abort(),
  116. REQUEST_TIMEOUT_MS,
  117. );
  118. if (shouldStream) {
  119. let responseText = "";
  120. let remainText = "";
  121. let finished = false;
  122. // animate response to make it looks smooth
  123. function animateResponseText() {
  124. if (finished || controller.signal.aborted) {
  125. responseText += remainText;
  126. console.log("[Response Animation] finished");
  127. if (responseText?.length === 0) {
  128. options.onError?.(new Error("empty response from server"));
  129. }
  130. return;
  131. }
  132. if (remainText.length > 0) {
  133. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  134. const fetchText = remainText.slice(0, fetchCount);
  135. responseText += fetchText;
  136. remainText = remainText.slice(fetchCount);
  137. options.onUpdate?.(responseText, fetchText);
  138. }
  139. requestAnimationFrame(animateResponseText);
  140. }
  141. // start animaion
  142. animateResponseText();
  143. const finish = () => {
  144. if (!finished) {
  145. finished = true;
  146. options.onFinish(responseText + remainText);
  147. }
  148. };
  149. controller.signal.onabort = finish;
  150. fetchEventSource(chatPath, {
  151. ...chatPayload,
  152. async onopen(res) {
  153. clearTimeout(requestTimeoutId);
  154. const contentType = res.headers.get("content-type");
  155. console.log(
  156. "[Tencent] request response content type: ",
  157. contentType,
  158. );
  159. if (contentType?.startsWith("text/plain")) {
  160. responseText = await res.clone().text();
  161. return finish();
  162. }
  163. if (
  164. !res.ok ||
  165. !res.headers
  166. .get("content-type")
  167. ?.startsWith(EventStreamContentType) ||
  168. res.status !== 200
  169. ) {
  170. const responseTexts = [responseText];
  171. let extraInfo = await res.clone().text();
  172. try {
  173. const resJson = await res.clone().json();
  174. extraInfo = prettyObject(resJson);
  175. } catch {}
  176. if (res.status === 401) {
  177. responseTexts.push(Locale.Error.Unauthorized);
  178. }
  179. if (extraInfo) {
  180. responseTexts.push(extraInfo);
  181. }
  182. responseText = responseTexts.join("\n\n");
  183. return finish();
  184. }
  185. },
  186. onmessage(msg) {
  187. if (msg.data === "[DONE]" || finished) {
  188. return finish();
  189. }
  190. const text = msg.data;
  191. try {
  192. const json = JSON.parse(text);
  193. const choices = json.Choices as Array<{
  194. Delta: { Content: string };
  195. }>;
  196. const delta = choices[0]?.Delta?.Content;
  197. if (delta) {
  198. remainText += delta;
  199. }
  200. } catch (e) {
  201. console.error("[Request] parse error", text, msg);
  202. }
  203. },
  204. onclose() {
  205. finish();
  206. },
  207. onerror(e) {
  208. options.onError?.(e);
  209. throw e;
  210. },
  211. openWhenHidden: true,
  212. });
  213. } else {
  214. const res = await fetch(chatPath, chatPayload);
  215. clearTimeout(requestTimeoutId);
  216. const resJson = await res.json();
  217. const message = this.extractMessage(resJson);
  218. options.onFinish(message);
  219. }
  220. } catch (e) {
  221. console.log("[Request] failed to make a chat request", e);
  222. options.onError?.(e as Error);
  223. }
  224. }
  225. async usage() {
  226. return {
  227. used: 0,
  228. total: 0,
  229. };
  230. }
  231. async models(): Promise<LLMModel[]> {
  232. return [];
  233. }
  234. }