260323 function add report chat and front

This commit is contained in:
super committed 2026-03-23 00:54:14 +08:00
1 parent 605317c2b2
commit 5e8ea03b6c
16 files changed
+2351 -100

No files matched your search

+131 -15
View File
@@ -7,12 +7,28 @@
*/
import { ref } from 'vue';
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;
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
}
export function useChat() {
/**
* messages: 响应式消息列表,用于 UI 渲染
* 结构: [{ role: 'user'|'assistant', content: string }]
*/
const messages = ref<any[]>([]);
const messages = ref<ChatMessage[]>([]);
/**
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
@@ -26,17 +42,29 @@ export function useChat() {
const conversationId = ref<string | null>(null);
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return {};
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
const candidates = [
sessionStorage.getItem('hxops_user'),
localStorage.getItem('hxops_user'),
];
for (const stored of candidates) {
if (!stored) continue;
try {
const data = JSON.parse(stored) as any;
const user = data.user || data;
if (!user?.username || !user?.role) continue;
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
} catch (e) {
continue;
}
}
return headers;
return {};
};
/**
@@ -56,7 +84,12 @@ export function useChat() {
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
const botMsgIndex = messages.value.push({ role: 'assistant', content: '' }) - 1;
const botMsgIndex = messages.value.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: []
}) - 1;
isThinking.value = true;
@@ -100,14 +133,26 @@ export function useChat() {
const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') {
messages.value[botMsgIndex].content += data.answer;
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') {
messages.value[botMsgIndex].content += `\n[Error: ${data.message}]`;
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
}
} catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
@@ -117,7 +162,10 @@ export function useChat() {
}
} catch (e: any) {
console.error(e);
messages.value[botMsgIndex].content += `\n[Error: ${e.message || 'Network Issue'}]`;
const botMsg = messages.value[botMsgIndex];
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
} finally {
isThinking.value = false;
}
@@ -125,3 +173,71 @@ export function useChat() {
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);
};
@@ -0,0 +1,44 @@
/**
* useReportLayoutStorage.ts
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
*/
const getCurrentAuthUser = () => {
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.getItem('hxops_user');
if (!stored) return null;
try {
const data = JSON.parse(stored);
return data.user || data;
} catch {
return null;
}
};
const getCurrentIdentity = () => {
const user = getCurrentAuthUser();
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
};
const getReportLayoutStorageKey = (table: string) => {
return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`;
};
export const loadReportLayoutPref = <T = any>(table: string): T | null => {
try {
const raw = localStorage.getItem(getReportLayoutStorageKey(table));
if (!raw) return null;
return JSON.parse(raw) as T;
} catch {
return null;
}
};
export const saveReportLayoutPref = (table: string, payload: unknown) => {
try {
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
} catch {
// Ignore storage write failure to avoid blocking core report flow.
}
};