Lesson 10 of 11 · Advanced
Multi-Agent Graphs
Build multi-agent systems in LangGraph: a supervisor routing with Command, agents handing back, parallel workers with Send, reducers and worker failures.
- 7 min read
- Advanced
- Reviewed
- Build a supervisor that routes work to agent nodes with Command
- Let agents hand control back to the supervisor
- Run the same worker in parallel with different inputs using Send
- Collect parallel results with a reducer and handle failed workers
- Choose between supervisor, handoff and map-reduce designs
Agents as nodes
The Multi-Agent Systems course explained why and when to split work across agents. LangGraph is one of the most common ways to build them, because every pattern from that course maps onto graph pieces:
| Pattern | In LangGraph |
|---|---|
| Lead agent with specialists | A supervisor node that routes to agent nodes |
| Handoffs | Nodes returning Command(goto=...) |
| Parallel workers | Send from a conditional edge, results joined by a reducer |
| Each agent with its own loop and tools | Each agent is a subgraph (lesson 9) |
A supervisor and two agents
from typing import Literal
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.types import Command
AGENTS = ["billing_agent", "repair_agent"]
def supervisor(state: MessagesState) -> Command[Literal["billing_agent", "repair_agent", "__end__"]]:
"""Decides who acts next. A model with structured output would usually make this choice."""
last = state["messages"][-1]
if last.type == "ai": # an agent has answered: finish
return Command(goto=END)
text = last.content.lower()
return Command(goto="billing_agent" if "charged" in text or "refund" in text else "repair_agent")
def billing_agent(state: MessagesState) -> Command[Literal["supervisor"]]:
reply = "Billing agent: I've found the duplicate charge and started a refund."
return Command(update={"messages": [("ai", reply)]}, goto="supervisor") # hand back control
def repair_agent(state: MessagesState) -> Command[Literal["supervisor"]]:
reply = "Repair agent: book a brake check at our Porto workshop; it takes about an hour."
return Command(update={"messages": [("ai", reply)]}, goto="supervisor")
builder = StateGraph(MessagesState)
builder.add_node("supervisor", supervisor)
builder.add_node("billing_agent", billing_agent)
builder.add_node("repair_agent", repair_agent)
builder.add_edge(START, "supervisor")
graph = builder.compile()
for question in ["I was charged twice for my e-bike", "My brakes are making a grinding noise"]:
print("User:", question)
for step in graph.stream({"messages": [("user", question)]}, stream_mode="updates"):
for node, update in step.items():
said = update["messages"][-1][1] if update else "(routes the conversation)"
print(f" {node:<14} {said}")User: I was charged twice for my e-bike supervisor (routes the conversation) billing_agent Billing agent: I've found the duplicate charge and started a refund. supervisor (routes the conversation) User: My brakes are making a grinding noise supervisor (routes the conversation) repair_agent Repair agent: book a brake check at our Porto workshop; it takes about an hour.
There are no edges between the agents at all. The supervisor returns Command(goto=...) to send the conversation to an agent, and each agent returns a Command that adds its message and hands control back. When an agent has answered, the supervisor ends the run. The Command[Literal[...]] return types tell LangGraph which moves are possible.
In a real system, each agent would be a subgraph with its own model, prompt and tools (like the agent from lesson 5), and the supervisor would choose with a model using structured output, limited to the agent names.
Parallel workers with Send
When the same kind of work is needed for several items, such as researching several topics, run one worker per item at the same time:
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
class State(TypedDict):
question: str
topics: list[str]
findings: Annotated[list[str], operator.add] # every worker adds to this list
answer: str
class WorkerInput(TypedDict):
topic: str
def plan(state: State) -> dict: # a lead model would choose the topics
return {"topics": ["battery range", "repair network", "price"]}
def assign_workers(state: State) -> list[Send]:
# One Send per topic: the same node runs once for each, in parallel, with its own input
return [Send("research", {"topic": t}) for t in state["topics"]]
def research(state: WorkerInput) -> dict: # a worker agent would search here
return {"findings": [f"{state['topic']}: 2 sources checked"]}
def synthesise(state: State) -> dict:
return {"answer": f"{len(state['findings'])} topics researched: " + "; ".join(sorted(state["findings"]))}
builder = StateGraph(State)
builder.add_node("plan", plan)
builder.add_node("research", research)
builder.add_node("synthesise", synthesise)
builder.add_edge(START, "plan")
builder.add_conditional_edges("plan", assign_workers, ["research"])
builder.add_edge("research", "synthesise")
builder.add_edge("synthesise", END)
graph = builder.compile()
print(graph.invoke({"question": "Which e-bike should we buy?", "findings": []})["answer"])3 topics researched: battery range: 2 sources checked; price: 2 sources checked; repair network: 2 sources checked
The planner chose three topics; assign_workers returned three Sends; the research node ran three times in parallel, each with only its own topic; and the operator.add reducer collected every finding before synthesise ran. The number of workers is decided at run time: five topics would mean five workers, with no change to the graph.
When a worker fails
Parallel workers fail independently. A robust design records failures as gaps and carries on, so the synthesis can say what's missing:
# Map-reduce with Send, in plain Python: the same worker runs once per topic with its own input,
# results are collected by a reducer, and failures become gaps instead of crashing the whole run.
def research(task):
if task["topic"] == "repair network":
raise TimeoutError("search API timed out")
return {"findings": [f"{task['topic']}: 2 sources"]}
def run_map_reduce(topics):
sends = [("research", {"topic": t}) for t in topics] # like [Send("research", {...}), ...]
state = {"findings": [], "gaps": []}
for node, task in sends: # LangGraph runs these in parallel
try:
update = research(task)
state["findings"] += update["findings"] # the operator.add reducer
except Exception as e:
state["gaps"].append(f"{task['topic']} ({e})")
return state
result = run_map_reduce(["battery range", "repair network", "price"])
print("Findings:", result["findings"])
print("Gaps: ", result["gaps"])In LangGraph, catch errors inside the worker node and return them as data (for example, a gaps key with its own reducer), or add a RetryPolicy to the node so transient failures are retried automatically.
Choosing a design
- Supervisor: one coordinator decides each next step. Easy to follow and control; the supervisor is an extra model call per step.
- Handoffs between agents: agents pass control directly to each other, like the triage-and-specialists design in the Multi-Agent Systems course. Fewer calls, but harder to see the overall flow.
- Map-reduce with Send: the same work on many items, in parallel. Ideal for research, document processing and evaluation.
Common mistakes
Write the fan-out step of a map-reduce graph: one task per topic for the same worker node, skipping work that's already done.
topics = ["battery range", "price", "repair network", "weight"]
already_done = {"price"}
# Build the list of tasks to send: one ("research", {"topic": t}) pair per topic,
# in order, skipping topics in already_done. Print the list.
What does returning [Send('research', {'topic': t}) for t in topics] from a conditional edge do?
Summary
- Multi-agent patterns map onto graph pieces: supervisor nodes, Command handoffs, Send for parallel workers, subgraphs for agents.
- A supervisor routes with
Command(goto=...); agents hand control back the same way. Sendruns one node per item in parallel; a reducer collects the results.- Record failed workers as gaps, use retry policies, and cap the fan-out and the number of turns.
Next: the project, a research agent.
Finished reading? Tick it off to track your progress.