tencent.ts 7.3 KB

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