glm.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. "use client";
  2. import {
  3. ApiPath,
  4. CHATGLM_BASE_URL,
  5. ChatGLM,
  6. REQUEST_TIMEOUT_MS,
  7. } from "@/app/constant";
  8. import {
  9. useAccessStore,
  10. useAppConfig,
  11. useChatStore,
  12. ChatMessageTool,
  13. usePluginStore,
  14. } from "@/app/store";
  15. import { stream } from "@/app/utils/chat";
  16. import {
  17. ChatOptions,
  18. getHeaders,
  19. LLMApi,
  20. LLMModel,
  21. SpeechOptions,
  22. } from "../api";
  23. import { getClientConfig } from "@/app/config/client";
  24. import { getMessageTextContent } from "@/app/utils";
  25. import { RequestPayload } from "./openai";
  26. import { fetch } from "@/app/utils/stream";
  27. interface BasePayload {
  28. model: string;
  29. }
  30. interface ChatPayload extends BasePayload {
  31. messages: ChatOptions["messages"];
  32. stream?: boolean;
  33. temperature?: number;
  34. presence_penalty?: number;
  35. frequency_penalty?: number;
  36. top_p?: number;
  37. }
  38. interface ImageGenerationPayload extends BasePayload {
  39. prompt: string;
  40. size?: string;
  41. user_id?: string;
  42. }
  43. interface VideoGenerationPayload extends BasePayload {
  44. prompt: string;
  45. duration?: number;
  46. resolution?: string;
  47. user_id?: string;
  48. }
  49. type ModelType = "chat" | "image" | "video";
  50. export class ChatGLMApi implements LLMApi {
  51. private disableListModels = true;
  52. private getModelType(model: string): ModelType {
  53. if (model.startsWith("cogview-")) return "image";
  54. if (model.startsWith("cogvideo-")) return "video";
  55. return "chat";
  56. }
  57. private getModelPath(type: ModelType): string {
  58. switch (type) {
  59. case "image":
  60. return ChatGLM.ImagePath;
  61. case "video":
  62. return ChatGLM.VideoPath;
  63. default:
  64. return ChatGLM.ChatPath;
  65. }
  66. }
  67. private createPayload(
  68. messages: ChatOptions["messages"],
  69. modelConfig: any,
  70. options: ChatOptions,
  71. ): BasePayload {
  72. const modelType = this.getModelType(modelConfig.model);
  73. const lastMessage = messages[messages.length - 1];
  74. const prompt =
  75. typeof lastMessage.content === "string"
  76. ? lastMessage.content
  77. : lastMessage.content.map((c) => c.text).join("\n");
  78. switch (modelType) {
  79. case "image":
  80. return {
  81. model: modelConfig.model,
  82. prompt,
  83. size: "1024x1024",
  84. } as ImageGenerationPayload;
  85. default:
  86. return {
  87. messages,
  88. stream: options.config.stream,
  89. model: modelConfig.model,
  90. temperature: modelConfig.temperature,
  91. presence_penalty: modelConfig.presence_penalty,
  92. frequency_penalty: modelConfig.frequency_penalty,
  93. top_p: modelConfig.top_p,
  94. } as ChatPayload;
  95. }
  96. }
  97. private parseResponse(modelType: ModelType, json: any): string {
  98. switch (modelType) {
  99. case "image": {
  100. const imageUrl = json.data?.[0]?.url;
  101. return imageUrl ? `![Generated Image](${imageUrl})` : "";
  102. }
  103. case "video": {
  104. const videoUrl = json.data?.[0]?.url;
  105. return videoUrl ? `<video controls src="${videoUrl}"></video>` : "";
  106. }
  107. default:
  108. return this.extractMessage(json);
  109. }
  110. }
  111. path(path: string): string {
  112. const accessStore = useAccessStore.getState();
  113. let baseUrl = "";
  114. if (accessStore.useCustomConfig) {
  115. baseUrl = accessStore.chatglmUrl;
  116. }
  117. if (baseUrl.length === 0) {
  118. const isApp = !!getClientConfig()?.isApp;
  119. const apiPath = ApiPath.ChatGLM;
  120. baseUrl = isApp ? CHATGLM_BASE_URL : apiPath;
  121. }
  122. if (baseUrl.endsWith("/")) {
  123. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  124. }
  125. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.ChatGLM)) {
  126. baseUrl = "https://" + baseUrl;
  127. }
  128. console.log("[Proxy Endpoint] ", baseUrl, path);
  129. return [baseUrl, path].join("/");
  130. }
  131. extractMessage(res: any) {
  132. return res.choices?.at(0)?.message?.content ?? "";
  133. }
  134. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  135. throw new Error("Method not implemented.");
  136. }
  137. async chat(options: ChatOptions) {
  138. const messages: ChatOptions["messages"] = [];
  139. for (const v of options.messages) {
  140. const content = getMessageTextContent(v);
  141. messages.push({ role: v.role, content });
  142. }
  143. const modelConfig = {
  144. ...useAppConfig.getState().modelConfig,
  145. ...useChatStore.getState().currentSession().mask.modelConfig,
  146. ...{
  147. model: options.config.model,
  148. providerName: options.config.providerName,
  149. },
  150. };
  151. const modelType = this.getModelType(modelConfig.model);
  152. const requestPayload = this.createPayload(messages, modelConfig, options);
  153. const path = this.path(this.getModelPath(modelType));
  154. console.log(`[Request] glm ${modelType} payload: `, requestPayload);
  155. const controller = new AbortController();
  156. options.onController?.(controller);
  157. try {
  158. const chatPayload = {
  159. method: "POST",
  160. body: JSON.stringify(requestPayload),
  161. signal: controller.signal,
  162. headers: getHeaders(),
  163. };
  164. const requestTimeoutId = setTimeout(
  165. () => controller.abort(),
  166. REQUEST_TIMEOUT_MS,
  167. );
  168. if (modelType === "image" || modelType === "video") {
  169. const res = await fetch(path, chatPayload);
  170. clearTimeout(requestTimeoutId);
  171. const resJson = await res.json();
  172. console.log(`[Response] glm ${modelType}:`, resJson);
  173. const message = this.parseResponse(modelType, resJson);
  174. options.onFinish(message, res);
  175. return;
  176. }
  177. const shouldStream = !!options.config.stream;
  178. if (shouldStream) {
  179. const [tools, funcs] = usePluginStore
  180. .getState()
  181. .getAsTools(
  182. useChatStore.getState().currentSession().mask?.plugin || [],
  183. );
  184. return stream(
  185. path,
  186. requestPayload,
  187. getHeaders(),
  188. tools as any,
  189. funcs,
  190. controller,
  191. // parseSSE
  192. (text: string, runTools: ChatMessageTool[]) => {
  193. const json = JSON.parse(text);
  194. const choices = json.choices as Array<{
  195. delta: {
  196. content: string;
  197. tool_calls: ChatMessageTool[];
  198. };
  199. }>;
  200. const tool_calls = choices[0]?.delta?.tool_calls;
  201. if (tool_calls?.length > 0) {
  202. const index = tool_calls[0]?.index;
  203. const id = tool_calls[0]?.id;
  204. const args = tool_calls[0]?.function?.arguments;
  205. if (id) {
  206. runTools.push({
  207. id,
  208. type: tool_calls[0]?.type,
  209. function: {
  210. name: tool_calls[0]?.function?.name as string,
  211. arguments: args,
  212. },
  213. });
  214. } else {
  215. // @ts-ignore
  216. runTools[index]["function"]["arguments"] += args;
  217. }
  218. }
  219. return choices[0]?.delta?.content;
  220. },
  221. // processToolMessage
  222. (
  223. requestPayload: RequestPayload,
  224. toolCallMessage: any,
  225. toolCallResult: any[],
  226. ) => {
  227. // @ts-ignore
  228. requestPayload?.messages?.splice(
  229. // @ts-ignore
  230. requestPayload?.messages?.length,
  231. 0,
  232. toolCallMessage,
  233. ...toolCallResult,
  234. );
  235. },
  236. options,
  237. );
  238. } else {
  239. const res = await fetch(path, chatPayload);
  240. clearTimeout(requestTimeoutId);
  241. const resJson = await res.json();
  242. const message = this.extractMessage(resJson);
  243. options.onFinish(message, res);
  244. }
  245. } catch (e) {
  246. console.log("[Request] failed to make a chat request", e);
  247. options.onError?.(e as Error);
  248. }
  249. }
  250. async usage() {
  251. return {
  252. used: 0,
  253. total: 0,
  254. };
  255. }
  256. async models(): Promise<LLMModel[]> {
  257. return [];
  258. }
  259. }