Skip to content

Chapter 6 · Conditional Edges, Subgraphs, and Modularity ​

Chapter goals:

  • Master conditional edge (conditional edges) routing logic
  • Learn to use subgraphs (subgraph) for modularization
  • Understand multi-step orchestration patterns for complex Agents

6.1 Conditional Edges Basics ​

Conditional edges route to different nodes based on state:

python
from langgraph.graph import StateGraph, MessagesState, START, END

def router(state: MessagesState) -> str:
    """Route based on last message"""
    last_msg = state["messages"][-1]
    if "help" in last_msg.content.lower():
        return "help_node"
    if "bye" in last_msg.content.lower():
        return END
    return "agent_node"

workflow = StateGraph(MessagesState)
workflow.add_node("agent", agent_func)
workflow.add_node("help", help_func)

workflow.add_conditional_edges(
    "agent",
    router,
    {"help_node": "help", "agent_node": "agent", END: END}
)

6.1.1 Complex Routing ​

python
def complex_router(state: AgentState) -> str:
    last_msg = state["messages"][-1]
    
    # Check for emergency
    if is_emergency(last_msg.content):
        return "escalation"
    
    # Check tool calls
    if last_msg.tool_calls:
        return "tools"
    
    # Check confidence
    if get_confidence(last_msg) > 0.9:
        return "respond"
    
    return "agent"

6.2 Subgraphs: Modular Design ​

Subgraphs encapsulate complex workflows:

python
from langgraph.graph import StateGraph

# Define subgraph
research_workflow = StateGraph(ResearchState)
research_workflow.add_node("search", search_node)
research_workflow.add_node("synthesize", synthesize_node)
research_workflow.add_edge(START, "search")
research_workflow.add_edge("search", "synthesize")
research_workflow.add_edge("synthesize", END)
research_graph = research_workflow.compile()

# Use in main graph
main_workflow = StateGraph(MainState)
main_workflow.add_node("research", research_graph.invoke)
main_workflow.add_edge(START, "research")
main_workflow.add_edge("research", END)
main_graph = main_workflow.compile()

6.2.1 Subgraph State Mapping ​

python
# Map outer state to inner state
def map_state(inputs: dict) -> dict:
    return {
        "query": inputs["user_query"],
        "context": inputs.get("context", {})
    }

# Map inner state back
def map_output(outputs: dict) -> dict:
    return {
        "research_result": outputs["synthesis"],
        "sources": outputs["search_results"]
    }

6.3 Multi-Agent Orchestration ​

python
from langgraph.graph import StateGraph

class OrchestratorState(TypedDict):
    messages: Annotated[list, operator.add]
    task_type: str

def classifier(state: OrchestratorState) -> dict:
    # Classify task type
    return {"task_type": "customer_support"}

def route_to_agent(state: OrchestratorState) -> str:
    if state["task_type"] == "customer_support":
        return "support_agent"
    elif state["task_type"] == "technical":
        return "tech_agent"
    return "general_agent"

workflow = StateGraph(OrchestratorState)
workflow.add_node("classifier", classifier)
workflow.add_node("support_agent", support_agent_func)
workflow.add_node("tech_agent", tech_agent_func)
workflow.add_node("general_agent", general_agent_func)

workflow.add_edge(START, "classifier")
workflow.add_conditional_edges("classifier", route_to_agent)
workflow.add_edge("support_agent", END)
workflow.add_edge("tech_agent", END)
workflow.add_edge("general_agent", END)

graph = workflow.compile()

Chapter Summary ​

  1. Conditional Edges: Route based on state conditions;
  2. Subgraphs: Encapsulate complex workflows for reuse;
  3. Multi-Agent: Orchestrate multiple specialized agents;
  4. State Mapping: Transform state between subgraph boundaries.

🛠️ Hands-on Practice ​

  1. Build a router that classifies queries into 3 categories and routes to different handling nodes.

  2. Create a subgraph for "research task" that can be reused across multiple parent graphs.

  3. Implement a multi-agent system where a supervisor routes tasks to specialized agents.


🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the purpose of add_conditional_edges?

2. What is the benefit of using subgraphs?

3. How do you map state between subgraph and parent graph?

4. What pattern enables multi-agent orchestration?