Routing & loops
Real work branches and repeats. Conditional edges let the state decide which node runs next, including going back to an earlier one.
Conditional edges
A normal edge always goes to the same node. A conditional edge calls a small routing function on the state and goes wherever it says. Pointing that edge back to an earlier node makes a loop: write, review, revise, review again, until a condition holds. This is the evaluator-optimiser pattern, and also how an agent loop is built.
def route(state: State) -> str:
if state["score"] >= 8 or state["rounds"] >= 3:
return "done"
return "revise"
builder.add_node("write", write)
builder.add_node("review", review)
builder.add_edge(START, "write")
builder.add_edge("write", "review")
builder.add_conditional_edges("review", route, {"revise": "write", "done": END})
# the same decision made inside a node instead:
# return Command(update={"score": 6}, goto="write")Keeping loops safe
Every run has a recursion limit on how many steps it may take; going past it raises GraphRecursionError instead of looping forever. Do not rely on it alone: keep a counter in the state, as above, so the graph ends cleanly with the best draft so far. A node can also route itself by returning Command(update=..., goto=...), which updates the state and chooses the next node in one go.
A worked example
With a required score of 8 and at most 3 rounds, the first draft scores 5, so the run goes back to write. The second scores 7, back again. The third scores 9: the route returns “done” and the run ends after six steps. Raise the bar to 10 and the counter stops it after round three instead.
Easy to confuse
- The routing function should only read the state and return a name; doing work in it hides steps from the graph’s history.
- A loop in a graph is visible and limited; a loop hidden inside one node is neither.
What does add_conditional_edges("review", route) do?
A conditional edge picks the next node at run time from the state, which is how graphs branch and loop.
A writer-reviewer loop never satisfies the reviewer. What stops it?
LangGraph raises GraphRecursionError when a run exceeds its step limit. Good graphs also keep their own counter and route to END after a few rounds.
When is returning Command(goto=..., update=...) from a node useful?
Command combines a state update with a routing decision in one return value, instead of a separate conditional edge.
Read more in the books
- LangChain and LangGraph documentation, LangChain: LangGraph: Graph API (conditional edges, Command, recursion limit).
- Learning LangChain, Mayo Oshin, Nuno Campos: the chapters on LangGraph and agent architectures.