By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The support graph must classify every incoming message into one of three paths: a read-only lookup, a refund proposal that needs approval, or an escalation to a human. A model can produce a new intent at any time — a typo, a language change, a request nobody anticipated — and a router that forwards an unrecognised label either crashes on an unmapped edge or, worse, falls through to a write. In this lab you implement the router as a pure function, test all three labels plus the unknown-label fallback, and add the missing guardrail: an explicit recursion limit around the one place the graph loops.
A router is a decision table, not a place for judgement. It reads state, normalises the signal it was given, and returns exactly one label from a closed set. It performs no I/O, imports no node and never guesses: an intent it does not recognise maps to escalate, the safe branch. That purity is what makes it cheap to unit-test and what keeps the write path unreachable from an uncertain classification.
Start with the function and its table, before any graph exists. A mapping from normalised intent to label keeps the policy visible and gives the fallback a named place. The return annotation is the same Literal the path map will handle, so a missing label is a type error in review as well as a runtime error at compile time.
from typing import Literal, TypedDict
Route = Literal["lookup", "refund", "escalate"]
INTENT_TO_LABEL = {
"order_status": "lookup",
"refund": "refund",
}
class TicketState(TypedDict):
message: str
intent: str | None
def route(state: TicketState) -> Route:
"""Pure: state in, one of three labels out. Never invents a label."""
intent = (state.get("intent") or "").strip().lower()
return INTENT_TO_LABEL.get(intent, "escalate")
print(route({"message": "", "intent": "refund"}))
print(route({"message": "", "intent": "order_status"}))
print(route({"message": "", "intent": "chargeback"}))
print(route({"message": "", "intent": None}))Four inputs, four deterministic labels. Notice what the function does not do: it never raises for a phrase it has not seen, it never returns the raw intent string, and it cannot return a label outside the three the graph knows how to wire. The unknown cases collapse to the same safe destination, which is exactly what the fallback is for.
The conditional edge is the router plus a path map. Keep both in one place so review can compare them: the map's keys should equal the router's possible labels, and the map values should be real nodes. The classification node here is a deterministic stand-in for the model so the lab runs without a provider.
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
class TicketState(TypedDict):
message: str
intent: str | None
reply: str | None
def classify(state: TicketState) -> dict:
# Stand-in for a model classifier: deterministic so the lab is keyless.
text = state["message"].lower()
if "refund" in text:
return {"intent": "refund"}
if "where" in text or "status" in text:
return {"intent": "order_status"}
return {"intent": "unknown"}
def route(state: TicketState) -> Literal["lookup", "refund", "escalate"]:
return {
"refund": "refund",
"order_status": "lookup",
"unknown": "escalate",
}.get(state["intent"] or "", "escalate")
def lookup(state: TicketState) -> dict:
return {"reply": "Order A17 is in transit."}
def refund(state: TicketState) -> dict:
return {"reply": "Refund queued for approval."}
def escalate(state: TicketState) -> dict:
return {"reply": "Escalated to a human."}
builder = StateGraph(TicketState)
builder.add_node("classify", classify)
builder.add_node("lookup", lookup)
builder.add_node("refund", refund)
builder.add_node("escalate", escalate)
builder.add_edge(START, "classify")
builder.add_conditional_edges(
"classify",
route,
{"lookup": "lookup", "refund": "refund", "escalate": "escalate"},
)
builder.add_edge("lookup", END)
builder.add_edge("refund", END)
builder.add_edge("escalate", END)
graph = builder.compile()
for message in (
"Where is order A17?",
"I want a refund for A17",
"My lawyer will call you",
):
result = graph.invoke({"message": message, "intent": None, "reply": None})
print(result["intent"], "->", result["reply"])Routing also decides when a loop ends. A retry or evaluation cycle must carry a progress signal in state — attempts, quality, a budget — and route out when the signal says so. recursion_limit (25 supersteps by default) is the crash backstop that turns a runaway loop into GraphRecursionError; it is not a termination strategy. Set the limit explicitly in tests so a regression cannot spin silently, and write one test that proves the runaway case raises.
from typing import Literal, TypedDict
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
class AttemptState(TypedDict):
attempts: int
def attempt(state: AttemptState) -> dict:
return {"attempts": state["attempts"] + 1}
def route(state: AttemptState) -> Literal["attempt", "done"]:
# The loop owns its stop condition; recursion_limit is only the backstop.
return "done" if state["attempts"] >= 2 else "attempt"
builder = StateGraph(AttemptState)
builder.add_node("attempt", attempt)
builder.add_edge(START, "attempt")
builder.add_conditional_edges(
"attempt", route, {"attempt": "attempt", "done": END}
)
graph = builder.compile()
print(graph.invoke({"attempts": 0}))
class LoopState(TypedDict):
steps: int
def step(state: LoopState) -> dict:
return {"steps": state["steps"] + 1}
def always_loop(state: LoopState) -> Literal["step"]:
return "step"
loop_builder = StateGraph(LoopState)
loop_builder.add_node("step", step)
loop_builder.add_edge(START, "step")
loop_builder.add_conditional_edges("step", always_loop, {"step": "step"})
runaway = loop_builder.compile()
try:
runaway.invoke({"steps": 0}, {"recursion_limit": 5})
except GraphRecursionError:
print("GraphRecursionError")recursion_limit low enough to prove the runaway case raises instead of hanging.Key takeaways
A router is a pure function plus a path map: it returns one closed label from state and the map resolves that label to a node.
Normalise the signal and map every unknown case to a safe fallback; an unmapped label raises rather than silently falling through.
Wire routing so the write path is reachable only through the approval branch, never from an uncertain classification.
A loop needs a progress condition it owns; recursion_limit is the crash backstop, so set it in tests and assert the runaway raises GraphRecursionError.
Router tests are cheap because the function is pure: table tests for every label and a set-equality test between labels and map keys catch the common regressions.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.