DS DevShelfHub Projects · AI tools
Tutorials / LangChain / Reference / Methods / .add_conditional_edges()
Method StateGraph

.add_conditional_edges(): Reference Guide

By DevShelfHub

Add conditional routing between nodes.

What is .add_conditional_edges()?

.add_conditional_edges() is the routing primitive in LangGraph's StateGraph. After a node executes and updates state, LangGraph evaluates the condition function you pass to decide which node to run next. The condition function receives the current state dict and must return a string matching one of the keys in the edge_map dict. LangGraph then follows that edge to the mapped destination node.

The power of conditional edges is most apparent in agentic loops. A ReAct-style agent that alternately calls a reasoning node and a tool execution node needs a condition to decide whether to loop back (the agent wants to call a tool) or to exit (the agent produced a final answer). Without conditional edges, you would encode routing logic inside the nodes themselves, which breaks the separation of concerns that makes LangGraph graphs testable and recomposable.

The third argument, edge_map, maps condition return values to node names. The special value END (from langgraph.graph) signals graph completion. From LangGraph 0.2+, add_conditional_edges also supports returning a list of node names from the condition function for fan-out routing — useful for parallel tool execution. The edge_map keys must exactly match every string your condition function can return; any unmatched return value raises a ValueError at runtime.

Use Cases

  • Conditional routing
  • Decision trees
  • Agent loops
  • Branching logic
  • Dynamic workflows
  • State-based routing

Key Features

  • Condition evaluation
  • Dynamic routing
  • State-based
  • Multiple paths
  • Flexible logic
  • Loop support

When NOT to Use

For unconditional routing—use add_edge().

Notes

All condition return values must be in edge_map

If the condition function returns a string not in edge_map, LangGraph raises a ValueError at runtime. Add a catch-all else branch in your condition function that returns a known key — for example an error_handler node — to prevent unexpected crashes.

Import END from langgraph.graph

Import END from langgraph.graph, not from langgraph.constants. Using the wrong import compiles without error but may fail silently at runtime. Verify with: from langgraph.graph import StateGraph, END.

Fan-out requires LangGraph 0.2+

Returning a list from the condition function to trigger multiple next nodes in parallel requires LangGraph 0.2+ and the Send API. Returning a list in older versions raises a TypeError. Check your version with pip show langgraph before using fan-out patterns.

Debug routing during development

Add a print statement inside your condition function during development to log which edge is taken. In production, enable LangSmith tracing — it visualizes exactly which conditional edges fired across every run.

Method Signature

python
graph.add_conditional_edges(from_node, condition_fn, edge_map)

Parameters

Parameter Type Required Purpose
from_node str Yes Source node

Return Value

Type:

StateGraph

Description:

Graph with conditional edges

Example Output:

graph

Code Examples

Basic conditional routing

python
def should_loop(state):
    if state['continue']:
        return 'loop_back'
    return 'finish'

graph.add_conditional_edges(
    'agent',
    should_loop,
    {'loop_back': 'agent', 'finish': END}
)

ReAct agent loop routing to tool executor

python
from langgraph.graph import StateGraph, END
from typing import Literal

def route_agent(state) -> Literal['tools', 'end']:
    last = state['messages'][-1]
    if hasattr(last, 'tool_calls') and last.tool_calls:
        return 'tools'
    return 'end'

graph.add_conditional_edges(
    'agent',
    route_agent,
    {'tools': 'tool_executor', 'end': END},
)

Multi-path intent classification routing

python
def classify_intent(state):
    intent = state.get('intent', 'general')
    if intent == 'search':
        return 'web_search'
    elif intent == 'calculate':
        return 'calculator'
    else:
        return 'general_answer'

graph.add_conditional_edges(
    'router',
    classify_intent,
    {'web_search': 'search_node', 'calculator': 'calc_node', 'general_answer': 'answer_node'},
)

Common Mistakes

❌ Return node name that doesn't exist

✅ Map condition return values to actual nodes

Browse the full LangChain API reference index to explore more classes, methods, and decorators, or start with the LangChain introduction tutorial for end-to-end context on building with .add_conditional_edges() and the wider framework.

.add_conditional_edges() FAQ

What does .add_conditional_edges() do in LangChain?

Add conditional routing between nodes. .add_conditional_edges() is the routing primitive in LangGraph's StateGraph. After a node executes and updates state, LangGraph evaluates the condition function you pass to decide which node to run next. The condition function receives the current state dict and must return a string matching one of the keys in the edge_map dict. LangGraph then follows that edge to the mapped destination node. The power of conditional edges is most apparent in agentic loops. A ReAct-style age…

Which LangChain classes support .add_conditional_edges()?

.add_conditional_edges() is available on StateGraph. Pin your installed LangChain version and verify the method exists in that release before deploying.

When should I use .add_conditional_edges()?

Use .add_conditional_edges() when your LangChain chains, agents, or pipelines need the behavior described in this guide.

What does .add_conditional_edges() return?

.add_conditional_edges() returns a StateGraph. Graph with conditional edges

Does .add_conditional_edges() have an async equivalent?

.add_conditional_edges() does not have a documented async variant. Avoid .add_conditional_edges() For unconditional routing—use add_edge().

Where can I explore more LangChain API reference pages?

Open the LangChain API reference index on DevShelfHub to browse classes, methods, and decorators, each with runnable examples, parameters, common mistakes, and cross-links.