Conditional routing
Conditional edges are what make our graph intelligent. They route execution based on the current state - like checking if there was an error or if visualization is needed.
def should_retry(state: AgentState) -> str:
"""Decide whether to retry after an error"""
if state.get("error"):
iteration = state.get("iteration", 0)
if iteration <= 3:
return "retry"
else:
return "end"
return "success"
def should_generate_graph(state: AgentState) -> str:
"""Decide whether to generate a graph"""
if state.get("needs_graph", False):
return "viz_agent"
return "skip_graph"
def check_scope(state: AgentState) -> str:
"""Check if question is in scope"""
if state.get("is_in_scope", True):
return "in_scope"
return "out_of_scope"Routing functions return string keys that map to next nodes.
Yes, they must exactly match the keys in the edge mapping dictionary you pass to add_conditional_edges. If your function returns "retry" but the mapping only has "Retry", LangGraph will raise an error. The diagrams below show each mapping.
Check_scope routing
How routing function returns map to next nodes.
Should_retry routing
Should_generate_graph routing
The check_scope routing function looks at the is_in_scope flag in state. If the question is out of scope, it routes directly to END, skipping all the SQL generation and analysis steps. The user gets a polite message saying the chatbot only handles e-commerce database questions.
Matching exercise: Match routing functions to decisions
Loading practice…
AI prompt: Try it with AI
Loading practice…
Fill in the blanks: Complete the conditional edge
Loading practice…
Hints: Hints
Loading practice…
You have wired up all the conditional routing logic. The graph now makes intelligent decisions at every branch point. Next, we will add streaming so users see progress in real time.