LLM Lab

Routing & loops

Real work branches and repeats. Conditional edges let the state decide which node runs next, including going back to an earlier one.

Where this sits in a LangGraph application
State→Nodes→Edges & routing→Parallel (Send)→Checkpoints & interrupts→Several agents

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.

revise (score < 8)doneSTARTwritereviewscoreEND
A conditional edge (dashed) after review: route back to write while the score is too low, or on to END. The loop is part of the graph, so it is visible and limited.
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")
A writer and a reviewer in a loop. The routing function ends the loop when the score is high enough or after three rounds.

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

Check yourself · 1 of 3

What does add_conditional_edges("review", route) do?

Check yourself · 2 of 3

A writer-reviewer loop never satisfies the reviewer. What stops it?

Check yourself · 3 of 3

When is returning Command(goto=..., update=...) from a node useful?

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.
All books
Labrevise until good
How to read this
  • The graph is write → review → (back to write, or END). The stage map lights the node that just ran; each step adds a line to the log.
  • Set the score the reviewer needs and the maximum number of rounds. Run steps until the route function sends the run to END.