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