Module 7 Lesson 1: Conditional Routing
·Agentic AI

Module 7 Lesson 1: Conditional Routing

The logic of the graph. Mastering how to route control based on tool calls, state variables, and LLM output.

Conditional Routing: Handling Complexity

In simple graphs, you just move from A to B. In "High-Agency" systems, the agent needs to make complex decisions. Should I search? Should I ask the user a question? Should I calculate something? Should I stop?

Conditional Routing is the LangGraph mechanism for these "If/Then" scenarios.

1. The Routing Function

A routing function is a standard Python function that looks at the Current State and returns a String. That string maps to the next node in the graph.

def router_logic(state: AgentState):
    # 1. Check if the LLM wants to use a tool
    if state["messages"][-1].tool_calls:
        return "call_tools"
    
    # 2. Check if the user is asking to exit
    if "goodbye" in state["messages"][-1].content.lower():
        return "end"
        
    return "ask_llm"

2. Dynamic vs. Fixed Routing

  • Fixed: workflow.add_edge("node_a", "node_b"). (Static path).
  • Dynamic: workflow.add_conditional_edges("node_a", router_logic, mapping). (Path determined at runtime).

3. The "Multi-Path" Edge

You don't just have to choose between two nodes. A routing function can navigate to any number of specialized nodes.

graph TD
    Agent[Agent Node] --> Router{Router}
    Router -->|Coding| NodeC[Code Specialist]
    Router -->|Research| NodeR[Research Specialist]
    Router -->|Math| NodeM[Calculation Specialist]
    Router -->|Done| END

Mapping the Router:

workflow.add_conditional_edges(
    "agent",
    router_logic,
    {
        "call_tools": "tools_node",
        "end": END,
        "ask_llm": "agent"
    }
)

4. Engineering Tip: Don't trust the LLM's Text

When routing, try to avoid checking for keywords in the LLM's text (e.g., if "I am done" in content). This is fragile. Instead, force the LLM to use Tool Calls.

  • If the model calls a final_answer_tool, route to END.
  • If the model calls a google_search_tool, route to TOOLS.

This turns your routing into a Type-Safe operation.


5. Visualizing Complex Routing

graph TD
    Start --> Inbound[Inbound Sanitizer]
    Inbound --> Brain[Main LLM]
    Brain --> Router{Decision}
    Router -- Search --> S[Search Node]
    Router -- Python --> P[Python Node]
    Router -- Done --> Outbound[Outbound Validator]
    S --> Brain
    P --> Brain
    Outbound --> END

Key Takeaways

  • Conditional Routing makes your agent non-linear.
  • The Routing Function is the brains behind the navigation.
  • Tool Calls are the most reliable way to trigger specific routes.
  • Always define a default path in your router to prevent the graph from getting "stuck."

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn