第 3 章 · 条件路由与有界循环
用确定性质量检查决定“修改一次”还是结束,避免把所有控制流都交给模型。本章的有限循环也是后续 Agent 工具循环的基础。
工作机制与设计选择
add_conditional_edges 接收路由函数,返回值映射到目标节点。每轮把 attempts 加一,业务停止条件由状态决定;recursion_limit 是最后一道运行保护,不是业务目标。路由分支必须覆盖可能结果,不要同一节点同时配置无条件退出和条件循环,导致多条路径意外同时运行。
示例
python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
attempts: int
score: int
def revise(state: State):
return {"attempts": state["attempts"] + 1, "score": state["score"] + 40}
def route(state: State):
return "done" if state["score"] >= 80 or state["attempts"] >= 3 else "again"
builder = StateGraph(State)
builder.add_node("revise", revise)
builder.add_edge(START, "revise")
builder.add_conditional_edges("revise", route, {"done": END, "again": "revise"})
graph = builder.compile()
result = graph.invoke({"attempts": 0, "score": 0}, {"recursion_limit": 10})
assert result == {"attempts": 2, "score": 80}
print(result)运行与验收
本例无需模型。运行后应恰好修改两轮。再把初始 score 改为 -100,验证 attempts 达到 3 后仍会退出。
容易踩的坑
不能仅提高 recursion_limit 来修复无限循环。应记录每轮决策,区分模型无进展、工具持续失败和停止条件缺失。
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. 谁定义业务停止条件?
2. recursion_limit 是什么?
3. 路由标签需要什么?
4. 无限循环最好如何修复?
动手实践
- 为退出增加 reason 字段,区分达标与次数耗尽。
- 对 score=80、score=0、score=-100 编写参数化测试。
- 把质量检查替换为固定返回不合格,验证循环仍有界。
官方参考
核验日期:2026-09-17。