deepSeek.ts 7.3 KB

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