deepSeek.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 chatPath = this.apiPath;
  70. const chatPayload = {
  71. method: "POST",
  72. body: JSON.stringify(params),
  73. signal: controller.signal,
  74. headers: {
  75. 'Content-Type': 'application/json',
  76. },
  77. };
  78. const requestTimeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  79. let responseText = "";
  80. let remainText = "";
  81. let finished = false;
  82. function animateResponseText() {
  83. if (finished || controller.signal.aborted) {
  84. responseText += remainText;
  85. if (responseText?.length === 0) {
  86. options.onError?.(new Error("请求已中止,请检查网络环境。"));
  87. }
  88. return;
  89. }
  90. if (remainText.length > 0) {
  91. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  92. const fetchText = remainText.slice(0, fetchCount);
  93. responseText += fetchText;
  94. remainText = remainText.slice(fetchCount);
  95. options.onUpdate?.(responseText, fetchText);
  96. }
  97. requestAnimationFrame(animateResponseText);
  98. }
  99. animateResponseText();
  100. const finish = () => {
  101. if (!finished) {
  102. finished = true;
  103. let text = responseText + remainText;
  104. options.onFinish(text);
  105. }
  106. };
  107. controller.signal.onabort = finish;
  108. let networkInfoPromise: Promise<void> | null = null;
  109. fetchEventSource(chatPath, {
  110. ...chatPayload,
  111. async onopen(res: any) {
  112. clearTimeout(requestTimeoutId);
  113. const contentType = res.headers.get("content-type");
  114. if (contentType?.startsWith("text/plain")) {
  115. responseText = await res.clone().text();
  116. return finish();
  117. }
  118. if (
  119. !res.ok ||
  120. !res.headers.get("content-type")?.startsWith(EventStreamContentType) ||
  121. res.status !== 200
  122. ) {
  123. const responseTexts = [responseText];
  124. let extraInfo = await res.clone().text();
  125. try {
  126. const resJson = await res.clone().json();
  127. extraInfo = prettyObject(resJson);
  128. } catch { }
  129. if (res.status === 401) {
  130. responseTexts.push(Locale.Error.Unauthorized);
  131. }
  132. if (extraInfo) {
  133. responseTexts.push(extraInfo);
  134. }
  135. responseText = responseTexts.join("\n\n");
  136. return finish();
  137. }
  138. },
  139. onmessage: (msg) => {
  140. const info = JSON.parse(msg.data);
  141. if (info.event === 'finish') {
  142. const isNetwork = useChatStore.getState().web_search;
  143. if (isNetwork) {// 联网搜索结果
  144. networkInfoPromise = (async () => {
  145. try {
  146. const res: any = await api.get(`bigmodel/api/web/search/${info.id}`);
  147. const networkInfo = {
  148. list: res.data.search_result,
  149. };
  150. useChatStore.getState().updateCurrentSession((session) => {
  151. session.messages = session.messages.map((item, index) => {
  152. if (index === session.messages.length - 1 && item.role !== 'user') {
  153. return {
  154. ...item,
  155. networkInfo: networkInfo,
  156. };
  157. } else {
  158. return {
  159. ...item,
  160. }
  161. }
  162. });
  163. });
  164. } catch (error) {
  165. console.error(error);
  166. }
  167. })();
  168. }
  169. return finish();
  170. }
  171. // 获取当前的数据
  172. const currentData = info.data;
  173. const formatStart = '```think';
  174. const formatEnd = 'think```';
  175. if (currentData?.startsWith(formatStart)) {
  176. remainText += currentData.replace(formatStart, '```think\n');
  177. } else if (currentData?.startsWith(formatEnd)) {
  178. remainText += currentData.replace(formatEnd, '```');
  179. } else {
  180. remainText += currentData;
  181. }
  182. },
  183. async onclose() {
  184. finish();
  185. if (networkInfoPromise) {
  186. await networkInfoPromise; // 等待 networkInfo 加载完成
  187. }
  188. const session = useChatStore.getState().sessions[0];
  189. const item = session.messages.find(item => item.role === 'user');
  190. const dialogName = item ? item.content : '新的聊天';
  191. const data = {
  192. id: session.id,
  193. appId: '1881269958412521255',
  194. userId: undefined,
  195. dialogName: dialogName,
  196. messages: session.messages.map(item => ({
  197. id: item.id,
  198. date: item.date,
  199. role: item.role,
  200. content: item.content,
  201. document: item.document,
  202. networkInfo: item.networkInfo,
  203. })),
  204. };
  205. await api.post('bigmodel/api/dialog/save', data);
  206. },
  207. onerror(e) {
  208. options.onError?.(e);
  209. throw e;
  210. },
  211. openWhenHidden: true,
  212. });
  213. } catch (e) {
  214. options.onError?.(e as Error);
  215. }
  216. }
  217. async usage() {
  218. return {
  219. used: 0,
  220. total: 0,
  221. };
  222. }
  223. async models(): Promise<LLMModel[]> {
  224. return [];
  225. }
  226. }