Lesson 3 of 11 · Graphs
Conditional Edges
Make LangGraph choose what runs next: conditional edges, typed destinations, loops with attempt limits, the recursion limit and Command to update and route.
- 7 min read
- Advanced
- Reviewed
- Route to different nodes with add_conditional_edges and a routing function
- Build loops that end, with an attempt counter in the state
- Explain the recursion limit and GraphRecursionError
- Update state and choose the next node at once with Command
- Route safely on labels a model produces
Choosing the next step
A fixed edge always goes to the same node. A conditional edge runs a function on the state and goes wherever it says.
Routing support messages
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
message: str
category: str
reply: str
def classify(state: State) -> dict: # a model would usually do this (with structured output)
text = state["message"].lower()
if any(w in text for w in ("refund", "charged", "invoice")):
return {"category": "billing"}
if any(w in text for w in ("brake", "battery", "puncture")):
return {"category": "repair"}
return {"category": "other"}
def billing(state: State) -> dict:
return {"reply": "Billing: we'll check your payment and reply within a day."}
def repair(state: State) -> dict:
return {"reply": "Workshop: you can book a repair slot online."}
def human(state: State) -> dict:
return {"reply": "A colleague will get back to you shortly."}
def route(state: State) -> Literal["billing", "repair", "human"]: # returns the next node's name
return {"billing": "billing", "repair": "repair"}.get(state["category"], "human")
builder = StateGraph(State)
for name, fn in [("classify", classify), ("billing", billing), ("repair", repair), ("human", human)]:
builder.add_node(name, fn)
builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", route)
for name in ("billing", "repair", "human"):
builder.add_edge(name, END)
graph = builder.compile()
for msg in ["I was charged twice", "My brakes squeak", "Do you sell gift cards?"]:
print(f"{msg!r:<28} -> {graph.invoke({'message': msg})['reply']}")'I was charged twice' -> Billing: we'll check your payment and reply within a day. 'My brakes squeak' -> Workshop: you can book a repair slot online. 'Do you sell gift cards?' -> A colleague will get back to you shortly.
add_conditional_edges("classify", route) says: after classify, call route(state) and go to the node it names. The return type Literal["billing", "repair", "human"] tells LangGraph the possible destinations, which it uses to check the graph and draw it. (Alternatively, pass a path_map dictionary that maps the function's return values to node names.)
In a real application, classify would ask a model, using structured output so the category is one of a fixed set (see the LangChain course).
Loops that end
Point a conditional edge back to an earlier node and you have a loop. Every loop needs an exit:
from typing import TypedDict
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
attempts: int
paid: bool
def try_payment(state: State) -> dict:
attempts = state["attempts"] + 1
return {"attempts": attempts, "paid": attempts >= 3} # pretend the 3rd attempt succeeds
def after_payment(state: State) -> str:
if state["paid"]:
return END
return "try_payment" if state["attempts"] < 5 else END # our own limit: give up after 5
builder = StateGraph(State)
builder.add_node("try_payment", try_payment)
builder.add_edge(START, "try_payment")
builder.add_conditional_edges("try_payment", after_payment)
graph = builder.compile()
print(graph.invoke({"attempts": 0, "paid": False}))
# A loop with no exit of its own is stopped by the recursion limit
forever = StateGraph(State)
forever.add_node("try_payment", lambda s: {"attempts": s["attempts"] + 1})
forever.add_edge(START, "try_payment")
forever.add_edge("try_payment", "try_payment")
try:
forever.compile().invoke({"attempts": 0, "paid": False}, config={"recursion_limit": 10})
except GraphRecursionError:
print("GraphRecursionError: stopped after 10 steps"){'attempts': 3, 'paid': True}
GraphRecursionError: stopped after 10 stepsThe first graph counts attempts in its state and gives up after 5, so it ends cleanly whether or not the payment succeeds. The second graph loops forever, and LangGraph's recursion limit stops it with GraphRecursionError. The default limit is very high (over 10,000 steps in LangGraph 1.2), so a runaway agent could make thousands of model calls before it stops. Set recursion_limit in the config to suit your graph.
Command: update and route together
Sometimes the node that does the work also knows where to go next. Returning a Command sets both at once:
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
class State(TypedDict):
amount: float
status: str
def check_refund(state: State) -> Command[Literal["auto_refund", "manager_review"]]:
# Update the state AND choose the next node in one return value
if state["amount"] <= 100:
return Command(update={"status": "approved automatically"}, goto="auto_refund")
return Command(update={"status": "waiting for a manager"}, goto="manager_review")
builder = StateGraph(State)
builder.add_node("check_refund", check_refund)
builder.add_node("auto_refund", lambda s: {})
builder.add_node("manager_review", lambda s: {})
builder.add_edge(START, "check_refund")
builder.add_edge("auto_refund", END)
builder.add_edge("manager_review", END)
graph = builder.compile()
for amount in (40, 350):
print(amount, "->", graph.invoke({"amount": amount, "status": ""})["status"])40 -> approved automatically 350 -> waiting for a manager
The Command[Literal[...]] return type lists the possible destinations, just like a routing function's. Use conditional edges when routing is a separate decision, and Command when the routing falls naturally out of the node's own work. Command is also how agents hand off to each other (lesson 10).
Routing on model output, safely
When a model chooses the route, its answer might be uncertain, or a label you never defined. Route defensively:
# Routing safely: a model's label is mapped to an allowed node, with a default for anything else,
# and a counter in the state ends loops that don't converge.
ALLOWED = {"billing": "billing_team", "repair": "workshop", "delivery": "logistics"}
def route(state):
if state["attempts"] >= 3:
return "human" # stop looping: a person takes over
if state["confidence"] < 0.6:
return "ask_clarifying_question" # unsure: ask instead of guessing
return ALLOWED.get(state["label"], "human") # unknown labels never crash the graph
cases = [
{"label": "billing", "confidence": 0.93, "attempts": 0},
{"label": "repair", "confidence": 0.41, "attempts": 1},
{"label": "warranty?", "confidence": 0.88, "attempts": 0}, # a label the model invented
{"label": "delivery", "confidence": 0.95, "attempts": 3},
]
for c in cases:
print(f"{c} -> {route(c)}")Unknown labels go to a person instead of crashing the graph, low confidence leads to a clarifying question instead of a guess, and too many attempts end the loop.
Common mistakes
Write the routing function for a conditional edge in a revise loop: finish when the work is good enough, give up after a limit, otherwise go round again.
def route(state):
# Return the next node's name:
# - "publish" if the review score is 8 or more
# - "give_up" if the score is below 8 and there have already been 3 revisions
# - "revise" otherwise
pass
for s in [{"score": 9, "revisions": 1}, {"score": 6, "revisions": 1}, {"score": 7, "revisions": 3}]:
print(route(s))
What is the best way to stop a revise loop in LangGraph?
Summary
add_conditional_edges(node, route)calls a routing function to choose the next node.- Type routing functions with
Literal(or pass a path_map) so the destinations are known. - Loops need an exit based on the state, such as an attempt counter; the recursion limit is only a safety net.
Command(update=..., goto=...)updates the state and routes in one step.- Route on model output defensively: fixed labels, defaults, confidence checks and limits.
Next: your first complete graph.
Finished reading? Tick it off to track your progress.