feat: 实现智能Agent系统,集成大模型和智能决策

- 创建IntelligentAgent核心,支持预警处理和知识库置信度处理
- 集成LLM客户端,支持OpenAI、Anthropic和本地LLM
- 实现ActionExecutor动作执行器,支持多种动作类型
- 优化TSPAgentAssistant,集成大模型和智能决策能力
- 添加预警自动处理措施,包括重启服务、检查状态、通知等
- 实现知识库置信度处理,自动增强低置信度知识条目
- 支持动作执行历史记录和统计
- 提供LLM使用统计和监控功能
This commit is contained in:
zhaojie
2025-09-10 23:55:43 +08:00
parent c7043c13b0
commit 6ef72837a5
7 changed files with 1489 additions and 23 deletions

View File

@@ -14,13 +14,16 @@ import json
from src.main import TSPAssistant
from src.agent import AgentCore, AgentState
from src.agent.auto_monitor import AutoMonitorService
from src.agent.intelligent_agent import IntelligentAgent, AlertContext, KnowledgeContext
from src.agent.llm_client import LLMManager, LLMConfig
from src.agent.action_executor import ActionExecutor
logger = logging.getLogger(__name__)
class TSPAgentAssistant(TSPAssistant):
"""TSP Agent助手 - 增强版TSP助手具备完整Agent功能"""
def __init__(self):
def __init__(self, llm_config: Optional[LLMConfig] = None):
# 初始化基础TSP助手
super().__init__()
@@ -30,6 +33,24 @@ class TSPAgentAssistant(TSPAssistant):
# 初始化自动监控服务
self.auto_monitor = AutoMonitorService(self)
# 初始化LLM客户端
if llm_config:
self.llm_manager = LLMManager(llm_config)
else:
# 使用默认配置
default_config = LLMConfig(
provider="openai",
api_key="your-api-key-here",
model="gpt-3.5-turbo"
)
self.llm_manager = LLMManager(default_config)
# 初始化智能Agent
self.intelligent_agent = IntelligentAgent(self.llm_manager)
# 初始化动作执行器
self.action_executor = ActionExecutor(self)
# Agent特有功能
self.is_agent_mode = True
self.proactive_tasks = []
@@ -286,37 +307,84 @@ class TSPAgentAssistant(TSPAssistant):
# 检查预警
alerts = self.get_alerts()
if alerts.get("count", 0) > 0:
proactive_actions.append({
"type": "alert_response",
"description": f"发现 {alerts['count']} 个活跃预警",
"priority": "high",
"action": "需要立即处理预警"
})
# 创建预警上下文
alert_context = AlertContext(
alert_id=f"alert_{datetime.now().timestamp()}",
alert_type="system_alert",
severity="high",
description=f"发现 {alerts['count']} 个活跃预警",
affected_systems=["main_system"],
metrics={"alert_count": alerts['count']}
)
# 使用智能Agent处理预警
alert_actions = await self.intelligent_agent.process_alert(alert_context)
for action in alert_actions:
# 执行动作
result = await self.action_executor.execute_action(action)
proactive_actions.append({
"type": "alert_response",
"description": action.description,
"priority": action.priority,
"confidence": action.confidence,
"result": result
})
# 检查系统健康
system_status = self.get_system_status()
if system_status.get("health_score", 1.0) < 0.8:
proactive_actions.append({
"type": "system_maintenance",
"description": "系统健康状态不佳",
"priority": "medium",
"action": "建议进行系统维护"
})
# 创建系统健康预警上下文
health_alert_context = AlertContext(
alert_id=f"health_{datetime.now().timestamp()}",
alert_type="system_health",
severity="medium",
description="系统健康状态不佳",
affected_systems=["main_system"],
metrics={"health_score": system_status.get("health_score", 0.5)}
)
health_actions = await self.intelligent_agent.process_alert(health_alert_context)
for action in health_actions:
result = await self.action_executor.execute_action(action)
proactive_actions.append({
"type": "system_maintenance",
"description": action.description,
"priority": action.priority,
"confidence": action.confidence,
"result": result
})
# 检查知识库质量
knowledge_stats = self.knowledge_manager.get_knowledge_stats()
if knowledge_stats.get("average_confidence", 0.8) < 0.6:
proactive_actions.append({
"type": "knowledge_improvement",
"description": "知识库质量需要提升",
"priority": "low",
"action": "建议更新知识库"
})
# 处理低置信度知识
low_confidence_items = knowledge_stats.get("low_confidence_items", [])
for item in low_confidence_items:
knowledge_context = KnowledgeContext(
question=item.get("question", ""),
answer=item.get("answer", ""),
confidence=item.get("confidence", 0.3),
source=item.get("source", "unknown"),
category=item.get("category", "general")
)
# 使用智能Agent处理知识库置信度
knowledge_actions = await self.intelligent_agent.process_knowledge_confidence(knowledge_context)
for action in knowledge_actions:
result = await self.action_executor.execute_action(action)
proactive_actions.append({
"type": "knowledge_improvement",
"description": action.description,
"priority": action.priority,
"confidence": action.confidence,
"result": result
})
return {
"proactive_actions": proactive_actions,
"timestamp": datetime.now().isoformat(),
"agent_status": self.agent_core.get_status()
"agent_status": self.agent_core.get_status(),
"llm_usage": self.llm_manager.get_usage_stats()
}
except Exception as e:
@@ -422,16 +490,20 @@ class TSPAgentAssistant(TSPAssistant):
"monitoring_active": monitor_status["is_running"],
"status": "active" if self.is_agent_mode else "inactive",
"active_goals": 0, # 简化处理
"available_tools": 6, # 简化处理
"available_tools": 8, # 增加工具数量
"llm_usage": self.llm_manager.get_usage_stats(),
"action_executor_stats": self.action_executor.get_action_statistics(),
"tools": [
{"name": "search_knowledge", "usage_count": 0, "success_rate": 0.8},
{"name": "create_work_order", "usage_count": 0, "success_rate": 0.8},
{"name": "update_work_order", "usage_count": 0, "success_rate": 0.8},
{"name": "generate_response", "usage_count": 0, "success_rate": 0.8},
{"name": "analyze_data", "usage_count": 0, "success_rate": 0.8},
{"name": "send_notification", "usage_count": 0, "success_rate": 0.8}
{"name": "send_notification", "usage_count": 0, "success_rate": 0.8},
{"name": "process_alert", "usage_count": 0, "success_rate": 0.9},
{"name": "enhance_knowledge", "usage_count": 0, "success_rate": 0.7}
],
"execution_history": [],
"execution_history": self.action_executor.get_execution_history(10),
"auto_monitor": monitor_status
}
except Exception as e:
@@ -768,6 +840,97 @@ class TSPAgentAssistant(TSPAssistant):
logger.error(f"获取工单洞察失败: {e}")
return "获取工单数据失败"
def get_action_history(self, limit: int = 50) -> List[Dict[str, Any]]:
"""获取动作执行历史"""
try:
return self.action_executor.get_execution_history(limit)
except Exception as e:
logger.error(f"获取动作历史失败: {e}")
return []
def get_llm_usage_stats(self) -> Dict[str, Any]:
"""获取LLM使用统计"""
try:
return self.llm_manager.get_usage_stats()
except Exception as e:
logger.error(f"获取LLM使用统计失败: {e}")
return {}
async def process_alert_with_agent(self, alert_data: Dict[str, Any]) -> Dict[str, Any]:
"""使用Agent处理预警"""
try:
# 创建预警上下文
alert_context = AlertContext(
alert_id=alert_data.get("id", f"alert_{datetime.now().timestamp()}"),
alert_type=alert_data.get("type", "unknown"),
severity=alert_data.get("severity", "medium"),
description=alert_data.get("description", ""),
affected_systems=alert_data.get("affected_systems", []),
metrics=alert_data.get("metrics", {})
)
# 使用智能Agent处理预警
actions = await self.intelligent_agent.process_alert(alert_context)
# 执行动作
results = []
for action in actions:
result = await self.action_executor.execute_action(action)
results.append({
"action": action.description,
"priority": action.priority,
"confidence": action.confidence,
"result": result
})
return {
"success": True,
"alert_id": alert_context.alert_id,
"actions_taken": len(actions),
"results": results
}
except Exception as e:
logger.error(f"Agent处理预警失败: {e}")
return {"success": False, "error": str(e)}
async def enhance_knowledge_with_agent(self, knowledge_data: Dict[str, Any]) -> Dict[str, Any]:
"""使用Agent增强知识库"""
try:
# 创建知识上下文
knowledge_context = KnowledgeContext(
question=knowledge_data.get("question", ""),
answer=knowledge_data.get("answer", ""),
confidence=knowledge_data.get("confidence", 0.5),
source=knowledge_data.get("source", "unknown"),
category=knowledge_data.get("category", "general")
)
# 使用智能Agent处理知识库置信度
actions = await self.intelligent_agent.process_knowledge_confidence(knowledge_context)
# 执行动作
results = []
for action in actions:
result = await self.action_executor.execute_action(action)
results.append({
"action": action.description,
"priority": action.priority,
"confidence": action.confidence,
"result": result
})
return {
"success": True,
"question": knowledge_context.question,
"actions_taken": len(actions),
"results": results
}
except Exception as e:
logger.error(f"Agent增强知识库失败: {e}")
return {"success": False, "error": str(e)}
def _parse_knowledge_manually(self, content: str) -> List[Dict[str, Any]]:
"""手动解析知识内容"""
try: