| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import { defHttp } from '/@/utils/http/axios';
- enum Api {
- unified = '/ventAI/api/chat',
- getHistoryList = '/ventAI/api/sessions',
- getDetail = '/ventAI/api/chat/history/',
- deleteSession = '/ventAI/api/sessions/',
- }
- /**
- * 历史会话接口
- */
- export const getHistoryList = (params) => defHttp.get({ url: Api.getHistoryList, params }, { joinParamsToUrl: true, isTransformResponse: false });
- /**
- * 获取历史会话详情
- * @param session_id - 会话ID
- */
- export const getDetail = (session_id: string) => defHttp.get({ url: Api.getDetail + session_id }, { isTransformResponse: false });
- /**
- * 删除会话
- * @param session_id - 会话ID
- */
- export const deleteSession = (session_id: string) => defHttp.delete({ url: Api.deleteSession + session_id }, { isTransformResponse: false });
- /**
- * 统一对话接口(SSE流式响应)
- * @param params.message - 用户输入的文本,必填
- * @param params.session_id - 会话唯一标识ID,不传参时服务端自动生成全新会话ID
- * @param params.file - 上传的PDF文件,可选
- * @param onChunk - 流式数据回调函数
- * @returns Promise<{ session_id: string }>
- */
- export const unifiedStream = async (
- params: { message: string; session_id?: string; file?: File },
- onChunk: (chunk: string) => void
- ): Promise<{ session_id: string }> => {
- try {
- const formData = new FormData();
- formData.append('message', params.message);
- if (params.session_id) {
- formData.append('session_id', params.session_id);
- }
- if (params.file) {
- formData.append('file', params.file);
- }
- const response = await fetch(Api.unified, {
- method: 'POST',
- body: formData,
- });
- if (!response.ok) {
- throw new Error(`HTTP错误: ${response.status}`);
- }
- const reader = response.body!.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- let sessionId = '';
- let isDone = false;
- // eslint-disable-next-line no-constant-condition
- while (true) {
- const { done, value } = await reader.read();
- if (done || isDone) break;
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop() || '';
- for (const line of lines) {
- if (line.trim() === '') continue;
- if (line.startsWith('data: ')) {
- const dataStr = line.replace(/^data: /, '');
- try {
- const data = JSON.parse(dataStr);
- onChunk(line);
- if (data.type === 'done' || data.type === 'error') {
- if (data.session_id) {
- sessionId = data.session_id;
- }
- isDone = true;
- break;
- }
- } catch (e) {
- console.warn('SSE数据解析失败:', dataStr);
- }
- }
- }
- if (isDone) break;
- }
- return { session_id: sessionId };
- } catch (error) {
- console.error('统一对话流式请求失败:', error);
- throw error;
- }
- };
|