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

  1. classify checks for digits and stores a category
  2. add_conditional_edges(“classify”, route) says: after classify, ask route where to go
  3. route returns a node name, and the graph jumps there
  4. Only the chosen helper runs. The other is skipped.
  5. 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

  1. Add a third category, greeting, for questions containing “hello” or “hi”, with its own helper node
  2. Make the router return END when the question is empty
  3. 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:

LangGraph State: TypedDict, Pydantic, and Reducers
LangGraph Loops and Cycles: Retry Logic and Iterative Workflows
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment