deepSeek.ts 7.8 KB

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