deepSeek.ts 7.6 KB

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