400 lines
14 KiB
TypeScript
400 lines
14 KiB
TypeScript
|
|
/**
|
|
* frontend/src/composables/useChat.ts
|
|
* 文件用途:前端 SSE 聊天 Hook
|
|
* 引用文件:vue
|
|
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
|
|
*/
|
|
import { ref } from 'vue';
|
|
import { getAuthHeaders } from '../utils/auth';
|
|
|
|
interface RetrieverResource {
|
|
// 知识库/检索来源的基础字段,具体键可能因后端返回而扩展
|
|
dataset_name?: string;
|
|
document_name?: string;
|
|
segment_id?: string;
|
|
content?: string;
|
|
score?: number;
|
|
[key: string]: any;
|
|
}
|
|
|
|
interface ChatMessage {
|
|
// 对话消息结构:用户/助手文本 + 可选的来源与归因信息
|
|
role: 'user' | 'assistant';
|
|
content: string;
|
|
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result';
|
|
retriever_resources?: RetrieverResource[];
|
|
attribution_parts?: string[];
|
|
chat_log_id?: number;
|
|
payload?: any;
|
|
local_id?: string;
|
|
local_only?: boolean;
|
|
rated?: boolean;
|
|
}
|
|
|
|
type RunStatus = 'running' | 'done' | 'error';
|
|
|
|
interface ChatRun {
|
|
runId: number;
|
|
agentId: number;
|
|
viewId: number;
|
|
query: string;
|
|
messages: ChatMessage[];
|
|
conversationId: string | null;
|
|
status: RunStatus;
|
|
createdAt: string;
|
|
}
|
|
|
|
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
|
|
const normalizeResources = (resources: any): RetrieverResource[] => {
|
|
if (!resources) return [];
|
|
if (Array.isArray(resources)) return resources;
|
|
if (Array.isArray(resources.data)) return resources.data;
|
|
return [];
|
|
};
|
|
|
|
// 将检索来源资源合并到消息中,并按文档名+片段ID+内容做去重和更新
|
|
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
|
const list = normalizeResources(resources);
|
|
if (list.length === 0) return;
|
|
if (!msg.retriever_resources) msg.retriever_resources = [];
|
|
for (const item of list) {
|
|
// 使用稳定键进行去重,避免同一条来源在多事件中重复展示
|
|
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
|
const existingIndex = msg.retriever_resources.findIndex(
|
|
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
|
);
|
|
if (existingIndex < 0) {
|
|
msg.retriever_resources.push(item);
|
|
} else {
|
|
// 存在则合并,确保后续带有 enrich 链接的字段能覆盖进去
|
|
msg.retriever_resources[existingIndex] = {
|
|
...msg.retriever_resources[existingIndex],
|
|
...item
|
|
};
|
|
}
|
|
}
|
|
};
|
|
|
|
// 归一化并合并归因内容(支持 string/array/object),按文本去重
|
|
const addAttributionParts = (msg: ChatMessage, value: any) => {
|
|
if (!value) return;
|
|
if (!msg.attribution_parts) msg.attribution_parts = [];
|
|
|
|
// 只收集非空文本,且保证唯一
|
|
const pushUnique = (text: string) => {
|
|
const v = text.trim();
|
|
if (!v) return;
|
|
if (!msg.attribution_parts!.includes(v)) {
|
|
msg.attribution_parts!.push(v);
|
|
}
|
|
};
|
|
|
|
if (typeof value === 'string') {
|
|
pushUnique(value);
|
|
return;
|
|
}
|
|
|
|
if (Array.isArray(value)) {
|
|
for (const item of value) {
|
|
if (typeof item === 'string') {
|
|
pushUnique(item);
|
|
} else if (item && typeof item === 'object') {
|
|
pushUnique(item.content || item.text || item.title || JSON.stringify(item));
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (typeof value === 'object') {
|
|
pushUnique(value.content || value.text || value.title || JSON.stringify(value));
|
|
}
|
|
};
|
|
|
|
// 从事件顶层与 metadata 中提取来源/归因信息并写回当前消息
|
|
const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
|
const metadata = data?.metadata || {};
|
|
addRetrieverResources(msg, data?.retriever_resources);
|
|
addRetrieverResources(msg, metadata?.retriever_resources);
|
|
addRetrieverResources(msg, metadata?.retrieverResources);
|
|
|
|
addAttributionParts(msg, data?.annotations);
|
|
addAttributionParts(msg, data?.annotation_reply);
|
|
addAttributionParts(msg, metadata?.annotations);
|
|
addAttributionParts(msg, metadata?.annotation_reply);
|
|
addAttributionParts(msg, data?.citation);
|
|
addAttributionParts(msg, metadata?.citation);
|
|
};
|
|
|
|
export function useChat() {
|
|
/**
|
|
* messages: 响应式消息列表,用于 UI 渲染
|
|
* 结构: [{ role: 'user'|'assistant', content: string }]
|
|
*/
|
|
const messages = ref<ChatMessage[]>([]);
|
|
|
|
/**
|
|
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
|
|
*/
|
|
const isThinking = ref(false);
|
|
|
|
const viewId = ref(0);
|
|
|
|
const runs = ref<ChatRun[]>([]);
|
|
const activeRunId = ref<number | null>(null);
|
|
let runSeq = 0;
|
|
|
|
/**
|
|
* conversationId: 当前会话 ID
|
|
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
|
|
*/
|
|
const conversationId = ref<string | null>(null);
|
|
|
|
const activateRun = (runId: number) => {
|
|
const run = runs.value.find((r) => r.runId === runId);
|
|
if (!run) return;
|
|
messages.value = run.messages;
|
|
conversationId.value = run.conversationId;
|
|
isThinking.value = run.status === 'running';
|
|
activeRunId.value = runId;
|
|
};
|
|
|
|
const createNewChatView = () => {
|
|
viewId.value += 1;
|
|
messages.value = [];
|
|
conversationId.value = null;
|
|
isThinking.value = false;
|
|
activeRunId.value = null;
|
|
};
|
|
|
|
/**
|
|
* sendMessage
|
|
* 用途:发送消息并处理 SSE 流式响应
|
|
* 核心逻辑:
|
|
* 1. 乐观更新 UI (立即显示用户消息)
|
|
* 2. Create assistant message lazily only after receiving real answer chunks.
|
|
* 3. 发起 Fetch POST 请求
|
|
* 4. 获取 Reader 流式读取
|
|
* 5. 逐块解码并追加到当前 AI 消息中
|
|
* 参数:
|
|
* query: 用户输入文本
|
|
* agentId: 目标 Agent ID
|
|
*/
|
|
const sendMessage = async (
|
|
query: string,
|
|
agentId: number,
|
|
kbType: string = '企业知识库',
|
|
files?: Array<
|
|
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
|
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
|
>,
|
|
) => {
|
|
const runViewId = viewId.value;
|
|
const runMessages = messages.value;
|
|
const run: ChatRun = {
|
|
runId: ++runSeq,
|
|
agentId,
|
|
viewId: runViewId,
|
|
query,
|
|
messages: runMessages,
|
|
conversationId: conversationId.value,
|
|
status: 'running',
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
runs.value.unshift(run);
|
|
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
|
activeRunId.value = run.runId;
|
|
console.info('[chat][send] start', {
|
|
agentId,
|
|
kbType,
|
|
queryLength: query.length,
|
|
conversationId: conversationId.value,
|
|
});
|
|
// 1. 乐观 UI 更新:立即将用户消息推入列表
|
|
runMessages.push({ role: 'user', content: query });
|
|
// Lazily create assistant message only when answer/error arrives.
|
|
let botMsgIndex: number | null = null;
|
|
const ensureBotMessage = () => {
|
|
if (botMsgIndex === null) {
|
|
botMsgIndex = runMessages.push({
|
|
role: 'assistant',
|
|
content: '',
|
|
retriever_resources: [],
|
|
attribution_parts: []
|
|
}) - 1;
|
|
}
|
|
return runMessages[botMsgIndex] || null;
|
|
};
|
|
|
|
isThinking.value = true;
|
|
|
|
try {
|
|
// 指向本地 Flask 端口 (需通过 Vite Proxy 转发到 5000)
|
|
const response = await fetch('/api/chat/completions', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
|
body: JSON.stringify({
|
|
query,
|
|
agent_id: agentId,
|
|
conversation_id: conversationId.value,
|
|
kb_type: kbType,
|
|
files: files && files.length > 0 ? files : undefined,
|
|
})
|
|
});
|
|
|
|
console.info('[chat][send] response', {
|
|
ok: response.ok,
|
|
status: response.status,
|
|
contentType: response.headers.get('content-type'),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const err = await response.json().catch(() => ({}));
|
|
console.error('[chat][send] non-ok response', err);
|
|
throw new Error(err.error || `Request failed with status ${response.status}`);
|
|
}
|
|
|
|
// 获取 ReadableStream 读取器
|
|
const reader = response.body?.getReader();
|
|
const decoder = new TextDecoder();
|
|
|
|
if (!reader) throw new Error('No reader');
|
|
|
|
// Loop read SSE stream; use a buffer to avoid dropping partial chunks.
|
|
let buffer = '';
|
|
while (true) {
|
|
const { done, value } = await reader.read();
|
|
if (done) break;
|
|
|
|
// Decode as stream and normalize CRLF so Windows-style SSE frames are parsed correctly.
|
|
buffer += decoder.decode(value, { stream: true });
|
|
buffer = buffer.replace(/\r\n/g, '\n');
|
|
const frames = buffer.split('\n\n');
|
|
buffer = frames.pop() || '';
|
|
|
|
for (const frame of frames) {
|
|
const dataLines = frame
|
|
.split('\n')
|
|
.map((l) => l.trim())
|
|
.filter((l) => l.startsWith('data:'));
|
|
if (dataLines.length === 0) continue;
|
|
|
|
// SSE allows multiple data lines in one event.
|
|
const payload = dataLines
|
|
.map((l) => l.replace(/^data:\s?/, ''))
|
|
.join('\n');
|
|
if (!payload) continue;
|
|
|
|
try {
|
|
const data = JSON.parse(payload);
|
|
console.debug('[chat][sse] event', {
|
|
event: data?.event,
|
|
answerLength: typeof data?.answer === 'string' ? data.answer.length : 0,
|
|
hasRetrieverResources: Boolean(data?.retriever_resources || data?.metadata?.retriever_resources),
|
|
conversationId: data?.conversation_id || conversationId.value,
|
|
});
|
|
|
|
if (data?.conversation_id) {
|
|
const cid = String(data.conversation_id);
|
|
if (!run.conversationId) run.conversationId = cid;
|
|
if (messages.value === runMessages) conversationId.value = cid;
|
|
}
|
|
|
|
const eventName = String(data.event || '');
|
|
if (eventName === 'message' || eventName === 'agent_message') {
|
|
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
|
const botMsg = ensureBotMessage();
|
|
if (!botMsg) continue;
|
|
botMsg.content += normalizeStreamText(data.answer);
|
|
console.debug('[chat][sse] append answer chunk', {
|
|
event: data.event,
|
|
appended: data.answer.length,
|
|
total: botMsg.content.length,
|
|
});
|
|
}
|
|
if (botMsgIndex !== null) {
|
|
const currentBotMsg = runMessages[botMsgIndex];
|
|
if (currentBotMsg) {
|
|
applyEventMetadata(currentBotMsg, data);
|
|
}
|
|
}
|
|
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
|
|
run.status = 'done';
|
|
if (messages.value === runMessages) isThinking.value = false;
|
|
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
|
|
const currentBotMsg = runMessages[botMsgIndex];
|
|
if (currentBotMsg) {
|
|
currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
|
}
|
|
}
|
|
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
|
const botMsg = ensureBotMessage();
|
|
if (!botMsg) continue;
|
|
const normalizedAnswer = normalizeStreamText(data.answer);
|
|
if (data.replace_answer) {
|
|
botMsg.content = normalizedAnswer;
|
|
} else {
|
|
botMsg.content += normalizedAnswer;
|
|
}
|
|
console.debug('[chat][sse] apply final answer', {
|
|
event: data.event,
|
|
replace: Boolean(data.replace_answer),
|
|
appended: data.answer.length,
|
|
total: botMsg.content.length,
|
|
});
|
|
}
|
|
if (botMsgIndex !== null) {
|
|
const currentBotMsg = runMessages[botMsgIndex];
|
|
if (currentBotMsg) {
|
|
applyEventMetadata(currentBotMsg, data);
|
|
}
|
|
}
|
|
} else if (eventName === 'error') {
|
|
const botMsg = ensureBotMessage();
|
|
if (!botMsg) continue;
|
|
botMsg.content += `\n[Error: ${data.message}]`;
|
|
console.error('[chat][sse] backend error event', data);
|
|
run.status = 'error';
|
|
if (messages.value === runMessages) isThinking.value = false;
|
|
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
|
const botMsg = ensureBotMessage();
|
|
if (!botMsg) continue;
|
|
botMsg.content += normalizeStreamText(data.answer);
|
|
}
|
|
} catch (e) {
|
|
// Ignore malformed or partial payload fragments.
|
|
console.warn('[chat][sse] parse failed', { payloadPreview: payload.slice(0, 200), error: e });
|
|
}
|
|
}
|
|
}
|
|
} catch (e: any) {
|
|
console.error('[chat][send] failed', e);
|
|
run.status = 'error';
|
|
const botMsg = ensureBotMessage();
|
|
if (botMsg) {
|
|
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
|
|
}
|
|
} finally {
|
|
if (messages.value === runMessages) {
|
|
isThinking.value = false;
|
|
console.info('[chat][send] end', {
|
|
messages: messages.value.length,
|
|
conversationId: conversationId.value,
|
|
});
|
|
} else {
|
|
console.info('[chat][send] end (detached)', {
|
|
activeConversationId: conversationId.value,
|
|
runViewId,
|
|
});
|
|
}
|
|
}
|
|
};
|
|
|
|
const normalizeStreamText = (text: string) => {
|
|
if (!text) return '';
|
|
return text.replace(/\\n/g, '\n');
|
|
};
|
|
|
|
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage };
|
|
}
|