deepSeek.ts 7.4 KB

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