07 Oct LangGraph Conditional Edges: Route Based on State
So far, every graph ran in a straight line. Real apps need to make decisions. A conditional edge lets the graph choose the next node based on the current state.
The idea
+-> math_helper ----+
START -> classify +-> END
+-> general_helper -+
After classify runs, the graph looks at the state and picks one path.
The routing function
A conditional edge uses a routing function. It reads the state and returns the name of the next node:
def route(state: State):
if state["category"] == "math":
return "math_helper"
return "general_helper"
It only decides where to go. It doesn’t update the state.
Full example
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
question: str
category: str
answer: str
def classify(state: State):
has_digit = any(ch.isdigit() for ch in state["question"])
return {"category": "math" if has_digit else "general"}
def math_helper(state: State):
return {"answer": "Math helper: let's solve it step by step."}
def general_helper(state: State):
return {"answer": "General helper: let me explain that."}
def route(state: State):
if state["category"] == "math":
return "math_helper"
return "general_helper"
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("math_helper", math_helper)
builder.add_node("general_helper", general_helper)
builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", route)
builder.add_edge("math_helper", END)
builder.add_edge("general_helper", END)
graph = builder.compile()
print(graph.invoke({"question": "What is 25 * 4?"}))
print(graph.invoke({"question": "What is Python?"}))
Output:
{'question': 'What is 25 * 4?', 'category': 'math', 'answer': "Math helper: let's solve it step by step."}
{'question': 'What is Python?', 'category': 'general', 'answer': 'General helper: let me explain that.'}
How it works
- classify checks for digits and stores a category
- add_conditional_edges(“classify”, route) says: after classify, ask route where to go
- route returns a node name, and the graph jumps there
- Only the chosen helper runs. The other is skipped.
- Both helpers connect to END, so either path finishes cleanly
Using a path map
Instead of returning node names directly, your router can return a short label, and you map labels to nodes:
def route(state: State):
return state["category"] # "math" or "general"
builder.add_conditional_edges(
"classify",
route,
{"math": "math_helper", "general": "general_helper"},
)
This keeps the router simple and puts the wiring in one visible place. It is handy when you rename nodes later.
Routing to END
A router can also end the graph early by returning END:
def route(state: State):
if state["question"].strip() == "":
return END
return "general_helper"
Helping the diagram: Literal
Add a return type hint so LangGraph knows the possible destinations:
from typing import Literal
def route(state: State) -> Literal["math_helper", "general_helper"]:
if state["category"] == "math":
return "math_helper"
return "general_helper"
Now draw_mermaid() can show both branches. Without the hint, the diagram may not show where the conditional edge leads.
Normal vs conditional edges
- Normal edge: the next node is always the same. Example: add_edge(“a”, “b”).
- Conditional edge: the next node is chosen at runtime. Example: add_conditional_edges(“a”, route).
Common mistakes
- Returning a name that doesn’t exist: “math_helpr” will fail, so check spelling
- Forgetting edges out of the destination nodes: each helper still needs a path to END
- Putting heavy logic in the router: do the analysis in a node and store the result, and let the router just read it
- Adding a normal edge from the same node too: an extra add_edge(“classify”, …) makes both paths run
Summary
- A conditional edge picks the next node at runtime
- A routing function reads the state and returns a node name (or END)
- A path map lets the router return labels instead of node names
- Use Literal type hints so diagrams show every branch
Practice
- Add a third category, greeting, for questions containing “hello” or “hi”, with its own helper node
- Make the router return END when the question is empty
- Print the Mermaid diagram with and without the Literal hint and compare
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.
For Videos, Join Our YouTube Channel:Â Join Now
Read More:
- Generative AI Tutorial
- AI Ethics
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- ChatGPT Tutorial
- Microsoft Copilot Tutorial
No Comments