Route with Conditional Edges
A graph whose edges are all fixed always takes the same path. Real programs need to choose: answer this message, pass on that one, stop here. In LangGraph a choice like that is made in three parts. A model gives its decision as data that code can read. A small routing function reads that decision from the state. A conditional edge sends the run to the node the function names. Once the graph is built, it can draw itself, so you can check that every path you meant to wire is really there.
A decision the code can read
Say a graph should treat incoming messages in three ways: answer a question, apologize for a complaint, and drop spam. A model can tell these apart, but if it answers in prose, the reply might be "This looks like a complaint to me" one time and "Complaint." the next. Code that branches on that text has to guess, and a guess that is wrong one time in fifty is a bug nobody can reproduce.
The fix is to ask for an answer that fits a schema with a fixed set of choices. In Python you write the schema as a Pydantic class, and you give it a field whose type is a Literal: the type lists the allowed values and nothing else. Then the chat model's with_structured_output method wraps the model, so that its reply comes back as an instance of that class instead of a message. Pydantic checks the reply when it builds the instance, so the field holds exactly one of the allowed values.
from typing import Literal
from pydantic import BaseModel, Field
class Triage(BaseModel):
kind: Literal["question", "complaint", "spam"] = Field(
description="What kind of message this is"
)
triage_model = model.with_structured_output(Triage, method="function_calling")
def triage(state: State) -> dict:
result = triage_model.invoke(state["messages"])
return {"kind": result.kind}A chat model can be made to fit a schema in more than one way, and the method argument picks which. With "function_calling", the model is made to call a tool whose arguments follow the schema, and the answer is read back from those arguments. With "json_schema", the provider's own structured-output feature does the work, and only some providers offer it. The OpenAI chat class uses "json_schema" when you name no method. So code that should work on any model that can call tools passes method="function_calling" explicitly.
The triage function above is an ordinary node. It calls the model and writes the chosen value into a state key, kind. The decision is now part of the state, as plain data, where the next piece of code can read it.
True or false?
With a Pydantic schema, the result of a structured-output call is an instance of that class, not a chat message.
True. The wrapped model parses the reply and returns the object, so code reads `result.kind` directly.
Listing the allowed values in the system prompt is just as reliable as putting them in a Literal field.
False. A prompt only asks. A Literal field in the schema is checked when the reply is parsed, so a value outside the set fails there instead of slipping through as text.
Routing functions
A routing function is the small piece of code that turns the decision into a direction. It receives the current state, like a node does, but it returns something different. A node returns an update to the state. A routing function returns the name of the node that should run next, or END to stop the run there.
from typing import Literal
from langgraph.graph import END
def route(state: State) -> Literal["answer", "apologize", END]:
if state["kind"] == "question":
return "answer"
if state["kind"] == "complaint":
return "apologize"
return ENDThree details matter here.
- It only reads. A routing function never changes the state. That is why the decision is written by a node first: the node updates the state, and the routing function reads it.
ENDis a name too. It is the string"__end__", imported fromlanggraph.graph. Returning it ends this path of the run.- The
Literalreturn type is information. It lists every destination the function can return. LangGraph reads that list when it draws the graph, so the hint does real work and is not only for your editor.
Because the routing function is plain Python that only reads the state, it is easy to reason about. You can call it with a hand-made state, such as route({"kind": "spam"}), and see "__end__" come back, without a model or a graph.
True or false?
A routing function can store the decision it makes by returning it in a dictionary, as a node does.
False. Whatever a routing function returns is read as a destination, not as a state update. Write the decision into the state with a node that runs before it.
Returning `END` from a routing function stops that path of the run.
True. `END` is the end marker of the graph, the string `"__end__"`, and it is a valid destination like any node name.
Conditional edges
A normal edge always leads to the same node. A conditional edge leads out of one node, and its destination is chosen while the graph runs. After the source node finishes, LangGraph calls the routing function with the updated state and goes where it says. You add one with add_conditional_edges, passing the source node and the routing function.
- START
- triage writes kind
- answer
- apologize
- END
- START to triage
- triage to answer: question
- triage to apologize: complaint
- triage to END: spam
- answer to END
- apologize to END
In the graph above, the solid edges are fixed and the dashed ones belong to the one conditional edge out of triage. Each run takes exactly one dashed path. Here is the full wiring:
from langgraph.graph import StateGraph, START, END
def route(state: State) -> str:
return state["kind"]
builder = StateGraph(State)
builder.add_node("triage", triage)
builder.add_node("answer", answer)
builder.add_node("apologize", apologize)
builder.add_edge(START, "triage")
builder.add_conditional_edges(
"triage",
route,
{"question": "answer", "complaint": "apologize", "spam": END},
)
builder.add_edge("answer", END)
builder.add_edge("apologize", END)
graph = builder.compile()This time the routing function simply returns the value of kind, and the third argument, the path map, translates each value into a node name. The path map is optional, and it changes how you write the routing function:
| How you call it | What the routing function returns | What LangGraph knows before a run |
|---|---|---|
| no path map | node names or END | the destinations in a Literal return type, if there is one |
| a dict path map | any key of the map, such as "spam" | every destination: the values of the map |
| a list of node names | node names from the list | every destination: the list itself |
When LangGraph knows the destinations, compile() can check them as part of checking the structure of the graph, and it rejects an edge that leads to a node that does not exist. The map is also strict at run time: a value that is not one of its keys, for example a misspelt "Spam", stops the run with a KeyError instead of quietly going somewhere.
Two wiring rules prevent surprises:
- One kind of exit per node. Give a node either normal edges or a conditional edge out of it, not both. A node with both can run both paths: the fixed one and the chosen one.
- A branch at the start. The source can be
START.add_conditional_edges(START, route)picks the first node from the input itself.
True or false?
If a node has a normal edge and a conditional edge out of it, only the conditional edge decides where the run goes.
False. The documentation warns that mixing them can run both paths. Use one kind of exit per node.
With a path map, a routing function may return values such as "spam" that are not node names.
True. The returned value is looked up in the map, and the map gives the node name. Without a map the function must return node names or `END`.
A path map is only there to make the drawing nicer.
False. It also lets `compile()` check the destinations, and at run time a value missing from the map raises a `KeyError`.
Drawing the graph
Wiring is easy to get slightly wrong: an edge forgotten, a branch pointing at the wrong node, a path that never reaches END. A compiled graph can describe its own nodes and edges, so instead of rereading the builder code you can look at what LangGraph actually built.
drawable = graph.get_graph()
print(drawable.draw_mermaid())get_graph() returns a drawable description of the graph. draw_mermaid() turns it into text in Mermaid, a small language for diagrams. It needs no extra package and no network, and any Mermaid viewer renders the text as a picture.
In that text, __start__ and __end__ appear as nodes. Normal edges are solid arrows (-->) and conditional edges are dashed (-.->). A dashed edge also carries a label when its path map key is not the same as the name of the node it leads to. In the triage graph the key question leads to the node answer, so its dashed arrow is labelled question.
Other ways to draw the same description need more:
| Call | Gives | Needs |
|---|---|---|
draw_mermaid() | Mermaid text | nothing extra |
draw_mermaid_png() | PNG image bytes | by default, a call to the Mermaid.ink web service |
draw_ascii(), print_ascii() | a text drawing for the terminal | the grandalf package |
draw_png() | PNG image bytes | pygraphviz and the Graphviz program |
The drawing has a limit worth knowing. LangGraph does not read the body of your routing function, so for a conditional edge it can only draw the destinations it was told about: the values of the path map, or the names in a Literal return type. With neither, LangGraph does not know where the branch can lead, and the drawing leaves it out: the source node gets a plain solid arrow to __end__, and the nodes the function returns are listed with no arrow into them, so the picture stops being a useful check.
So the check works like this. Declare the destinations, draw the graph, and follow every dashed arrow out of each branch. Each one should lead to a node you meant, and every path should reach __end__. If an arrow is missing or extra, the wiring, the map or the hint disagrees with what you intended.
True or false?
The drawing of a graph always shows exactly the paths its routing functions can take.
False. It shows only what the path map or the `Literal` return type declares. Without either, the branch is missing from the drawing even though the function still returns node names at run time.
Printing `graph.get_graph().draw_mermaid()` works offline, with no extra package installed.
True. It only builds Mermaid text. Turning that text into a PNG with `draw_mermaid_png()` is what calls a web service by default.