/** * features/chat/composables/useChat.ts * SSE 流式对话核心:消息列表、runs、发送与接收。 */ import { ref } from 'vue'; import { getAuthHeaders } from '@/shared/utils/auth'; import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types'; const normalizeResources = (resources: unknown) => { if (!resources) return []; if (Array.isArray(resources)) return resources; if (typeof resources === 'object' && resources !== null && Array.isArray((resources as { data?: unknown }).data)) { return (resources as { data: unknown[] }).data; } return []; }; const addRetrieverResources = (msg: ChatMessage, resources: unknown) => { const list = normalizeResources(resources); if (list.length === 0) return; if (!msg.retriever_resources) msg.retriever_resources = []; for (const item of list) { const r = item as Record; const key = `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}`; const existingIndex = msg.retriever_resources.findIndex( (x) => `${x.document_name || ''}|${x.segment_id || ''}|${x.content || ''}` === key, ); if (existingIndex < 0) { msg.retriever_resources.push(item as RetrieverResource); } else { msg.retriever_resources[existingIndex] = { ...msg.retriever_resources[existingIndex], ...(item as object), }; } } }; const addAttributionParts = (msg: ChatMessage, value: unknown) => { 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') { const o = item as Record; pushUnique(String(o.content || o.text || o.title || JSON.stringify(item))); } } return; } if (typeof value === 'object' && value !== null) { const o = value as Record; pushUnique(String(o.content || o.text || o.title || JSON.stringify(value))); } }; const applyEventMetadata = (msg: ChatMessage, data: Record) => { const metadata = (data?.metadata || {}) as Record; 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() { const messages = ref([]); const isThinking = ref(false); const viewId = ref(0); const runs = ref([]); const activeRunId = ref(null); let runSeq = 0; const conversationId = ref(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; }; const loadConversationState = (id: string, nextMessages: ChatMessage[]) => { viewId.value += 1; activeRunId.value = null; isThinking.value = false; messages.value = nextMessages; conversationId.value = id; }; const normalizeStreamText = (text: string) => { if (!text) return ''; return text.replace(/\\n/g, '\n'); }; const sendMessage = async ( query: string, agentId: number, kbType = '企业知识库', 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; runMessages.push({ role: 'user', content: query }); 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 { 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, }), }); if (!response.ok) { const err = await response.json().catch(() => ({})); throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`); } const reader = response.body?.getReader(); const decoder = new TextDecoder(); if (!reader) throw new Error('No reader'); let buffer = ''; while (true) { const { done, value } = await reader.read(); if (done) break; 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; const payload = dataLines.map((l) => l.replace(/^data:\s?/, '')).join('\n'); if (!payload) continue; try { const data = JSON.parse(payload) as Record; 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); } if (botMsgIndex !== null) { const currentBotMsg = runMessages[botMsgIndex]; if (currentBotMsg) applyEventMetadata(currentBotMsg, data); } } else if (eventName === 'chat_perf') { const perf = (data.perf || {}) as Record; const nodes = Array.isArray(perf.nodes) ? perf.nodes : []; // eslint-disable-next-line no-console console.groupCollapsed( `[chat-perf] request=${String(perf.request_id || '')} total=${String(perf.total_ms ?? '')}ms ttft=${String(perf.ttft_ms ?? '')}ms`, ); if (nodes.length > 0) { // eslint-disable-next-line no-console console.table( nodes.map((node) => { const item = node as Record; return { index: item.index, title: item.title, type: item.node_type, elapsed_ms: item.elapsed_ms, at_ms: item.at_ms, status: item.status, }; }), ); } else { // eslint-disable-next-line no-console console.log(perf); } // eslint-disable-next-line no-console console.groupEnd(); } else if (eventName === 'message_end' || eventName === 'workflow_finished') { const relay = (data.hxops_relay || {}) as Record; if (relay.total_relay_ms != null) { // eslint-disable-next-line no-console console.info( `[chat-perf] hxops relay first_chunk=${String(relay.first_chunk_ms ?? '')}ms total=${String(relay.total_relay_ms ?? '')}ms`, ); } 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; } } 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}]`; 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 { // ignore malformed SSE frames } } } } catch (e: unknown) { run.status = 'error'; const botMsg = ensureBotMessage(); if (botMsg) { const message = e instanceof Error ? e.message : 'Network Issue'; botMsg.content += `\n[Error: ${message}]`; } } finally { if (messages.value === runMessages) { isThinking.value = false; } } }; return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, loadConversationState, sendMessage, }; }