本文档总结了将原有基于 create_react_agent
的 Demo 重构为使用 StateGraph
的、具备强大上下文处理能力和流程控制能力的新版 Agent 的概要设计。
generate_sql -> valid_sql -> run_sql
这一固定流程进行强力引导,防止 LLM“忘记”执行下一步或执行错误,提高 Agent 的可靠性和可预测性。StateGraph
架构新架构的核心是一个包含 5 个节点的 StateGraph
,它取代了原有的 create_react_agent
黑盒。
graph TD
A[START] --> B(agent_node);
B --> C{有工具调用?};
C -- 是 --> D(prepare_tool_input_node);
C -- 否 --> G(format_final_response_node);
D --> E(tool_node);
E --> F(update_state_after_tool_node);
F --> B;
G --> H[END];
agent_node
(决策者)
state
,包含 messages
历史和 suggested_next_step
。state.suggested_next_step
作为强烈的行动建议 (例如: valid_sql
, run_sql
, analyze_error
)。tool_calls
,或决定直接回答的 AIMessage
。prepare_tool_input_node
(信息组装者) - (新增节点)
agent_node
之后, tool_node
之前。agent_node
输出的 tool_calls
。generate_sql
),则从 state.messages
中提取完整的对话历史。history_messages
参数,注入到 tool_calls
的 args
中。tool_calls
。tool_node
(执行者)
tool_calls
,并忠实地调用 sql_tools.py
中的工具函数。update_state_after_tool_node
(流程建议与错误处理器) - (新增节点)
tool_node
之后。state.suggested_next_step
字段,以精确引导下一步:
generate_sql
成功: suggested_next_step
-> "valid_sql"
generate_sql
失败: suggested_next_step
-> "answer_with_common_sense"
(引导LLM基于常识回答或向用户解释)valid_sql
成功: suggested_next_step
-> "run_sql"
valid_sql
失败: suggested_next_step
-> "analyze_validation_error"
(引导LLM分析错误原因)run_sql
执行后: suggested_next_step
-> "summarize_final_answer"
(引导LLM基于数据总结)state
。format_final_response_node
(最终输出格式化器) - (新增节点)
agent_node
决定直接回答后,图结束前。"[Node] format_final_response - 准备格式化最终输出..."
。state
中提取 LLM 的最终文字总结和最近一次 run_sql
的数据(如果存在)。state
中最后一条 AIMessage
的内容。AgentState
状态设计state.py
文件将定义 StateGraph
中流转的数据结构。
from typing import TypedDict, Annotated, Optional, List
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: Annotated[List[BaseMessage], add_messages]
user_id: str
thread_id: str
# 新增字段,用于引导 LLM 的下一步行动
suggested_next_step: Optional[str]
messages
: 核心字段,存储完整的、包含 HumanMessage
, AIMessage
, ToolMessage
的对话历史。suggested_next_step
: 流程控制的关键。它由 update_state_after_tool_node
写入,由 agent_node
读取,为 LLM 提供强力的流程引导。sql_tools.py
:
generate_sql(question: str, history_messages: List[BaseMessage]) -> str
:history_messages
。question
和 history_messages
组合成更丰富的提示,再交给 Vanna 的 LLM 进行处理,从而解决上下文理解问题。valid_sql
和 run_sql
保持简单的输入输出。logging
模块,由 config.py
控制级别。在每个节点的入口和出口、关键的逻辑判断处打印详细日志,以便清晰地追踪 Agent 的思考和执行链路。AsyncRedisSaver
机制。CustomReactAgent
在初始化时创建 checkpointer
,并在编译 StateGraph
时传入,以实现自动的状态持久化。prepare_tool_input_node
确保 generate_sql
能获取完整的对话历史。update_state_after_tool_node
和 suggested_next_step
确保 Agent 遵循预设的执行流程。