glm.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. export class ChatGLMApi implements LLMApi {
  28. private disableListModels = true;
  29. path(path: string): string {
  30. const accessStore = useAccessStore.getState();
  31. let baseUrl = "";
  32. if (accessStore.useCustomConfig) {
  33. baseUrl = accessStore.chatglmUrl;
  34. }
  35. if (baseUrl.length === 0) {
  36. const isApp = !!getClientConfig()?.isApp;
  37. const apiPath = ApiPath.ChatGLM;
  38. baseUrl = isApp ? CHATGLM_BASE_URL : apiPath;
  39. }
  40. if (baseUrl.endsWith("/")) {
  41. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  42. }
  43. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.ChatGLM)) {
  44. baseUrl = "https://" + baseUrl;
  45. }
  46. console.log("[Proxy Endpoint] ", baseUrl, path);
  47. return [baseUrl, path].join("/");
  48. }
  49. extractMessage(res: any) {
  50. return res.choices?.at(0)?.message?.content ?? "";
  51. }
  52. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  53. throw new Error("Method not implemented.");
  54. }
  55. async chat(options: ChatOptions) {
  56. const messages: ChatOptions["messages"] = [];
  57. for (const v of options.messages) {
  58. const content = getMessageTextContent(v);
  59. messages.push({ role: v.role, content });
  60. }
  61. const modelConfig = {
  62. ...useAppConfig.getState().modelConfig,
  63. ...useChatStore.getState().currentSession().mask.modelConfig,
  64. ...{
  65. model: options.config.model,
  66. providerName: options.config.providerName,
  67. },
  68. };
  69. const requestPayload: RequestPayload = {
  70. messages,
  71. stream: options.config.stream,
  72. model: modelConfig.model,
  73. temperature: modelConfig.temperature,
  74. presence_penalty: modelConfig.presence_penalty,
  75. frequency_penalty: modelConfig.frequency_penalty,
  76. top_p: modelConfig.top_p,
  77. };
  78. console.log("[Request] glm payload: ", requestPayload);
  79. const shouldStream = !!options.config.stream;
  80. const controller = new AbortController();
  81. options.onController?.(controller);
  82. try {
  83. const chatPath = this.path(ChatGLM.ChatPath);
  84. const chatPayload = {
  85. method: "POST",
  86. body: JSON.stringify(requestPayload),
  87. signal: controller.signal,
  88. headers: getHeaders(),
  89. };
  90. // make a fetch request
  91. const requestTimeoutId = setTimeout(
  92. () => controller.abort(),
  93. REQUEST_TIMEOUT_MS,
  94. );
  95. if (shouldStream) {
  96. const [tools, funcs] = usePluginStore
  97. .getState()
  98. .getAsTools(
  99. useChatStore.getState().currentSession().mask?.plugin || [],
  100. );
  101. return stream(
  102. chatPath,
  103. requestPayload,
  104. getHeaders(),
  105. tools as any,
  106. funcs,
  107. controller,
  108. // parseSSE
  109. (text: string, runTools: ChatMessageTool[]) => {
  110. // console.log("parseSSE", text, runTools);
  111. const json = JSON.parse(text);
  112. const choices = json.choices as Array<{
  113. delta: {
  114. content: string;
  115. tool_calls: ChatMessageTool[];
  116. };
  117. }>;
  118. const tool_calls = choices[0]?.delta?.tool_calls;
  119. if (tool_calls?.length > 0) {
  120. const index = tool_calls[0]?.index;
  121. const id = tool_calls[0]?.id;
  122. const args = tool_calls[0]?.function?.arguments;
  123. if (id) {
  124. runTools.push({
  125. id,
  126. type: tool_calls[0]?.type,
  127. function: {
  128. name: tool_calls[0]?.function?.name as string,
  129. arguments: args,
  130. },
  131. });
  132. } else {
  133. // @ts-ignore
  134. runTools[index]["function"]["arguments"] += args;
  135. }
  136. }
  137. return choices[0]?.delta?.content;
  138. },
  139. // processToolMessage, include tool_calls message and tool call results
  140. (
  141. requestPayload: RequestPayload,
  142. toolCallMessage: any,
  143. toolCallResult: any[],
  144. ) => {
  145. // @ts-ignore
  146. requestPayload?.messages?.splice(
  147. // @ts-ignore
  148. requestPayload?.messages?.length,
  149. 0,
  150. toolCallMessage,
  151. ...toolCallResult,
  152. );
  153. },
  154. options,
  155. );
  156. } else {
  157. const res = await fetch(chatPath, chatPayload);
  158. clearTimeout(requestTimeoutId);
  159. const resJson = await res.json();
  160. const message = this.extractMessage(resJson);
  161. options.onFinish(message, res);
  162. }
  163. } catch (e) {
  164. console.log("[Request] failed to make a chat request", e);
  165. options.onError?.(e as Error);
  166. }
  167. }
  168. async usage() {
  169. return {
  170. used: 0,
  171. total: 0,
  172. };
  173. }
  174. async models(): Promise<LLMModel[]> {
  175. return [];
  176. }
  177. }