06. Advanced: LangGraph Supervisor
Overview
Moving beyond sequential chains (A → B → C), we explore the Supervisor Pattern. A single "Supervisor Node" (LLM) sees the state and decides who acts next (Researcher vs Coder) or if the job is finished.
This mimics a real-world team structure and is essential for building "Deep Agents" that can handle open-ended tasks.
The Supervisor Pattern
Key Concepts
| Concept | Description |
|---|---|
| Supervisor | LLM that decides routing and task completion |
| Worker Nodes | Specialized agents (research, code, review) |
| State | Shared context passed between all nodes |
| Routing | Dynamic decision based on current state |
Implementation with LangGraph
from langgraph.graph import StateGraph, END
from typing import TypedDict, Literal
class AgentState(TypedDict):
messages: list
next: str
def supervisor_node(state: AgentState) -> AgentState:
"""Supervisor decides who acts next"""
response = llm.invoke([
SystemMessage(content="""You are a supervisor managing a team.
Based on the conversation, decide who should act next:
- 'researcher' for information gathering
- 'coder' for implementation
- 'FINISH' if task is complete"""),
*state["messages"]
])
return {"next": response.content}
def researcher_node(state: AgentState) -> AgentState:
"""Research agent gathers information"""
# ... research logic
return {"messages": state["messages"] + [result]}
def coder_node(state: AgentState) -> AgentState:
"""Coder agent writes code"""
# ... coding logic
return {"messages": state["messages"] + [result]}Building the Graph
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("supervisor", supervisor_node)
workflow.add_node("researcher", researcher_node)
workflow.add_node("coder", coder_node)
# Add edges
workflow.add_conditional_edges(
"supervisor",
lambda x: x["next"],
{
"researcher": "researcher",
"coder": "coder",
"FINISH": END
}
)
workflow.add_edge("researcher", "supervisor")
workflow.add_edge("coder", "supervisor")
workflow.set_entry_point("supervisor")
app = workflow.compile()Why Supervisor Pattern?
Dynamic Routing: The supervisor adapts to the task, calling specialists as needed
| Sequential | Supervisor |
|---|---|
| Fixed order A→B→C | Dynamic routing |
| All steps always run | Skip unnecessary steps |
| Simple tasks | Complex, open-ended tasks |
Hands-on Practice
Define Worker Agents
Create researcher and coder nodes
Build Supervisor Logic
Implement routing decisions
Wire the Graph
Connect nodes with conditional edges
Test with Tasks
Run different queries and observe routing