/** * Agent页面组件 */ export default class Agent { constructor(container, route) { this.container = container; this.route = route; this.init(); } async init() { try { this.render(); this.bindEvents(); this.loadAgentStatus(); this.loadActionHistory(); } catch (error) { console.error('Agent init error:', error); this.showError(error); } } render() { this.container.innerHTML = `
Agent状态
加载中...
加载Agent状态...
控制面板
Agent对话
暂无对话记录
工具统计
加载中...
LLM使用统计
加载中...
执行历史
加载中...
`; } bindEvents() { // 控制按钮事件 document.getElementById('start-monitoring-btn').addEventListener('click', () => { this.startMonitoring(); }); document.getElementById('stop-monitoring-btn').addEventListener('click', () => { this.stopMonitoring(); }); document.getElementById('run-analysis-btn').addEventListener('click', () => { this.runAnalysis(); }); document.getElementById('trigger-sample-btn').addEventListener('click', () => { this.triggerSampleActions(); }); // 对话事件 document.getElementById('send-chat-btn').addEventListener('click', () => { this.sendChatMessage(); }); document.getElementById('chat-input').addEventListener('keypress', (e) => { if (e.key === 'Enter') { this.sendChatMessage(); } }); // 清空历史 document.getElementById('clear-history-btn').addEventListener('click', () => { this.clearHistory(); }); // 定期刷新状态 this.statusInterval = setInterval(() => { this.loadAgentStatus(); }, 5000); } async loadAgentStatus() { try { const response = await fetch('/api/agent/status'); const data = await response.json(); const statusDiv = document.getElementById('agent-status'); if (data.success) { const status = data.status || 'unknown'; const activeGoals = data.active_goals || 0; const availableTools = data.available_tools || 0; let statusClass = 'text-warning'; let statusText = '未知状态'; switch (status) { case 'active': statusClass = 'text-success'; statusText = '运行中'; break; case 'inactive': statusClass = 'text-secondary'; statusText = '未激活'; break; case 'error': statusClass = 'text-danger'; statusText = '错误'; break; } statusDiv.innerHTML = `
${statusText}
${activeGoals}
活跃目标
${availableTools}
可用工具
`; } else { statusDiv.innerHTML = `
Agent服务不可用
`; } } catch (error) { console.error('加载Agent状态失败:', error); document.getElementById('agent-status').innerHTML = `
加载状态失败
`; } } async loadActionHistory() { try { const response = await fetch('/api/agent/action-history?limit=20'); const data = await response.json(); const historyDiv = document.getElementById('action-history'); if (data.success && data.history.length > 0) { let html = '
'; html += ''; data.history.forEach(action => { const timestamp = new Date(action.timestamp).toLocaleString(); const statusClass = action.success ? 'text-success' : 'text-danger'; const statusText = action.success ? '成功' : '失败'; html += ``; }); html += '
时间动作状态详情
${timestamp} ${action.action_type || '未知'} ${statusText} ${action.details || ''}
'; historyDiv.innerHTML = html; } else { historyDiv.innerHTML = '
暂无执行历史
'; } } catch (error) { console.error('加载执行历史失败:', error); document.getElementById('action-history').innerHTML = '
加载历史失败
'; } } async loadToolsStats() { try { const response = await fetch('/api/agent/tools/stats'); const data = await response.json(); const statsDiv = document.getElementById('tools-stats'); if (data.success) { const tools = data.tools || []; const performance = data.performance || {}; let html = `
工具数量: ${tools.length}
`; if (tools.length > 0) { html += '
可用工具:
'; } statsDiv.innerHTML = html; } else { statsDiv.innerHTML = '
获取工具统计失败
'; } } catch (error) { console.error('加载工具统计失败:', error); document.getElementById('tools-stats').innerHTML = '
加载失败
'; } } async loadLLMStats() { try { const response = await fetch('/api/agent/llm-stats'); const data = await response.json(); const statsDiv = document.getElementById('llm-stats'); if (data.success) { const stats = data.stats || {}; let html = ''; if (stats.total_requests) { html += `
总请求数: ${stats.total_requests}
`; } if (stats.success_rate !== undefined) { html += `
成功率: ${(stats.success_rate * 100).toFixed(1)}%
`; } if (stats.average_response_time) { html += `
平均响应时间: ${stats.average_response_time.toFixed(2)}s
`; } if (!html) { html = '
暂无统计数据
'; } statsDiv.innerHTML = html; } else { statsDiv.innerHTML = '
获取LLM统计失败
'; } } catch (error) { console.error('加载LLM统计失败:', error); document.getElementById('llm-stats').innerHTML = '
加载失败
'; } } async startMonitoring() { try { const response = await fetch('/api/agent/monitoring/start', { method: 'POST' }); const data = await response.json(); if (data.success) { if (window.showToast) { window.showToast('监控已启动', 'success'); } this.loadAgentStatus(); } else { if (window.showToast) { window.showToast(data.message || '启动监控失败', 'error'); } } } catch (error) { console.error('启动监控失败:', error); if (window.showToast) { window.showToast('网络错误', 'error'); } } } async stopMonitoring() { try { const response = await fetch('/api/agent/monitoring/stop', { method: 'POST' }); const data = await response.json(); if (data.success) { if (window.showToast) { window.showToast('监控已停止', 'success'); } this.loadAgentStatus(); } else { if (window.showToast) { window.showToast(data.message || '停止监控失败', 'error'); } } } catch (error) { console.error('停止监控失败:', error); if (window.showToast) { window.showToast('网络错误', 'error'); } } } async runAnalysis() { try { const response = await fetch('/api/agent/intelligent-analysis', { method: 'POST' }); const data = await response.json(); if (data.success) { if (window.showToast) { window.showToast('智能分析完成', 'success'); } this.loadActionHistory(); } else { if (window.showToast) { window.showToast('分析失败', 'error'); } } } catch (error) { console.error('运行分析失败:', error); if (window.showToast) { window.showToast('网络错误', 'error'); } } } async triggerSampleActions() { try { const response = await fetch('/api/agent/trigger-sample', { method: 'POST' }); const data = await response.json(); if (data.success) { if (window.showToast) { window.showToast('示例动作已触发', 'success'); } this.loadActionHistory(); } else { if (window.showToast) { window.showToast('触发示例动作失败', 'error'); } } } catch (error) { console.error('触发示例动作失败:', error); if (window.showToast) { window.showToast('网络错误', 'error'); } } } async sendChatMessage() { const input = document.getElementById('chat-input'); const message = input.value.trim(); if (!message) { return; } // 添加用户消息到界面 this.addMessageToChat('user', message); input.value = ''; try { const response = await fetch('/api/agent/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: message, context: { user_id: 'admin' } }) }); const data = await response.json(); if (data.success) { // 添加Agent回复到界面 this.addMessageToChat('agent', data.response); } else { this.addMessageToChat('agent', '抱歉,处理您的请求时出现错误。'); } } catch (error) { console.error('发送消息失败:', error); this.addMessageToChat('agent', '网络错误,请稍后重试。'); } } addMessageToChat(sender, message) { const chatMessages = document.getElementById('chat-messages'); const messageDiv = document.createElement('div'); messageDiv.className = `chat-message ${sender === 'user' ? 'text-end' : ''}`; const time = new Date().toLocaleTimeString(); messageDiv.innerHTML = `
${message}
${time}
`; chatMessages.appendChild(messageDiv); chatMessages.scrollTop = chatMessages.scrollHeight; } async clearHistory() { if (!confirm('确定要清空所有执行历史吗?')) { return; } try { const response = await fetch('/api/agent/clear-history', { method: 'POST' }); const data = await response.json(); if (data.success) { if (window.showToast) { window.showToast('历史已清空', 'success'); } this.loadActionHistory(); } else { if (window.showToast) { window.showToast('清空历史失败', 'error'); } } } catch (error) { console.error('清空历史失败:', error); if (window.showToast) { window.showToast('网络错误', 'error'); } } } showError(error) { this.container.innerHTML = `

页面加载失败

${error.message || '未知错误'}

`; } destroy() { if (this.statusInterval) { clearInterval(this.statusInterval); } } }