4.1 条件分支详解
条件分支允许图根据运行时状态动态决定执行路径。
4.1.1 基础条件路由
pythonfrom typing import Literal
def classify_intent(state: AgentState) -> Literal["greeting", "question", "complaint", "other"]:
last_msg = state["messages"][-1].content.lower()
if any(g in last_msg for g in ["hi", "hello", "你好"]):
return "greeting"
elif "?" in last_msg or any(q in last_msg for q in ["怎么", "什么", "如何"]):
return "question"
elif any(c in last_msg for c in ["投诉", "不满", "太差"]):
return "complaint"
else:
return "other"
graph.add_conditional_edges(
"classify",
classify_intent,
{
"greeting": "handle_greeting",
"question": "answer_question",
"complaint": "handle_complaint",
"other": "general_response"
}
)
4.1.2 多条件组合
pythondef complex_router(state: AgentState) -> str:
msg = state["messages"][-1].content
urgency = state.get("urgency_level", 0)
is_vip = state.get("is_vip", False)
# VIP + 高紧急度 → 人工客服
if is_vip and urgency > 8:
return "human_agent"
# 高紧急度 → 快速通道
elif urgency > 7:
return "fast_track"
# VIP → VIP 通道
elif is_vip:
return "vip_queue"
# 普通 → 标准流程
else:
return "standard_flow"
4.2 循环与迭代
LangGraph 原生支持循环,这使得实现 ReAct 等推理模式变得简单。
4.2.1 ReAct 模式实现
pythonfrom langgraph.graph import StateGraph, START
graph = StateGraph(ReActState)
# 添加节点
graph.add_node("reasoner", reason_node) # 推理
graph.add_node("act", act_node) # 执行工具
graph.add_node("observe", observe_node) # 观察结果
# 设置循环
graph.add_edge(START, "reasoner")
graph.add_edge("reasoner", "act")
graph.add_edge("act", "observe")
# 关键:循环回到 reasoner
graph.add_edge("observe", "reasoner")
# 终止条件
def should_continue(state: ReActState) -> Literal["reasoner", "END"]:
if state["should_stop"]:
return "END"
return "reasoner"
graph.add_conditional_edges("observe", should_continue, {
"reasoner": "reasoner",
"END": END
})
图 4-1:复杂条件路由决策树
4.2 ReAct 循环模式
LangGraph 原生支持循环,这使得实现 ReAct(Reason + Act + Observe)等推理模式变得简单。
4.2.1 ReAct 模式实现
图 4-2:ReAct 循环流程
4.2.2 循环次数限制
python# 防止无限循环:添加步骤计数
class SafeState(TypedDict):
messages: Annotated[list, add]
step: int
def check_step_limit(state: SafeState) -> Literal["continue", "END"]:
if state["step"] >= 10: # 最多循环 10 次
return "END"
return "continue"
# 在节点中递增 step
def increment_step(state: SafeState) -> dict:
return {"step": state["step"] + 1}
4.3 本章小结
- 条件分支:
add_conditional_edges根据函数返回值路由 - 路由函数返回目标节点名称(字符串)
- 循环:节点之间互相指向即可形成循环
- 终止条件:使用条件边控制何时退出循环
- 安全考虑:添加循环次数限制防止无限循环
下章预告
第 5 章我们将学习 Checkpointer 检查点:如何保存和恢复状态,实现多轮对话和断点续传。

