bigmodel.ts 5.5 KB

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