deepSeek.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 DeepSeekApi implements LLMApi {
  18. public baseURL: string;
  19. public apiPath: string;
  20. constructor() {
  21. // 蓝色模型纯聊天 不走知识库 就是直接和AI对话
  22. // this.baseURL = 'http://192.168.3.209:18078';
  23. this.baseURL = '/deepseek-api';
  24. this.apiPath = this.baseURL + '/vllm/ai/chat';//线上地址
  25. // this.apiPath = this.baseURL + '/vllm/chat'; // 测试地址
  26. }
  27. async chat(options: ChatOptions) {
  28. const list: ChatOptions['messages'] = JSON.parse(JSON.stringify(options.messages)) || [];
  29. const backList = list.reverse();
  30. const item = backList.find((item) => {
  31. if (item.document) {
  32. if (item.document.id) {
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. } else {
  38. return false;
  39. }
  40. });
  41. const messages = options.messages.map((item) => {
  42. return {
  43. role: item.role,
  44. content: getMessageTextContent(item),
  45. }
  46. });
  47. const userMessages = messages.filter(item => item.content);
  48. if (userMessages.length % 2 === 0) {
  49. userMessages.unshift({
  50. role: "user",
  51. content: "⠀",
  52. });
  53. }
  54. const isDeepThink = useChatStore.getState().isDeepThink;
  55. // 参数
  56. const params = {
  57. // model: 'DeepSeek-R1-Distill-Qwen-14B',
  58. model: 'Qwen3-30B',
  59. enable_think: isDeepThink,
  60. messages: userMessages,
  61. stream: true,
  62. document_id: (item && item.document) ? item.document.id : undefined,
  63. // 进阶配置
  64. max_tokens: undefined,
  65. temperature: undefined,
  66. web_search: options.config.web_search,
  67. };
  68. const controller = new AbortController();
  69. options.onController?.(controller);
  70. try {
  71. const userInfo = localStorage.getItem('userInfo');
  72. const token = userInfo ? JSON.parse(userInfo).token : "";
  73. const chatPath = this.apiPath;
  74. const chatPayload = {
  75. method: "POST",
  76. body: JSON.stringify(params),
  77. signal: controller.signal,
  78. headers: {
  79. 'Content-Type': 'application/json',
  80. 'Authorization': token
  81. },
  82. };
  83. const requestTimeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  84. let responseText = "";
  85. let remainText = "";
  86. let finished = false;
  87. function animateResponseText() {
  88. if (finished || controller.signal.aborted) {
  89. responseText += remainText;
  90. if (responseText?.length === 0) {
  91. options.onError?.(new Error("请求已中止,请检查网络环境。"));
  92. }
  93. return;
  94. }
  95. if (remainText.length > 0) {
  96. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  97. const fetchText = remainText.slice(0, fetchCount);
  98. responseText += fetchText;
  99. remainText = remainText.slice(fetchCount);
  100. options.onUpdate?.(responseText, fetchText);
  101. }
  102. requestAnimationFrame(animateResponseText);
  103. }
  104. animateResponseText();
  105. const finish = () => {
  106. if (!finished) {
  107. finished = true;
  108. let text = responseText + remainText;
  109. options.onFinish(text);
  110. }
  111. };
  112. controller.signal.onabort = finish;
  113. let networkInfoPromise: Promise<void> | null = null;
  114. fetchEventSource(chatPath, {
  115. ...chatPayload,
  116. async onopen(res: any) {
  117. clearTimeout(requestTimeoutId);
  118. const contentType = res.headers.get("content-type");
  119. if (contentType?.startsWith("text/plain")) {
  120. responseText = await res.clone().text();
  121. return finish();
  122. }
  123. if (
  124. !res.ok ||
  125. !res.headers.get("content-type")?.startsWith(EventStreamContentType) ||
  126. res.status !== 200
  127. ) {
  128. const responseTexts = [responseText];
  129. let extraInfo = await res.clone().text();
  130. try {
  131. const resJson = await res.clone().json();
  132. extraInfo = prettyObject(resJson);
  133. } catch { }
  134. if (res.status === 401) {
  135. responseTexts.push(Locale.Error.Unauthorized);
  136. }
  137. if (extraInfo) {
  138. responseTexts.push(extraInfo);
  139. }
  140. responseText = responseTexts.join("\n\n");
  141. return finish();
  142. }
  143. },
  144. onmessage: (msg) => {
  145. const info = JSON.parse(msg.data);
  146. if (info.event === 'finish') {
  147. const isNetwork = useChatStore.getState().web_search;
  148. if (isNetwork) {// 联网搜索结果
  149. networkInfoPromise = (async () => {
  150. try {
  151. const res: any = await api.get(`bigmodel/api/web/search/${info.id}`);
  152. const networkInfo = {
  153. list: res.data.search_result,
  154. };
  155. useChatStore.getState().updateCurrentSession((session) => {
  156. session.messages = session.messages.map((item, index) => {
  157. if (index === session.messages.length - 1 && item.role !== 'user') {
  158. return {
  159. ...item,
  160. networkInfo: networkInfo,
  161. };
  162. } else {
  163. return {
  164. ...item,
  165. }
  166. }
  167. });
  168. });
  169. } catch (error) {
  170. console.error(error);
  171. }
  172. })();
  173. }
  174. return finish();
  175. }
  176. // 获取当前的数据
  177. const currentData = info.data;
  178. const formatStart = '```think';
  179. const formatEnd = 'think```';
  180. if (currentData?.startsWith(formatStart)) {
  181. remainText += currentData.replace(formatStart, '```think\n');
  182. } else if (currentData?.startsWith(formatEnd)) {
  183. remainText += currentData.replace(formatEnd, '```');
  184. } else {
  185. remainText += currentData;
  186. }
  187. },
  188. async onclose() {
  189. finish();
  190. if (networkInfoPromise) {
  191. await networkInfoPromise; // 等待 networkInfo 加载完成
  192. }
  193. const session = useChatStore.getState().sessions[0];
  194. const item = session.messages.find(item => item.role === 'user');
  195. const dialogName = item ? item.content : '新的聊天';
  196. const data = {
  197. id: session.id,
  198. appId: '1881269958412521255',
  199. userId: undefined,
  200. dialogName: dialogName,
  201. messages: session.messages.map(item => ({
  202. id: item.id,
  203. date: item.date,
  204. role: item.role,
  205. content: item.content,
  206. document: item.document,
  207. networkInfo: item.networkInfo,
  208. })),
  209. };
  210. await api.post('bigmodel/api/dialog/save', data);
  211. },
  212. onerror(e) {
  213. options.onError?.(e);
  214. throw e;
  215. },
  216. openWhenHidden: true,
  217. });
  218. } catch (e) {
  219. options.onError?.(e as Error);
  220. }
  221. }
  222. async usage() {
  223. return {
  224. used: 0,
  225. total: 0,
  226. };
  227. }
  228. async models(): Promise<LLMModel[]> {
  229. return [];
  230. }
  231. }