deepSeek.ts 6.9 KB

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