deepSeek.ts 5.9 KB

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