deepSeek.ts 7.5 KB

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