bigmodel.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 = {
  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. },
  59. };
  60. const requestTimeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  61. let responseText = "";
  62. let remainText = "";
  63. let finished = false;
  64. function animateResponseText() {
  65. if (finished || controller.signal.aborted) {
  66. responseText += remainText;
  67. if (responseText?.length === 0) {
  68. options.onError?.(new Error("请求已中止,请检查网络环境。"));
  69. }
  70. return;
  71. }
  72. if (remainText.length > 0) {
  73. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  74. const fetchText = remainText.slice(0, fetchCount);
  75. responseText += fetchText;
  76. remainText = remainText.slice(fetchCount);
  77. options.onUpdate?.(responseText, fetchText);
  78. }
  79. requestAnimationFrame(animateResponseText);
  80. }
  81. animateResponseText();
  82. const finish = () => {
  83. if (!finished) {
  84. finished = true;
  85. options.onFinish(responseText + remainText);
  86. }
  87. };
  88. controller.signal.onabort = finish;
  89. fetchEventSource(chatPath, {
  90. ...chatPayload,
  91. async onopen(res: any) {
  92. clearTimeout(requestTimeoutId);
  93. const contentType = res.headers.get("content-type");
  94. if (contentType?.startsWith("text/plain")) {
  95. responseText = await res.clone().text();
  96. return finish();
  97. }
  98. if (
  99. !res.ok ||
  100. !res.headers.get("content-type")?.startsWith(EventStreamContentType) ||
  101. res.status !== 200
  102. ) {
  103. const responseTexts = [responseText];
  104. let extraInfo = await res.clone().text();
  105. try {
  106. const resJson = await res.clone().json();
  107. extraInfo = prettyObject(resJson);
  108. } catch { }
  109. if (res.status === 401) {
  110. responseTexts.push(Locale.Error.Unauthorized);
  111. }
  112. if (extraInfo) {
  113. responseTexts.push(extraInfo);
  114. }
  115. responseText = responseTexts.join("\n\n");
  116. return finish();
  117. }
  118. },
  119. onmessage: (msg) => {
  120. const info = JSON.parse(msg.data);
  121. if (info.event === 'finish') {
  122. return finish();
  123. }
  124. // 获取当前的数据
  125. const currentData = info.data;
  126. remainText += currentData;
  127. },
  128. async onclose() {
  129. finish();
  130. const session = useChatStore.getState().sessions[0];
  131. const data = {
  132. id: session.id,
  133. appId: session.appId,
  134. userId: undefined,
  135. dialogName: session.topic,
  136. messages: session.messages.map(item => ({
  137. id: item.id,
  138. date: item.date,
  139. role: item.role,
  140. content: item.content,
  141. })),
  142. };
  143. await api.post('bigmodel/api/dialog/save', data);
  144. },
  145. onerror(e) {
  146. options.onError?.(e);
  147. throw e;
  148. },
  149. openWhenHidden: true,
  150. });
  151. } catch (e) {
  152. options.onError?.(e as Error);
  153. }
  154. }
  155. async usage() {
  156. return {
  157. used: 0,
  158. total: 0,
  159. };
  160. }
  161. async models(): Promise<LLMModel[]> {
  162. return [];
  163. }
  164. }