fix: 支持原文件下载,同时将postgres地址由localhost变更为8.152.207.171

This commit is contained in:
sophie committed 2026-04-03 11:30:49 +08:00
1 parent 70f95e9f5c
commit c380248502
12 files changed
+1273 -273

No files matched your search

+148 -105
View File
@@ -23,6 +23,75 @@ interface ChatMessage {
attribution_parts?: string[];
}
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (Array.isArray(resources.data)) return resources.data;
return [];
};
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 exists = msg.retriever_resources.some(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (!exists) {
msg.retriever_resources.push(item);
}
}
};
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));
}
};
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 渲染
@@ -81,6 +150,11 @@ export function useChat() {
* agentId: 目标 Agent ID
*/
const sendMessage = async (query: string, agentId: number) => {
console.info('[chat][send] start', {
agentId,
queryLength: query.length,
conversationId: conversationId.value,
});
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
@@ -105,8 +179,15 @@ export function useChat() {
})
});
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}`);
}
@@ -116,128 +197,90 @@ export function useChat() {
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;
// 解码二进制块为文本
const chunk = decoder.decode(value);
// SSE 数据可能包含多行,按双换行符分割
const lines = chunk.split('\n\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
// 解析 JSON 数据
const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
botMsg.content += data.answer;
applyEventMetadata(botMsg, data);
} else if (data.event === 'message_end') {
// 记录会话 ID,便于后续发送反馈
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
applyEventMetadata(botMsg, data);
} else if (data.event === 'agent_message' || data.event === 'workflow_finished') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
applyEventMetadata(botMsg, data);
} else if (data.event === 'error') {
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
}
} catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
// 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);
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
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.event === 'message' || data.event === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
botMsg.content += data.answer;
console.debug('[chat][sse] append answer chunk', {
event: data.event,
appended: data.answer.length,
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
} else if (data.event === 'message_end' || data.event === 'workflow_finished') {
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
// Some providers may put final answer on message_end/workflow events.
if (typeof data.answer === 'string' && data.answer.length > 0) {
botMsg.content += data.answer;
console.debug('[chat][sse] append final answer', {
event: data.event,
appended: data.answer.length,
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
} else if (data.event === 'error') {
botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data);
}
} 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(e);
console.error('[chat][send] failed', e);
const botMsg = messages.value[botMsgIndex];
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
} finally {
isThinking.value = false;
console.info('[chat][send] end', {
messages: messages.value.length,
conversationId: conversationId.value,
});
}
};
return { messages, isThinking, conversationId, sendMessage };
}
const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return [];
if (Array.isArray(resources)) return resources;
if (Array.isArray(resources.data)) return resources.data;
return [];
};
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 exists = msg.retriever_resources.some(
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
);
if (!exists) {
msg.retriever_resources.push(item);
}
}
};
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));
}
};
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);
};