bigmodel.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 api from "@/app/api/api";
  17. export class BigModelApi implements LLMApi {
  18. public baseURL: string;
  19. public apiPath: string;
  20. constructor() {
  21. this.baseURL = '/bigmodel-api';
  22. this.apiPath = this.baseURL + '/bigmodel/api/model-api/sse-invoke';
  23. }
  24. async chat(options: ChatOptions) {
  25. const messages = options.messages.map((item) => {
  26. return {
  27. role: item.role,
  28. content: getMessageTextContent(item),
  29. }
  30. });
  31. const userMessages = messages.filter(item => item.content);
  32. if (userMessages.length % 2 === 0) {
  33. userMessages.unshift({
  34. role: "user",
  35. content: "⠀",
  36. });
  37. }
  38. // 大模型参数
  39. const params: any = {
  40. appId: options.config.appId,// 应用id
  41. prompt: userMessages,
  42. // 进阶配置
  43. request_id: 'jkec2024-knowledge-base',
  44. returnType: undefined,
  45. knowledge_ids: undefined,
  46. document_ids: undefined,
  47. };
  48. const controller = new AbortController();
  49. options.onController?.(controller);
  50. try {
  51. const chatPath = this.apiPath;
  52. const chatPayload = {
  53. method: "POST",
  54. body: JSON.stringify(params),
  55. signal: controller.signal,
  56. headers: {
  57. 'Content-Type': 'application/json',
  58. Authorization: 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQwNDljOTY1LWZiYjYtNDIyNy1iNWExLWEwZGYwMWRmMzE5YyJ9.Ij4Ztl-MX1jrJHBPg7NV35MiaXLTyrSdMlwQaKZsGI0S9BD6TZFrRo6yqhXsSX2K8-hhYLTipE7_lO69cnZyPw',
  59. },
  60. };
  61. const requestTimeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  62. let responseText = "";
  63. let remainText = "";
  64. let finished = false;
  65. function animateResponseText() {
  66. if (finished || controller.signal.aborted) {
  67. responseText += remainText;
  68. if (responseText?.length === 0) {
  69. // options.onError?.(new Error("empty response from server"));
  70. options.onError?.(new Error("请求已中止,请检查网络环境。"));
  71. }
  72. return;
  73. }
  74. if (remainText.length > 0) {
  75. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  76. const fetchText = remainText.slice(0, fetchCount);
  77. responseText += fetchText;
  78. remainText = remainText.slice(fetchCount);
  79. options.onUpdate?.(responseText, fetchText);
  80. }
  81. requestAnimationFrame(animateResponseText);
  82. }
  83. animateResponseText();
  84. const finish = () => {
  85. if (!finished) {
  86. finished = true;
  87. options.onFinish(responseText + remainText);
  88. }
  89. };
  90. controller.signal.onabort = finish;
  91. fetchEventSource(chatPath, {
  92. ...chatPayload,
  93. async onopen(res) {
  94. clearTimeout(requestTimeoutId);
  95. const contentType = res.headers.get("content-type");
  96. if (contentType?.startsWith("text/plain")) {
  97. responseText = await res.clone().text();
  98. return finish();
  99. }
  100. if (
  101. !res.ok ||
  102. !res.headers.get("content-type")?.startsWith(EventStreamContentType) ||
  103. res.status !== 200
  104. ) {
  105. const responseTexts = [responseText];
  106. let extraInfo = await res.clone().text();
  107. try {
  108. const resJson = await res.clone().json();
  109. extraInfo = prettyObject(resJson);
  110. } catch { }
  111. if (res.status === 401) {
  112. responseTexts.push(Locale.Error.Unauthorized);
  113. }
  114. if (extraInfo) {
  115. responseTexts.push(extraInfo);
  116. }
  117. responseText = responseTexts.join("\n\n");
  118. return finish();
  119. }
  120. },
  121. onmessage: (msg) => {
  122. const info = JSON.parse(msg.data);
  123. if (info.event === 'finish') {
  124. return finish();
  125. }
  126. // 获取当前的数据
  127. const currentData = info.data;
  128. remainText += currentData;
  129. },
  130. async onclose() {
  131. finish();
  132. const session = useChatStore.getState().sessions[0];
  133. const data = {
  134. id: session.id,
  135. messages: session.messages.map(item => ({
  136. id: item.id,
  137. date: item.date,
  138. role: item.role,
  139. content: item.content,
  140. })),
  141. };
  142. await api.post('bigmodel/api/dialog/save', data);
  143. },
  144. onerror(e) {
  145. options.onError?.(e);
  146. throw e;
  147. },
  148. openWhenHidden: true,
  149. });
  150. } catch (e) {
  151. options.onError?.(e as Error);
  152. }
  153. }
  154. async usage() {
  155. return {
  156. used: 0,
  157. total: 0,
  158. };
  159. }
  160. async models(): Promise<LLMModel[]> {
  161. return [];
  162. }
  163. }