Conditional Routing and Branching
Use add_conditional_edges to dispatch based on state — the agent decides where to go next.
Conditional Routing and Branching is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Conditional Edges?
Real agents make decisions. After a step, the next step depends on the current state. Conditional edges encode that logic.
Adding a Conditional Edge
Three ingredients: source node, router function, destination map:
def route_after_planning(state: AgentState) -> str:
if state.get('confidence', 0) > 0.8:
return 'execute'
return 'replan'
graph.add_conditional_edges(
'planner',
route_after_planning,
{
'execute': 'executor',
'replan': 'planner'
}
)Routing Function Signatures
The router takes the full state, returns a string (or list of strings for parallel branches).
Self-Loops
An edge can loop back to the same node — used for retries:
graph.add_conditional_edges(
'validator',
lambda s: 'retry' if not s['valid'] else 'done',
{'retry': 'planner', 'done': END}
)Parallel Branches
Return a list of node names to run multiple downstream nodes in parallel:
def fan_out(state):
return ['search_news', 'search_arxiv', 'search_github']
graph.add_conditional_edges('planner', fan_out)Joining Parallel Branches
Parallel branches re-converge at a common downstream node. State merges combine their outputs (use reducers for lists/dicts).
Routing on Tool Calls
Classic pattern: after the LLM responds, check for tool_calls and route accordingly:
def should_use_tool(state):
last_msg = state['messages'][-1]
if last_msg.tool_calls:
return 'tools'
return END
graph.add_conditional_edges('agent', should_use_tool, {'tools': 'tools', END: END})Multi-Way Routing
Switch-case logic:
def route_by_intent(state):
intent = classify(state['messages'][-1])
return {'q': 'qa_agent', 'order': 'order_agent', 'support': 'support_agent'}.get(intent, 'fallback')Routing with LLM Calls
You can use an LLM to decide where to go next:
def llm_router(state):
decision = llm.invoke(f'Route this to: search, calculate, or end?\nState: {state}').content.strip()
return decision # 'search' / 'calculate' / ENDAvoid Infinite Loops
Without a step counter, an agent can loop forever. Add a counter to state:
class State(TypedDict):
step: int
...
def route(state):
if state['step'] >= MAX_STEPS:
return END
return 'continue'Increment Counter Reducer
def add(old: int, new: int) -> int:
return old + new
class State(TypedDict):
step: Annotated[int, add]
def any_node(state):
return {'step': 1} # increments by 1Visualising Branches
The Mermaid diagram of a graph with conditional edges shows decision diamonds — useful for review:
print(app.get_graph().draw_mermaid())Conditional Edges
What does the router function in add_conditional_edges return?
Recap
Conditional edges are how agents make decisions. Add a step counter to avoid loops, and visualise the graph to keep your sanity.
Frequently asked questions
Is the “Conditional Routing and Branching” lesson free?
Yes — the full text of “Conditional Routing and Branching” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Conditional Routing and Branching”?
Use add_conditional_edges to dispatch based on state — the agent decides where to go next. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Conditional Routing and Branching” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why Graphs Beat Flat Chains
- Nodes, Edges and State
- Conditional Routing and Branching
- Persisting Graph State (Checkpoints)