2026-02-26 13:43:44 +08:00
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
|
from langchain_core.messages import HumanMessage
|
|
|
|
|
from langgraph.graph import StateGraph, END
|
|
|
|
|
|
|
|
|
|
from services.llm_factory import create_chat_model
|
|
|
|
|
from .state import AgentState
|
|
|
|
|
from . import nodes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class BaseAgent:
|
|
|
|
|
"""包含通用功能的基础代理类"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, model_section: Optional[str] = None):
|
|
|
|
|
self.model = create_chat_model(model_section)
|
|
|
|
|
self.graph = self._build_graph()
|
|
|
|
|
|
|
|
|
|
def _build_graph(self) -> StateGraph:
|
|
|
|
|
"""构建代理状态图"""
|
|
|
|
|
workflow = StateGraph(AgentState)
|
|
|
|
|
|
|
|
|
|
workflow.add_node("process_input", nodes.process_input)
|
|
|
|
|
workflow.add_node("normalize_input", self._normalize_input)
|
2026-02-26 18:06:17 +08:00
|
|
|
workflow.add_node("generate_sql", self._generate_sql)
|
2026-02-26 13:43:44 +08:00
|
|
|
workflow.add_node("generate_response", self._generate_response)
|
|
|
|
|
|
|
|
|
|
workflow.add_edge("process_input", "normalize_input")
|
2026-02-26 18:06:17 +08:00
|
|
|
workflow.add_edge("normalize_input", "generate_sql")
|
|
|
|
|
workflow.add_edge("generate_sql", "generate_response")
|
2026-02-26 13:43:44 +08:00
|
|
|
workflow.add_edge("generate_response", END)
|
|
|
|
|
|
|
|
|
|
workflow.set_entry_point("process_input")
|
|
|
|
|
|
|
|
|
|
return workflow.compile()
|
|
|
|
|
|
|
|
|
|
def _generate_response(self, state: AgentState) -> AgentState:
|
|
|
|
|
"""使用 LLM 生成回复"""
|
|
|
|
|
return nodes.generate_response(state, self.model)
|
|
|
|
|
|
|
|
|
|
def _normalize_input(self, state: AgentState) -> AgentState:
|
|
|
|
|
"""规范化用户输入"""
|
|
|
|
|
return nodes.normalize_input(state, self.model)
|
|
|
|
|
|
2026-02-26 18:06:17 +08:00
|
|
|
def _generate_sql(self, state: AgentState) -> AgentState:
|
|
|
|
|
"""生成 SQL"""
|
|
|
|
|
return nodes.generate_sql(state, self.model)
|
|
|
|
|
|
2026-02-26 13:43:44 +08:00
|
|
|
def run(self, user_input: str, **kwargs) -> Dict[str, Any]:
|
|
|
|
|
"""运行代理并处理用户输入"""
|
|
|
|
|
initial_state = AgentState(
|
|
|
|
|
messages=[HumanMessage(content=user_input)],
|
|
|
|
|
context=kwargs
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
result = self.graph.invoke(initial_state)
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"messages": result.get("messages", []),
|
|
|
|
|
"context": result.get("context", {}),
|
|
|
|
|
"final_step": result.get("current_step", "unknown")
|
|
|
|
|
}
|