2026-02-26 13:43:44 +08:00
|
|
|
from typing import Dict, Any, List, Optional
|
2026-02-17 02:31:39 +08:00
|
|
|
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
|
|
|
|
|
from langgraph.graph import StateGraph, END
|
|
|
|
|
from .base_agent import BaseAgent, AgentState
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ConversationAgent(BaseAgent):
|
2026-02-26 13:43:44 +08:00
|
|
|
"""处理多轮对话的代理"""
|
2026-02-17 02:31:39 +08:00
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
def __init__(self, model_section: Optional[str] = None):
|
|
|
|
|
super().__init__(model_section)
|
2026-02-17 02:31:39 +08:00
|
|
|
self.conversation_history: List[BaseMessage] = []
|
|
|
|
|
|
|
|
|
|
def _build_graph(self) -> StateGraph:
|
2026-02-26 13:43:44 +08:00
|
|
|
"""构建对话专用图"""
|
2026-02-17 02:31:39 +08:00
|
|
|
workflow = StateGraph(AgentState)
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
# 添加节点
|
2026-02-17 02:31:39 +08:00
|
|
|
workflow.add_node("analyze_intent", self._analyze_intent)
|
|
|
|
|
workflow.add_node("generate_response", self._generate_response)
|
|
|
|
|
workflow.add_node("update_context", self._update_context)
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
# 定义边
|
2026-02-17 02:31:39 +08:00
|
|
|
workflow.add_edge("analyze_intent", "generate_response")
|
|
|
|
|
workflow.add_edge("generate_response", "update_context")
|
|
|
|
|
workflow.add_edge("update_context", END)
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
# 设置入口节点
|
2026-02-17 02:31:39 +08:00
|
|
|
workflow.set_entry_point("analyze_intent")
|
|
|
|
|
|
|
|
|
|
return workflow.compile()
|
|
|
|
|
|
|
|
|
|
def _analyze_intent(self, state: AgentState) -> AgentState:
|
2026-02-26 13:43:44 +08:00
|
|
|
"""分析用户意图与对话上下文"""
|
|
|
|
|
# 简单意图分析,可用更复杂逻辑增强
|
2026-02-17 02:31:39 +08:00
|
|
|
user_message = state.messages[-1] if state.messages else None
|
|
|
|
|
|
|
|
|
|
if user_message and isinstance(user_message, HumanMessage):
|
|
|
|
|
content = user_message.content.lower()
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
# 基础意图识别
|
2026-02-17 02:31:39 +08:00
|
|
|
if any(word in content for word in ["hello", "hi", "hey", "greetings"]):
|
|
|
|
|
state.context["intent"] = "greeting"
|
|
|
|
|
elif any(word in content for word in ["help", "assist", "support"]):
|
|
|
|
|
state.context["intent"] = "help"
|
|
|
|
|
elif "?" in content:
|
|
|
|
|
state.context["intent"] = "question"
|
|
|
|
|
else:
|
2026-02-26 13:43:44 +08:00
|
|
|
"""兼容导出:请优先使用 agent 包"""
|
|
|
|
|
|
|
|
|
|
from agent.conversation import ConversationAgent
|
|
|
|
|
|
|
|
|
|
__all__ = ["ConversationAgent"]
|