Module 2 · Flow control

Conditional edges and routers

6 min read

A useful graph makes decisions: handle a question differently from a refund request, hand over to a human when the agent is stuck, skip an unnecessary step. In LangGraph, these decisions are made in two places: in conditional edges, or directly in a node returning a Command. Knowing which to choose, and how to have the model decide reliably, is the subject of this lesson.

The conditional edge

A conditional edge attaches a routing function to a node: after the node runs, the engine calls this function with the state, and it returns the name of the next node.

def route_intent(state: SupportState) -> Literal["agent", "refund", "handoff"]:
    match state["intent"]:
        case "question" | "order_status":
            return "agent"
        case "refund":
            return "refund"
        case _:
            return "handoff"


builder.add_conditional_edges("triage", route_intent)

The Literal[...] return annotation declares the possible destinations: LangGraph uses it to draw the graph and check names. You can also provide them explicitly, as a list, or as a dictionary mapping a returned value to a node:

builder.add_conditional_edges(
    "triage", classify_fn, {"simple": "agent", "money": "refund", "unknown": "handoff"}
)

A router can also return a list of nodes: they will all run, in parallel, in the next step.

The golden rule: a router only reads

A routing function must be pure: it reads the state and returns a destination, nothing else. No model call, no database write, no state update (it couldn't anyway: its return value is a destination, not an update).

Why? Because the decision must be reproducible and inspectable. If routing depends on an LLM call made inside the router, nothing records it: the state doesn't say why the graph went left rather than right. Good practice is therefore two-step:

  1. a node makes the decision (possibly with an LLM) and writes it to the state (intent);
  2. a pure router reads that value and dispatches.

The decision is then visible in the state, in checkpoints, in traces, and can be tested or corrected (lesson 4.3).

Having the model decide: structured output

Relay's triage node delegates classification to the model. For an LLM decision to be usable by code, it must be constrained: no free text, but an output conforming to a schema.

class Triage(BaseModel):
    intent: Literal["question", "order_status", "refund", "other"] = Field(
        description="question : question générale ; order_status : suivi d'une commande ; "
        "refund : demande de remboursement ou de retour ; other : tout le reste"
    )
    order_id: str | None = Field(
        description="Numéro de commande au format ORD-XXXX s'il est cité, sinon null"
    )
    language: Literal["fr", "en"] = Field(description="Langue du message du client")


async def triage(state: SupportState) -> dict:
    model = chat_model(fast=True).with_structured_output(Triage, method="json_schema")
    result = await model.ainvoke([SystemMessage(TRIAGE_PROMPT), state["messages"][-1]])
    return {
        "intent": result.intent,
        "order_id": result.order_id or state.get("order_id"),
        "language": result.language,
        "audit": [f"triage → {result.intent}"],
    }

Several choices deserve attention:

  • method="json_schema" uses the Claude API's native structured outputs: generation is constrained by the schema, and the answer is always valid. The other method (function_calling) goes through a forced tool call, which the most recent models no longer accept.
  • A fast model (fast=True, Claude Haiku) is enough to classify: it's a simple task, called on every message. The large model is reserved for the conversation.
  • Literal closes the choices: the model cannot invent an "urgent" category that the router wouldn't know how to handle.
  • str | None for the order number: without this option, a model forced to fill the field might invent one.
  • Only the last message is classified, with a dedicated prompt: triage doesn't see the whole history, which makes it fast and cheap.

Command: decide and update in one go

Sometimes the decision and the state update are inseparable. In the refund subgraph, after a supervisor's approval, you must both record their decision and choose the next step (finance, execution or refusal). A node can then return a Command:

from langgraph.types import Command


def supervisor_review(state: RefundState) -> Command[Literal["finance_review", "execute", "explain"]]:
    ...
    if answer["decision"] == "reject":
        audit = [f"supervisor: refusé par {reviewer}"]
        return Command(goto="explain", update={"refund": updated, "audit": audit})
    return Command(goto="finance_review", update={"refund": updated, "audit": [...]})

Command(goto=..., update=...) applies the update and names the next node. The Command[Literal[...]] annotation plays the same role as for a router: it declares the possible destinations, for visualization and validation. A node that routes this way needs no outgoing edge in the builder.

Conditional edgeCommand
Who decidesA separate routing functionThe node itself
Update + routingTwo steps (node, then router)In a single step
Graph readabilityRouting visible in the assemblyRouting inside the node body
Typical caseDispatch on a state valueThe node's logic determines what's next (approval, handoff between agents)

Command is also used to go up to the parent graph from a subgraph (Command(graph=Command.PARENT, goto=...)) — the mechanism behind handoffs between agents in network architectures — and to resume an interrupted run (Command(resume=...), module 4).

Designing routes

A few principles from practice:

  1. Always a default exit. route_intent's case _ sends any unforeseen case to a human. A router without a default case will eventually receive an unexpected value.
  2. Prefer business categories to technical ones. refund speaks to the support team; tool_path_2 speaks to nobody.
  3. Keep hard rules in code. "Above €500, finance approval" is a business rule: it is written in Python, not in a prompt. The model classifies and interprets; the code decides what is allowed.
  4. Test every branch. A router is a pure function: it can be tested in one line, without an LLM.
def test_route_intent():
    assert route_intent({"intent": "refund"}) == "refund"
    assert route_intent({"intent": "other"}) == "handoff"

Key takeaways

  • A conditional edge calls a routing function that returns the next node(s).
  • A router is pure: the decision is made in a node, written to the state, and the router only reads.
  • To have the model decide: structured output (with_structured_output(..., method="json_schema")), Literal to close the choices.
  • Command(goto=..., update=...) updates the state and picks the next step at once.
  • Always a default route, and business rules in code, not in the prompt.

Practice

  1. Read the tests of route_intent and route_after_agent in tests/test_units.py, then run them: how long do they take?
  2. Add a complaint intent (a complaint with no refund request) with its own response node.
  3. Rewrite route_after_agent as a Command returned by the agent node. Which version do you find more readable?

Resources