bigmodel.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. "use client";
  2. import { REQUEST_TIMEOUT_MS } from "@/app/constant";
  3. import { useChatStore } from "@/app/store";
  4. import {
  5. ChatOptions,
  6. LLMApi,
  7. LLMModel,
  8. } from "../api";
  9. import Locale from "../../locales";
  10. import {
  11. EventStreamContentType,
  12. fetchEventSource,
  13. } from "@fortaine/fetch-event-source";
  14. import { prettyObject } from "@/app/utils/format";
  15. import { getMessageTextContent } from "@/app/utils";
  16. import { bigModelApiKey, knowledgeId, template } from "../config";
  17. export class BigModelApi implements LLMApi {
  18. public useApi: 'public' | 'private';
  19. public publicPath: string;
  20. public privatePath: string;
  21. constructor() {
  22. this.useApi = 'private';
  23. this.publicPath = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
  24. this.privatePath = 'https://open.bigmodel.cn/api/llm-application/open/model-api/1828613766624038913/sse-invoke';
  25. }
  26. async chat(options: ChatOptions) {
  27. const messages = options.messages.map((item) => {
  28. return {
  29. role: item.role,
  30. content: getMessageTextContent(item),
  31. }
  32. });
  33. const userMessages = messages.filter(item => item.content);
  34. if (userMessages.length % 2 === 0) {
  35. userMessages.unshift({
  36. role: "user",
  37. content: "⠀",
  38. });
  39. }
  40. // 开放大模型参数
  41. const publicParams: any = {
  42. messages: userMessages,
  43. stream: true,// 流式回复
  44. model: 'glm-4-0520',// 模型
  45. temperature: 0.01,// 采样温度
  46. top_p: 0.7,// 核取样
  47. // 进阶配置
  48. tools: [
  49. {
  50. type: 'retrieval', // 工具类型为检索
  51. retrieval: {
  52. // 知识库ID
  53. knowledge_id: knowledgeId,
  54. // 知识库模板
  55. prompt_template: template.content,
  56. },
  57. },
  58. ],
  59. };
  60. // 私有大模型参数
  61. const privateParams: any = {
  62. prompt: userMessages,
  63. model: 'glm-4-0520',// 模型
  64. temperature: 0.01,// 采样温度
  65. top_p: 0.7,// 核取样
  66. // 进阶配置
  67. request_id: 'jianke2024',
  68. returnType: undefined,
  69. knowledge_ids: undefined,
  70. document_ids: undefined,
  71. };
  72. const controller = new AbortController();
  73. options.onController?.(controller);
  74. try {
  75. const chatPath = this.useApi === 'public' ? this.publicPath : this.privatePath;
  76. const chatPayload = {
  77. method: "POST",
  78. body: JSON.stringify(this.useApi === 'public' ? publicParams : privateParams),
  79. signal: controller.signal,
  80. headers: {
  81. 'Content-Type': 'application/json',
  82. // APIKey
  83. Authorization: bigModelApiKey
  84. },
  85. };
  86. const requestTimeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  87. let responseText = "";
  88. let remainText = "";
  89. let finished = false;
  90. function animateResponseText() {
  91. if (finished || controller.signal.aborted) {
  92. responseText += remainText;
  93. if (responseText?.length === 0) {
  94. options.onError?.(new Error("empty response from server"));
  95. }
  96. return;
  97. }
  98. if (remainText.length > 0) {
  99. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  100. const fetchText = remainText.slice(0, fetchCount);
  101. responseText += fetchText;
  102. remainText = remainText.slice(fetchCount);
  103. options.onUpdate?.(responseText, fetchText);
  104. }
  105. requestAnimationFrame(animateResponseText);
  106. }
  107. animateResponseText();
  108. const finish = () => {
  109. if (!finished) {
  110. finished = true;
  111. options.onFinish(responseText + remainText);
  112. }
  113. };
  114. controller.signal.onabort = finish;
  115. // 记录上次的 remainText
  116. let previousRemainText = "";
  117. fetchEventSource(chatPath, {
  118. ...chatPayload,
  119. async onopen(res) {
  120. clearTimeout(requestTimeoutId);
  121. const contentType = res.headers.get("content-type");
  122. if (contentType?.startsWith("text/plain")) {
  123. responseText = await res.clone().text();
  124. return finish();
  125. }
  126. if (
  127. !res.ok ||
  128. !res.headers.get("content-type")?.startsWith(EventStreamContentType) ||
  129. res.status !== 200
  130. ) {
  131. const responseTexts = [responseText];
  132. let extraInfo = await res.clone().text();
  133. try {
  134. const resJson = await res.clone().json();
  135. extraInfo = prettyObject(resJson);
  136. } catch { }
  137. if (res.status === 401) {
  138. responseTexts.push(Locale.Error.Unauthorized);
  139. }
  140. if (extraInfo) {
  141. responseTexts.push(extraInfo);
  142. }
  143. responseText = responseTexts.join("\n\n");
  144. return finish();
  145. }
  146. },
  147. onmessage: (msg) => {
  148. const handlePublicMessage = () => {
  149. if (msg.data === "[DONE]" || finished) {
  150. return finish();
  151. }
  152. const text = msg.data;
  153. try {
  154. const json = JSON.parse(text);
  155. const choices = json.choices as Array<{ delta: { content: string } }>;
  156. const delta = choices[0]?.delta?.content;
  157. if (delta) {
  158. remainText += delta;
  159. }
  160. } catch (e) {
  161. console.error("[Request] parse error", text, msg);
  162. }
  163. };
  164. const handlePrivateMessage = () => {
  165. if (msg.event === 'finish') {
  166. return finish();
  167. }
  168. // 获取当前的数据
  169. const currentData = msg.data;
  170. // 计算新增的字符
  171. const newChars = currentData.substring(previousRemainText.length);
  172. remainText += newChars;
  173. // 更新 previousRemainText
  174. previousRemainText = currentData;
  175. };
  176. if (this.useApi === 'public') {
  177. handlePublicMessage();
  178. } else {
  179. handlePrivateMessage();
  180. }
  181. },
  182. async onclose() {
  183. finish();
  184. const session = useChatStore.getState().sessions[0];
  185. const data = {
  186. id: session.id,
  187. messages: session.messages.map(item => ({
  188. id: item.id,
  189. date: item.date,
  190. role: item.role,
  191. content: item.content,
  192. })),
  193. };
  194. await fetch('/api/bigModel', {
  195. method: 'POST',
  196. body: JSON.stringify(data),
  197. });
  198. },
  199. onerror(e) {
  200. options.onError?.(e);
  201. throw e;
  202. },
  203. openWhenHidden: true,
  204. });
  205. } catch (e) {
  206. options.onError?.(e as Error);
  207. }
  208. }
  209. async usage() {
  210. return {
  211. used: 0,
  212. total: 0,
  213. };
  214. }
  215. async models(): Promise<LLMModel[]> {
  216. return [];
  217. }
  218. }