Multi-agent architectures
Overview
In the previous lesson, you explored plan-and-execute agents and learned how to select an architecture based on the complexity of a task.
Until now, most of our architectures have focused on coordinating the behavior of an individual agent. That agent might use tools, retrieve information, execute a plan, reflect on its output, or request human approval.
However, production applications frequently require several distinct capabilities.
Consider an automated enterprise research system that must:
- Search internal documents and external information sources.
- Analyze structured data from a SQL database.
- Write a comprehensive report.
- Verify factual claims and supporting evidence.
- Obtain approval before publishing the report.
A single agent could theoretically perform every responsibility. In practice, giving one agent extensive instructions, dozens of tools, multiple security responsibilities, and a growing conversation history can make its behavior difficult to control.
A multi-agent architecture addresses this problem by distributing responsibilities among specialized agents and defining how they cooperate.
An agent within such a system typically has its own instructions, tools, model configuration, responsibilities, and execution boundaries. Multiple agents can use the same underlying language model while behaving differently because they receive different context and capabilities.
LangGraph provides the orchestration infrastructure that connects these agents through state, nodes, edges, subgraphs, and dynamic routing.
Importantly, a multi-agent system does not require multiple servers, processes, or model providers. Several specialized agents can execute within one Python application.
By the end of this lesson, you should understand how to select an appropriate coordination architecture and design the communication, state, and termination contracts that make agent collaboration reliable.
Single agent vs multi-agent systems
A single-agent system uses one primary decision-maker to interpret requests, select tools, execute actions, and generate responses.
A multi-agent system distributes these responsibilities among multiple specialized decision-makers.
The distinction is architectural rather than numerical. Calling the same model five times does not automatically create a multi-agent system. What matters is whether the components have distinct responsibilities, decision-making boundaries, and coordination mechanisms.
Comparing the approaches
| Dimension | Single agent | Multi-agent system |
|---|---|---|
| Decision-making | Centralized in one agent | Distributed across agents |
| Instructions | One primary instruction set | Role-specific instructions |
| Tool access | Common tool collection | Specialized tool collections |
| Context | Usually one primary context | Shared or isolated contexts |
| Implementation | Relatively simple | More orchestration required |
| Model calls | Generally fewer | Potentially more |
| Parallelism | Possible | Often easier to organize |
| Debugging | Fewer components | Requires cross-agent tracing |
| Security | Broader agent permissions | Supports finer permission boundaries |
| Best suited for | Focused tasks | Complex, specialized workflows |
When should you introduce multiple agents?
Consider multiple agents when:
- Tool selection becomes unreliable because the agent has too many capabilities.
- Different tasks require substantially different instructions or domain knowledge.
- Independent tasks can execute concurrently.
- Different responsibilities require different access permissions.
- Specialized components must be developed and tested independently.
- Independent review or verification materially improves output quality.
For example, an agent that retrieves customer order information and explains delivery status probably does not require multiple agents.
An enterprise procurement system involving supplier research, financial analysis, contract review, and approval workflows might benefit considerably from specialization.
Multiple agents also introduce additional failure modes. A worker might misunderstand its assignment, a supervisor might delegate unnecessarily, or two agents might repeatedly disagree.
Always establish a single-agent baseline before introducing additional architectural complexity. Compare task success rate, cost, latency, and maintainability rather than assuming that more agents produce better intelligence.
Four common architectures
Multi-agent architectures differ primarily in how control moves between agents.
Four widely applicable patterns are supervisors, handoffs, hierarchical teams, and routers.
| Architecture | Control mechanism | Typical interaction | Best application |
|---|---|---|---|
| Supervisor | Central coordinator | Delegate and return | Collaborative task execution |
| Handoffs | Agent-to-agent transfer | Transfer ownership | Multi-stage conversations |
| Hierarchical teams | Multiple coordination levels | Nested delegation | Large workflows |
| Router | Request classification | Dispatch and optionally aggregate | Domain-specific requests |
These patterns are not mutually exclusive. A production application might use a router at its entry point, a supervisor within each domain, and handoffs when transferring customer-facing responsibilities.
The LangChain multi-agent documentation describes several related coordination and context-management patterns.
Supervisor architecture
A supervisor architecture contains a central coordinating agent responsible for managing specialized workers.
The supervisor decides which worker should execute next, what information that worker needs, whether additional work is required, and when the overall task is complete.
Workers typically return results to the supervisor instead of independently deciding the entire workflow.
How a supervisor works
The following diagram illustrates centralized delegation between a supervisor and specialized workers.
Imagine that a user requests a report about database performance.
The supervisor might coordinate execution as follows:
- Delegate information gathering to the research agent.
- Receive research findings.
- Delegate report preparation to the writing agent.
- Send the draft to the review agent.
- Request corrections if the review identifies problems.
- Return the approved report.
Supervisors can use deterministic rules, structured model outputs, or model-selected tool calls to make delegation decisions.
An LLM-based supervisor offers flexibility when the sequence of work cannot be predicted. A deterministic supervisor is preferable when business rules already define the required order.
Centralized coordination simplifies auditing and gives the system a clear authority for final decisions. However, repeatedly returning to the supervisor introduces additional model calls and can create a performance bottleneck.
The next lesson will implement a complete supervisor architecture. Here, concentrate on the principle: workers perform bounded assignments, while the supervisor remains responsible for the overall objective.
Handoffs: Network architecture
A handoff occurs when one agent transfers control to another agent.
Unlike supervisor-based delegation, a handoff does not require every interaction to return to a central coordinator.
For example, a customer-support conversation might begin with a general support agent. After identifying a billing problem, that agent transfers responsibility to a billing specialist. If the issue requires technical investigation, the specialist may transfer responsibility again.
The currently active agent becomes responsible for continuing the interaction.
This is sometimes called a network architecture because agents can be connected through multiple permitted transfer paths.
Handoffs can be implemented between distinct agents or through dynamic changes to a single agent’s instructions and available tools.
Implementing a stateful handoff
Install the required packages for this lesson:
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openaiThe following example demonstrates persistent conversational ownership using Command and InMemorySaver. The worker functions use deterministic responses so you can inspect the architecture without paying for model calls.
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
from langgraph.checkpoint.memory import InMemorySaver
class SupportState(TypedDict):
query: str
active_agent: str
answer: str
def select_agent(
state: SupportState,
) -> Literal["triage", "billing"]:
if state.get("active_agent") == "billing":
return "billing"
return "triage"
def triage(
state: SupportState,
) -> Command[Literal["billing", "__end__"]]:
query = state["query"].lower()
if "invoice" in query or "payment" in query:
return Command(
update={"active_agent": "billing"},
goto="billing",
)
return Command(
update={
"active_agent": "triage",
"answer": "How can general support help?",
},
goto=END,
)
def billing(state: SupportState):
return {
"answer": f"Billing specialist handling: {state['query']}"
}
builder = StateGraph(SupportState)
builder.add_node("triage", triage)
builder.add_node("billing", billing)
builder.add_conditional_edges(START, select_agent)
builder.add_edge("billing", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "support-001"},
"recursion_limit": 10,
}
first = graph.invoke(
{
"query": "I have an invoice problem",
"active_agent": "triage",
"answer": "",
},
config,
)
second = graph.invoke(
{"query": "Can you explain the additional charge?"},
config,
)
print(first["active_agent"])
print(first["answer"])
print(second["answer"])Expected output:
billing
Billing specialist handling: I have an invoice problem
Billing specialist handling: Can you explain the additional charge?The first invocation transfers ownership to billing. The second invocation uses the same thread, allowing the graph to recover the saved active_agent field and route directly to billing.
Notice that reaching END completes the current graph invocation without deleting conversation ownership.
A production implementation would additionally support transferring back to general support, resolving the issue, authenticating the customer, and escalating to a human.
When model-selected handoff tools are used, they should preserve valid tool-call histories, including corresponding ToolMessage objects. The handoffs documentation explains this pattern in greater detail.
Hierarchical agent teams
A hierarchical architecture extends the supervisor pattern by introducing multiple coordination levels.
Instead of assigning every worker to a single supervisor, related workers are grouped into teams. Each team can have its own supervisor, while a higher-level supervisor coordinates the teams.
Consider an enterprise reporting application containing:
- A research team with document retrieval, database analysis, and evidence-verification agents.
- A content team with writing, editing, and formatting agents.
- A governance team with compliance and quality-control agents.
The top-level supervisor delegates objectives to team supervisors rather than interacting with every individual worker.
The following diagram illustrates nested delegation across specialized teams.
LangGraph subgraphs are particularly useful for hierarchical architectures.
Each team can be implemented as a separate graph with its own internal state, routing rules, tools, and termination conditions. The parent graph sees the team as a reusable component.
This allows independent development and testing. The research team can change its internal implementation without requiring changes to the main supervisor, provided its input and output contracts remain compatible.
Hierarchies also introduce overhead. Every additional coordination layer can increase latency, token consumption, and the risk of losing important details during summarization.
Use hierarchical teams when the organizational boundaries provide genuine engineering benefits, not simply to imitate a human organizational chart.
Router architecture
A router classifies an incoming request and dispatches it to the appropriate specialized agent or group of agents.
For example, an enterprise assistant might route requests involving invoices to a finance agent, employee policies to an HR agent, and software problems to an IT agent.
Unlike a supervisor, a basic router does not repeatedly inspect intermediate results and decide what to do next. Its primary responsibility is selecting the appropriate execution path.
Routing can be implemented using:
- Deterministic business rules.
- Classification models.
- Semantic similarity.
- LLM-generated structured outputs.
- Combinations of these techniques.
Parallel routing with Send
Sometimes a request requires information from multiple domains.
LangGraph’s Send allows a routing function to create separate tasks with customized inputs. The results can then be combined through a reducer.
The following runnable example simulates specialized finance and technical workers using local responses.
import operator
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send
class RouterState(TypedDict):
query: str
results: Annotated[list[str], operator.add]
answer: str
class WorkerState(TypedDict):
query: str
domain: str
def route(state: RouterState):
query = state["query"].lower()
domains = []
if "cost" in query or "budget" in query:
domains.append("finance")
if "database" in query or "server" in query:
domains.append("technical")
if not domains:
domains.append("general")
return [
Send(
"specialist",
{"query": state["query"], "domain": domain},
)
for domain in domains
]
def specialist(state: WorkerState):
responses = {
"finance": "Finance: Estimate infrastructure costs.",
"technical": "Technical: Evaluate database capacity.",
"general": "General: Collect additional requirements.",
}
return {"results": [responses[state["domain"]]]}
def synthesize(state: RouterState):
return {
"answer": "\n".join(sorted(state["results"]))
}
builder = StateGraph(RouterState)
builder.add_node("specialist", specialist)
builder.add_node("synthesize", synthesize)
builder.add_conditional_edges(START, route)
builder.add_edge("specialist", "synthesize")
builder.add_edge("synthesize", END)
graph = builder.compile()
result = graph.invoke(
{
"query": "Estimate the cost of upgrading our database",
"results": [],
"answer": "",
},
config={"recursion_limit": 10},
)
print(result["answer"])Expected output:
Finance: Estimate infrastructure costs.
Technical: Evaluate database capacity.The router creates two tasks targeting the same worker node with different inputs. LangGraph can execute these tasks concurrently within the same super-step.
The operator.add reducer combines both result lists, and the synthesis node runs after the parallel worker tasks complete.
In production, the worker would invoke the appropriate specialist agent or subgraph instead of returning predefined text.
See the router pattern documentation for additional routing approaches.
Two ways to call another agent
Agent coordination in LangGraph commonly uses two invocation mechanisms: tool-based delegation and graph-based orchestration.
Method 1: Agent as a tool
A specialized agent can be wrapped in a tool that another agent calls.
This approach is particularly useful when a supervisor should autonomously decide whether delegation is necessary.
The following example creates a database specialist and exposes it as a tool to a coordinating agent.
Set the OPENAI_API_KEY environment variable before running this example.
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.tools import tool
from langchain.messages import HumanMessage
model = init_chat_model("openai:gpt-5.4-mini")
database_agent = create_agent(
model=model,
tools=[],
system_prompt=(
"You are a database performance specialist. "
"Provide concise, technically accurate guidance. "
"Do not claim to have inspected a live database."
),
)
@tool
def consult_database_specialist(question: str) -> str:
"""Consult a specialist about SQL and database performance."""
result = database_agent.invoke(
{"messages": [HumanMessage(content=question)]},
config={"recursion_limit": 10},
)
return result["messages"][-1].text
supervisor = create_agent(
model=model,
tools=[consult_database_specialist],
system_prompt=(
"You coordinate technical specialists. "
"Consult the database specialist for database questions, "
"then explain the findings to the user."
),
)
result = supervisor.invoke(
{
"messages": [
HumanMessage(
content="Why might a SQL query ignore an index?"
)
]
},
config={"recursion_limit": 20},
)
print(result["messages"][-1].text)Expected behavior: the supervisor should consult the database specialist and use its response to explain causes such as low selectivity, small tables, stale statistics, or expressions that prevent efficient index usage.
The exact response and tool-selection behavior depend on the model.
Internally, the supervising agent issues a tool call, the tool invokes the specialist’s compiled agent graph, and the specialist’s result becomes a tool response available to the supervisor.
Only the delegated question is explicitly passed into the specialist. Its complete internal conversation does not automatically become part of the supervisor’s conversation.
This is the central mechanism behind the subagents pattern.
Method 2: Agent as a graph node or subgraph
When the application requires explicit orchestration, an agent can execute as a graph node.
A compiled subgraph can be added directly as a node when the parent and child share compatible state channels. Alternatively, a wrapper node can invoke the child and translate between different schemas.
The following example demonstrates direct subgraph composition using a deterministic research component.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
topic: str
findings: str
report: str
def collect(state: State):
return {
"findings": (
f"{state['topic']} requires explicit coordination."
)
}
research_builder = StateGraph(State)
research_builder.add_node("collect", collect)
research_builder.add_edge(START, "collect")
research_builder.add_edge("collect", END)
research_team = research_builder.compile()
def write(state: State):
return {"report": f"Report: {state['findings']}"}
parent = StateGraph(State)
parent.add_node("research", research_team)
parent.add_node("write", write)
parent.add_edge(START, "research")
parent.add_edge("research", "write")
parent.add_edge("write", END)
graph = parent.compile()
result = graph.invoke(
{
"topic": "Multi-agent systems",
"findings": "",
"report": "",
}
)
print(result["report"])Expected output:
Report: Multi-agent systems requires explicit coordination.A real research team could contain model calls, retrieval tools, retries, and additional agents without changing the parent’s basic structure.
| Consideration | Agent as tool | Agent as node or subgraph |
|---|---|---|
| Invocation | Usually model-selected | Controlled by graph routing |
| Context exchange | Explicit tool arguments | Shared channels or mapped state |
| Workflow predictability | Lower | Higher with explicit edges |
| Best use | Flexible delegation | Structured orchestration |
See the LangGraph subgraphs guide for schema mapping and nested persistence.
Note: The deterministic examples intentionally simulate agent responsibilities to make orchestration predictable. The model-based example requires provider credentials and model access. API usage was checked against the official documentation, but the examples were not runtime-executed in the authoring environment.
Shared vs isolated state
State design is one of the most consequential decisions in multi-agent engineering.
It determines which information agents can access, how they collaborate, and how their execution can be recovered.
Shared state
With shared state, agents operate on common graph channels.
For a research and writing workflow, shared fields might include the original objective, evidence, current draft, reviewer feedback, and execution status.
Workers return updates rather than mutating global state directly.
LangGraph applies those updates according to each channel’s reducer. Ordinary fields generally replace their previous values, while fields configured with reducers can accumulate or merge updates.
When multiple parallel workers write to the same channel, that channel needs an appropriate reducer; otherwise, conflicting writes can raise InvalidUpdateError.
For message-based workflows, use MessagesState or configure a message field with add_messages.
import operator
from typing import Annotated
from langgraph.graph import MessagesState
class TeamState(MessagesState):
objective: str
findings: Annotated[list[str], operator.add]
draft: str
review_feedback: str
status: strHere, messages use LangGraph’s message-aware reducer, findings accumulate, and the remaining fields use ordinary replacement behavior.
Shared state simplifies collaboration but does not mean every agent should receive every field in its model prompt.
Isolated state
With isolated state, each agent maintains its own working context and exchanges selected information with other components.
For example, a research agent might process extensive documents and tool results internally while returning only verified findings and source identifiers to the parent.
Isolation reduces context consumption, prevents irrelevant instructions from spreading between agents, and supports clearer component boundaries.
However, state isolation is not a security sandbox. Sensitive tools and external data sources still require application-level authorization.
Hybrid state
Production systems frequently combine both approaches.
Keep objectives, task statuses, approved artifacts, and coordination metadata in shared state. Keep verbose tool interactions and specialist-specific working messages local to each agent.
Use checkpointers for resumable thread execution and stores for appropriately scoped information that must survive across threads.
Pass immutable request-scoped dependencies and authenticated identity through runtime context rather than placing user data in config["configurable"].
Agent communication and collaboration
Agents should exchange information through explicit communication contracts rather than ambiguous conversational instructions alone.
A delegation request might contain a task identifier, objective, constraints, relevant evidence, and expected output format.
A worker response should communicate its outcome, findings, supporting sources, limitations, and any requested follow-up.
Define these contracts using TypedDict, Pydantic models, structured model outputs, or validated tool arguments.
Keep the original objective available throughout execution. Otherwise, repeated delegation and summarization can gradually distort what the user requested.
Assign ownership of important state fields. For example, let the writer own the draft, the reviewer own the review decision, and the supervisor own the overall workflow status.
When communicating between parent and child graphs, Command.PARENT can transfer execution to an appropriate node in the parent graph. Compatible state channels and reducers must be designed carefully for these cross-graph updates.
Remember that workers can disagree or return incomplete information. Treat their outputs as evidence to evaluate, not automatically trusted instructions.
External documents and retrieved content can also contain prompt injection. Never allow a worker’s textual response alone to authorize privileged actions.
Communication and termination
A multi-agent workflow must have a clear definition of completion.
Without explicit termination conditions, a supervisor can delegate indefinitely, two specialists can repeatedly hand off responsibility, or a reviewer can request endless revisions.
Semantic and operational termination
Semantic termination means the business objective has been satisfied. Examples include an approved report, a resolved support case, or a successfully completed analysis.
Operational termination means execution must stop because a resource limit or failure condition has been reached.
Production systems need both.
Typical operational safeguards include:
- Maximum delegation and revision counts.
- Model-call and token budgets.
- Wall-clock deadlines.
- Detection of repeated handoffs or unchanged artifacts.
- Bounded retries for transient failures.
- Escalation when required information is unavailable.
- Explicit terminal states for success, failure, and partial completion.
LangGraph’s END marks graph completion. The recursion_limit configuration provides an additional safeguard against runaway graph execution.
For example, invoke a graph with config={"recursion_limit": 25} to impose an explicit super-step limit.
The recursion limit is not a precise model-call budget, particularly when parallel tasks or nested agents are involved. Track those resources separately when they matter.
Tip: Do not rely on instructions such as “finish when the task is complete” as your only termination mechanism. Enforce execution limits and completion criteria in Python.
An unresolved workflow can terminate with a meaningful escalation status or pause using interrupt() when human input is required. These outcomes should not be reported as successful completion.
For production observability, use LangSmith tracing to examine routing decisions, worker invocations, costs, and repeated execution paths. Test both final outputs and execution trajectories, including incorrect routing, worker failure, exhausted budgets, and unsuccessful review cycles.
Connection to the upcoming lessons
The previous lesson introduced planning as a mechanism for organizing complex work. Multi-agent architectures extend that idea by assigning portions of the work to specialized execution components.
In the next lesson, Building a supervisor architecture, you will implement a central coordinator that dynamically selects workers, evaluates their results, and controls termination.
The subsequent lesson will examine agent handoffs and delegation in greater depth, including how responsibility moves between agents.
These techniques will ultimately be combined in this chapter’s hands-on project: a collaborative research, writing, and review team with explicit responsibilities, controlled revisions, structured communication, and reliable completion conditions.
Build a bounded agent handoff workflow
Build a LangGraph workflow in which a drafting worker hands its output to a reviewing worker. The reviewer must approve acceptable drafts, request a revision when necessary, or terminate with an escalation status after two drafting attempts. Use Command for routing and shared state to track the draft, revision count, and final status. Test both successful revision and escalation scenarios.
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
class State(TypedDict):
topic: str
draft: str
attempts: int
allow_revision: bool
status: str
def draft_agent(state: State) -> Command[Literal["review"]]:
# TODO: Increment attempts and create or revise the draft.
# On the second attempt, add a source marker if revision is allowed.
# Transfer control to the reviewer.
raise NotImplementedError
def review_agent(
state: State,
) -> Command[Literal["draft", "__end__"]]:
# TODO: Approve drafts containing "[source: demo]".
# Request another draft if fewer than two attempts have occurred.
# Otherwise, terminate with status "needs_human_review".
raise NotImplementedError
builder = StateGraph(State)
builder.add_node("draft", draft_agent)
builder.add_node("review", review_agent)
# TODO: Connect START to the drafting worker.
# Compile the graph and invoke it with a recursion limit.
initial_state: State = {
"topic": "Agentic AI",
"draft": "",
"attempts": 0,
"allow_revision": True,
"status": "pending",
}from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
class State(TypedDict):
topic: str
draft: str
attempts: int
allow_revision: bool
status: str
def draft_agent(state: State) -> Command[Literal["review"]]:
attempts = state["attempts"] + 1
draft = f"Introduction to {state['topic']}."
if attempts > 1 and state["allow_revision"]:
draft += " [source: demo]"
return Command(
update={
"draft": draft,
"attempts": attempts,
"status": "pending_review",
},
goto="review",
)
def review_agent(
state: State,
) -> Command[Literal["draft", "__end__"]]:
if "[source: demo]" in state["draft"]:
return Command(
update={"status": "approved"},
goto=END,
)
if state["attempts"] >= 2:
return Command(
update={"status": "needs_human_review"},
goto=END,
)
return Command(
update={"status": "revision_requested"},
goto="draft",
)
builder = StateGraph(State)
builder.add_node("draft", draft_agent)
builder.add_node("review", review_agent)
builder.add_edge(START, "draft")
graph = builder.compile()
initial_state: State = {
"topic": "Agentic AI",
"draft": "",
"attempts": 0,
"allow_revision": True,
"status": "pending",
}
success = graph.invoke(
initial_state,
config={"recursion_limit": 10},
)
escalation = graph.invoke(
{**initial_state, "allow_revision": False},
config={"recursion_limit": 10},
)
print(success["draft"])
print(success["status"], success["attempts"])
print(escalation["status"], escalation["attempts"])
assert success["status"] == "approved"
assert success["attempts"] == 2
assert escalation["status"] == "needs_human_review"
assert escalation["attempts"] == 2
# Expected output:
# Introduction to Agentic AI. [source: demo]
# approved 2
# needs_human_review 2Summary
- Multi-agent architectures divide complex responsibilities among specialized agents with explicit coordination and communication mechanisms.
- A single agent remains preferable when specialization does not provide measurable improvements in reliability, security, or performance.
- Supervisors centralize delegation, handoffs transfer control, hierarchical teams distribute coordination, and routers dispatch requests according to their requirements.
- Agents can collaborate through tool-based delegation or graph-based orchestration using nodes, subgraphs, and Command.
- Shared state simplifies collaboration, while isolated state protects context boundaries and reduces unnecessary token consumption.
- Structured communication contracts and reducers make agent collaboration more predictable and maintainable.
- Every multi-agent system requires explicit completion conditions, execution budgets, failure handling, and protection against infinite loops.