LangChain Multi-Agent - Multi-Agent Collaboration
When a task involves multiple different domains, or a single Agent needs to handle a large number of tools and complex workflows, you can consider using a Multi-agent architecture.
The core idea of multi-agent is to split a complex task into multiple relatively independent subtasks, let different Agents handle different domains, and then have a coordinator aggregate the results.
For example, a programming learning assistant can be divided into a course retrieval Agent, a code analysis Agent, and a learning planning Agent. Each Agent uses its own System Prompt and tools, and does not need to master all business details.
This chapter is based on LangChain 1.x and introduces Subagents, Supervisor, Router, Handoffs, sequential workflows, and context management for multi-agent systems.
1. Why do we need multiple Agents?
A single Agent can accomplish a lot, but as task complexity continues to increase, the following problems may arise:
- **Too much context:** A large number of system prompts, documents, and tool results occupy the context window.
- **Difficulty selecting tools:** When there are many available tools, the model may choose the wrong tool or parameters.
- **Mixed professional capabilities:** Different tasks require different processing rules and data sources.
- **Complex maintenance:** With all business logic concentrated in one Agent, modification and testing are difficult.
Multi-agent can split tasks into independent modules, with each Agent receiving only the information needed to complete its current task.
However, note that multi-agent does not necessarily improve answer accuracy or reduce costs.
Because each sub-Agent may incur additional model calls, token consumption, and network latency.
Single Agent vs. Multi-Agent comparison
| Comparison Item | Single Agent | Multi-Agent |
|---|---|---|
| structures | One Agent handles all tasks | Multiple specialized Agents collaborate |
| Tool Management | Centralized management | Grouped by domain |
| Context | Usually handled by one Agent | Can isolate context for subtasks |
| Development cost | relatively simple | Requires coordination and routing logic |
| Model calls | Usually fewer | May increase |
| Applicable scenarios | Simple tasks, few tools | Multiple domains, complex workflows |
**Recommendation:** If one Agent with reasonable tool grouping can solve the problem, there is no need to increase architectural complexity just to use multiple Agents.
2. LangChain multi-agent architecture patterns
LangChain officially introduces the following collaboration patterns:
| Mode | Principle | Applicable scenarios |
|---|---|---|
Subagents |
The main Agent calls specialized sub-Agents through tools | Multi-domain tasks, unified coordination |
Router |
Classify tasks first, then dispatch them to specialized Agents | Customer service classification, knowledge base retrieval |
Handoffs |
Switch specialized processing stages according to the current state | Multi-stage customer service, human takeover |
Skills |
Load professional knowledge and operating instructions on demand | Many tools and knowledge, but no need for multiple independent Agents |
Custom Workflow |
Use LangGraph to define execution nodes and edges | Fixed order, complex conditions, and parallel tasks |
Among these, the easiest way to get started is Subagents (sub-Agents as tools).
3. Method 1: Sub-Agents as tools
The Subagents pattern is also known as the Supervisor pattern.
It contains a main Agent (coordinator) and multiple sub-Agents with specialized capabilities.
Execution flow:
用户问题
|
v
主 Agent
Supervisor
|
+---------+---------+
| |
v v
课程 Agent 计算 Agent
| |
查询课程目录 数学计算
| |
+---------+---------+
|
v
主 Agent 汇总
|
v
最终回答
The main Agent does not need to master all internal tools of each sub-Agent; it only needs to know when to call the corresponding expert.
Basic implementation
First create the sub-Agent:
subagent = create_agent(
model="deepseek:deepseek-flash",
tools=[...],
system_prompt="You are a professional assistant."
)
Then wrap it as a tool:
@tool
def ask_expert(question: str) -> str:
"""向专业 Agent 咨询。"""
result = subagent.invoke({
"messages": [{"role": "user", "content": question}]
})
return result["messages"][-1].content
Finally, have the main Agent call that tool:
coordinator = create_agent(
model="deepseek:deepseek-flash",
tools=[ask_expert]
)
Although the sub-Agent here is an independent CompiledStateGraph, the parent Agent calls it through a Python tool function rather than automatically merging the subgraph nodes into the parent graph.
4. Complete example: Course expert and math expert collaboration
Below we create three Agents:
- Course expert: queries mock programming courses.
- Math expert: performs numerical calculations.
- Main Agent: analyzes the user's question, calls the experts, and organizes the answer.
This example does not use eval() to execute expressions generated by the model; instead, it defines math tools with explicit parameters.
Filename:multi_agent_demo.py
Install dependencies:
pip install -U langchain langgraph langchain-deepseek python-dotenv
Configure .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
load_dotenv
(
)
MODEL
=
"deepseek:deepseek-flash"
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query mock programming courses by language keyword."""
courses
=
{
"python"
:
"Python3 basic tutorial, beginner"
,
"java"
:
"Java basic tutorial, beginner"
}
return
courses.
get
(
keyword
.
strip
(
)
.
lower
(
)
,
"No matching simulated course found"
)
@
tool
def
celsius_to_fahrenheit
(
celsius:
float
)
float
:
"""Convert Celsius to Fahrenheit."""
return
round
(
celsius *
9
/
5
32
,
2
)
course_agent
=
create_agent
(
model
=
MODEL
,
tools
=
[
search_course
]
,
name
=
"course_expert"
,
system_prompt
=
"You are the course expert. Use tools when querying courses; the course data is for teaching simulation only."
)
math_agent
=
create_agent
(
model
=
MODEL
,
tools
=
[
celsius_to_fahrenheit
]
,
name
=
"math_expert"
,
system_prompt
=
"You are the numerical calculation expert. You must use tools for temperature conversion; do not guess the calculation result."
)
@
tool
def
ask_course_expert
(
question:
str
)
str
:
"""Delegate programming course queries to the course expert."""
(
"[Coordinator] Calling the course expert"
)
result
=
course_agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
return
str
(
result
[
"messages"
]
[
1
]
.
content
)
@
tool
def
ask_math_expert
(
question:
str
)
str
:
"""Delegate numerical calculations and temperature conversion to the math expert."""
(
"[Coordinator] Calling the math expert"
)
result
=
math_agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
return
str
(
result
[
"messages"
]
[
1
]
.
content
)
coordinator
=
create_agent
(
model
=
MODEL
,
tools
=
[
ask_course_expert
,
ask_math_expert
]
,
name
=
"coordinator"
,
system_prompt
=
"You are the coordinator. Call the course expert for course questions and the math expert for calculation questions. For compound tasks, delegate separately and then merge the results."
)
result
=
coordinator.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Recommend an introductory Python course and calculate how many degrees Fahrenheit 25 degrees Celsius equals."
}
]
}
)
(
"Final answer: "
,
result
[
"messages"
]
[
1
]
.
content
)
Possible run results
[协调者] 调用课程专家
[协调者] 调用数学专家
Final Answer:
可以学习 Python3 基础教程,适合编程初学者。
另外,25 摄氏度等于 77 华氏度。
This is the most typical use of multi-agent: the main Agent is not responsible for specific calculations or course queries, but delegates tasks to the corresponding specialized Agents.
**Note:** The model does not guarantee calling the experts in a fixed order, and may call only one of them. Therefore, the above logs and replies are only possible run results.
5. Context isolation of sub-Agents
One of the important values of the Subagents pattern is reducing irrelevant context from entering subtasks.
For example, a user discusses multiple topics in succession in the main Agent:
1. Python 课程
2. Java 基础
3. 数据库优化
4. 温度计算
When the main Agent calls the math expert, it can send only the current math question:
25 摄氏度等于多少华氏度?
The math expert does not need to process all the previous course- and database-related chat history.
This reduces context interference in subtasks.
Stateless by default
If a sub-Agent has no Checkpointer configured and uses independent message input each time, the sub-Agent's conversation history is not automatically preserved between calls.
For example:
result = math_agent.invoke({
"messages": [{"role": "user", "content": question}]
})
Only the current question is sent each time, forming an independent subtask context.
If a sub-Agent needs multi-turn memory, you can configure a Checkpointer additionally, but you must carefully design thread_id, user isolation, and task scope.
**Note:** The main Agent does not automatically obtain all execution messages of the sub-Agent. The tool above returns only the sub-Agent's final answer to the main Agent.
6. The name parameter: Naming an Agent
can be used via create_agent(name=...) Assigns a name to an Agent.
Example
Example
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
name
=
"customer_service"
,
system_prompt
=
"You are a customer service assistant."
)
name Mainly used to identify the Agent graph, helping with debugging, tracing, and embedding in more complex graph structures.
It is recommended to use meaningful names:
course_expert
math_expert
code_reviewer
learning_planner
coordinator
However, note that you cannot assume that after setting name, all AIMessages will automatically carry that name.
In the previous tool-wrapping pattern, if you need to distinguish the source of execution, you can mark it through tool names, logs, and tracing information.
7. Method 2: Router task routing
If the business only needs to determine which domain a user's question belongs to and then hand it to the corresponding Agent, a main Agent with multiple tools may not be necessary.
You can create a Router directly.
Workflow:
用户问题
|
v
任务分类 Router
|
+---- 课程问题 ---- 课程 Agent
|
+---- 数学问题 ---- 数学 Agent
|
+---- 其他问题 ---- 通用 Agent
The Router is mainly responsible for judging the task type, while specialized Agents handle the actual processing.
For systems with clear task types, this structure is usually easier to maintain and test.
Example: Selecting an Agent by task type
Example
from
typing
import
Literal
from
pydantic
import
BaseModel
from
langchain.
chat_models
import
init_chat_model
class
RouteDecision
(
BaseModel
)
:
category: Literal
[
"course"
,
"math"
,
"general"
]
router_model
=
init_chat_model
(
"deepseek:deepseek-flash"
)
router
=
router_model.
with_structured_output
(
RouteDecision
)
general_agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
system_prompt
=
"You are a general-purpose Chinese assistant."
)
def
route_question
(
question:
str
)
str
:
decision
=
router.
invoke
(
f
"Determine whether the question is about course queries, mathematical calculations, or other: {question}"
)
agents
=
{
"course"
: course_agent
,
"math"
: math_agent
,
"general"
: general_agent
}
result
=
agents
[
decision.
category
]
.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
)
return
str
(
result
[
"messages"
]
[
1
]
.
content
)
(
route_question
(
"What introductory courses are there for Python?"
)
)
Here Pydantic is used to restrict the routing result to three values:
course
math
general
Unlike the coordinator pattern, the Router selects only one Agent in this example.
If a question needs to be split into multiple domains for parallel processing, a more complete Router workflow or the Supervisor pattern should be used.
**Note:** The Router's classification result can also be wrong; the classification accuracy should be tested against the actual business. For simple, fixed rules, you can also use Python conditionals directly without calling a model.
8. Method 3: Sequential workflow
Some tasks have a clear execution order, for example:
生成文章
↓
检查技术事实
↓
润色文章
↓
输出最终内容
Such a workflow does not necessarily need the main Agent to dynamically choose the next step.
If the execution order is fixed, you can build a deterministic workflow directly with Python or LangGraph.
Example: Article generation and review
Example
from
langchain.
agents
import
create_agent
writer
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
system_prompt
=
"You are a technical writer. Write a concise and easy-to-understand Python tutorial."
)
reviewer
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
]
,
system_prompt
=
"You are a technical review assistant. Point out questionable points, errors, and facts that need verification in the content; do not assume anything has been verified."
)
def
write_and_review
(
topic:
str
)
:
draft
=
writer.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: f
"Write a tutorial about {topic} within 200 words."
}
]
}
)
article
=
str
(
draft
[
"messages"
]
[
1
]
.
content
)
checked
=
reviewer.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: f
"Please review the following article and list what needs to be modified or verified:\n{article}"
}
]
}
)
return
article
,
str
(
checked
[
"messages"
]
[
1
]
.
content
)
article
,
review
=
write_and_review
(
"Python decorators"
)
(
"Article:"
,
article
)
(
"Review suggestions:"
,
review
)
This example creates two Agents but does not create a coordinator.
Because the task order is already determined:
Writer → Reviewer
This approach is usually more direct than having a coordinator repeatedly decide the next step.
**Note:** The second Agent can only identify potential issues based on its own capabilities and cannot automatically guarantee that technical facts are correct. If fact-checking is needed, provide trusted documents, testing tools, or other data sources.
9. Method 4: Handoffs control transfer
Handoffs differ from Supervisor.
In Supervisor, the main Agent uniformly calls sub-Agents, while Handoffs allows the execution flow to switch to another specialized processing stage based on the current state.
For example, online customer service:
普通客服
↓
判断用户需要退款
↓
切换到退款处理阶段
↓
退款助手处理相关流程
↓
必要时进入人工审批
↓
完成处理
This pattern suits businesses with clear stage transitions, for example:
- General customer service transfers to order customer service.
- Technical support transfers to after-sales processing.
- Issue collection transfers to manual review.
- After document review is completed, enter the execution stage.
Handoffs usually need to maintain the current active stage, for example:
active_agent = "support"
active_agent = "refund"
In LangChain, you can update state through tool calls, and then adjust the current Prompt and tools based on the state.
If multiple independent graph nodes need to hand off control to each other, you can also use LangGraph to build a more explicit Handoff workflow.
**Note:** A Handoff does not mean automatically gaining higher permissions. After entering stages such as refund, payment, or deletion, backend permission checks and necessary manual approval must still be performed.
10. Middleware and multi-agent routing
Middleware can dynamically modify the tool list or system prompt of a model request, but it is not itself a multi-agent system.
For example, adjusting the tools available to the current Agent based on the user's role:
普通用户 → 查询工具
管理员 → 查询工具 + 管理工具
This is dynamic tool selection and does not necessarily require creating two independent Agents.
Example: Filtering tools with wrap_model_call
Example
from
dataclasses
import
dataclass
from
langchain.
agents
.
middleware
import
wrap_model_call
,
ModelRequest
from
langchain.
tools
import
tool
@
dataclass
class
UserContext:
is_admin:
bool
=
False
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query mock courses."""
return
f
"Querying: {keyword}"
@
tool
def
delete_course
(
course_id:
str
)
str
:
"""Mock course deletion."""
return
f
"Simulating course deletion: {course_id}"
@
wrap_model_call
def
select_tools
(
request: ModelRequest
[
UserContext
]
,
handler
)
:
"""Filter the tools visible to the current model based on the trusted role."""
if
request.
runtime
.
context
.
is_admin
:
return
handler
(
request
)
allowed
=
[
t
for
t
in
request.
tools
if
t.
name
!=
"delete_course"
]
return
handler
(
request.
override
(
tools
=
allowed
)
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
search_course
,
delete_course
]
,
context_schema
=
UserContext
,
middleware
=
[
select_tools
]
)
Here, ordinary users will not see in the current model request delete_course the tool definition.
But it must be emphasized thatdynamically hiding tools is not the same as real permission isolation.。
If a tool has real deletion, payment, or management capabilities, the tool execution layer must still verify the trusted user's identity and permissions.
If fully deterministic security isolation is needed, a safer approach is to create different tool sets based on backend permissions, or enforce checks again at the trusted tool execution entry point.
11. Message and memory management in multi-agent systems
A multi-agent system not only needs to manage tasks, but also needs to clarify which context each Agent can access.
There are three common approaches:
| Method | Description | Applicable scenarios |
|---|---|---|
| Pass only the current question | The sub-Agent does not read the full main conversation history | Independent calculations, simple queries |
| Pass necessary context | Extract the historical information needed to complete the subtask | Specialized tasks that depend on user preferences |
| Share a long-term Store | Read the same long-term data with authorization | Learning preferences, long-term user records |
For example, the course expert can obtain:
用户当前学习等级:入门
用户想学习:Python
任务:推荐适合的课程
without needing to obtain all of the user's historical messages.
This is the very important Context Engineering in multi-agent systems.
By allocating context reasonably, irrelevant data can be reduced and the task focus of each specialized Agent improved.
**Note:** Do not pass other users' complete conversation histories, keys, or irrelevant sensitive information into sub-Agents.
12. Executing multiple sub-Agents in parallel
If there are no dependencies between subtasks, they can be executed in parallel.
For example:
课程分析 ────┐
├── 汇总结果
代码检查 ────┘
For two independent Agents, you can use Python's asyncio.gather() for concurrent calls.
Example: Concurrently obtaining answers from two experts
Example
import
asyncio
async
def
consult_experts
(
)
:
questions
=
[
course_agent.
ainvoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Introduce introductory Python courses."
}
]
}
)
,
math_agent.
ainvoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Calculate the Fahrenheit temperature corresponding to 25 degrees Celsius."
}
]
}
)
]
results
=
await asyncio.
gather
(
*questions
)
for
name
,
result
in
zip
(
[
"Course expert"
,
"Math expert"
]
,
results
)
:
(
name
,
":"
,
result
[
"messages"
]
[
1
]
.
content
)
if
name
==
"main"
:
asyncio.
run
(
consult_experts
(
)
)
Here we reuse the two Agents defined earlier.
Two independent tasks can wait concurrently for model and tool execution.
However, concurrency does not guarantee an overall speedup; you also need to consider API rate limits, network conditions, tool resources, and server-side concurrency capacity.
If there are dependencies between tasks, such as obtaining course data before calculating statistics, they should be executed in dependency order.
13. How to choose a multi-agent architecture?
| Business requirement | Recommended approach | Reason |
|---|---|---|
| Only a few tools | Single Agent | Simple structure, low overhead |
| Need to delegate tasks by domain | Subagents | Have a coordinator call experts |
| Process by classifying input | Router | Clear routing responsibilities |
| Fixed task steps | Sequential workflow | Predictable execution process |
| Need to switch the current specialized processing stage | Handoffs | Suitable for multi-stage interactions |
| Much knowledge but tools are not complex | Skills | Load knowledge on demand, avoid creating unnecessary Agents |
| Need precise control over parallelism and state | LangGraph | Able to clearly define nodes and routes |
For most beginners, it is recommended to learn in the following order:
单 Agent + Tools
↓
子 Agent 作为工具
↓
Router 任务分类
↓
Handoffs 状态切换
↓
LangGraph 自定义工作流
Do not design a complex multi-agent network from the start.
14. Production environment considerations
1. Control model call costs
A single user request may first call the coordinator, then call multiple sub-Agents, and finally call the coordinator again to aggregate the results.
This increases token consumption and the number of API requests.
It is recommended to record the call count, response time, and cost of each Agent.
2. Limit task delegation levels
If sub-Agents can continue to call other Agents, circular delegation or repeated execution may occur.
You should limit the maximum execution depth, number of model calls, and timeout.
3. Do not use eval() to execute model-generated code
Strings generated by the model are not trusted code.
For mathematical calculations, use computation tools with explicit parameters, or a safe expression parser with restricted syntax.
4. Sub-Agents should maintain least privilege
The course expert does not need database management permissions, and the math expert does not need the ability to send emails.
Configure each Agent with the minimum tools needed to complete its task.
5. Define clear input/output protocols
In complex systems, it is recommended to use Pydantic structured outputs to define the return fields of sub-Agents, avoiding the parent Agent relying on unstable natural-language format parsing.
6. Handle errors appropriately
When a sub-Agent fails, you can decide, based on the business, to retry, use a backup service, return a partial result, or terminate the task.
But you must not describe an incomplete subtask as a successful execution.
7. Monitor the call chain
When troubleshooting a multi-agent system, you should know not only the final answer but also which Agent, which tool, and at which step the problem occurred.
You can use tracing tools such as LangSmith to observe the execution path.
XV. FAQ
1. Are multiple Agents always stronger than a single Agent?
Not necessarily. Multi-agent suits tasks that require domain isolation, independent context, or complex execution flows, but it increases development and call costs.
2. Can sub-Agents use different models?
Yes. Different Agents can be configured with different models as needed, as long as the corresponding integrations and tool capabilities meet the requirements.
3. Must sub-Agents be registered as tools?
No. You can wrap a sub-Agent as a tool, or directly orchestrate subgraphs or custom nodes through LangGraph.
4. Does the parent Agent automatically obtain the sub-Agent's full history?
No. Tool wrapping usually returns only the specified result of the sub-Agent; when more information is needed, it should be passed explicitly.
5. Do sub-Agents remember previous tasks by default?
Not necessarily. Without a Checkpointer and with new messages passed each time, sub-Agents usually execute independently.
6. What is the purpose of the name parameter?
It is mainly used to identify the Agent graph, assist tracing, and compose graphs; it does not guarantee that all generated messages carry the same name.
7. What is the difference between Router and Supervisor?
The Router is mainly responsible for classification and dispatch; the Supervisor is a coordinator that can repeatedly select sub-Agents across multiple rounds of execution.
8. Can Middleware implement multi-agent?
Middleware can dynamically select tools, models, and prompts, but if it does not actually call multiple Agents, it is usually just a dynamic single-Agent configuration.
9. Can multiple sub-Agents be called in parallel?
Yes. When subtasks are independent of each other, they can be processed in parallel through async concurrency or a LangGraph workflow.
10. How do multiple Agents share long-term memory?
They can access the same long-term data with authorization through a Store or a business database.
11. How to avoid Agents calling each other in a loop?
You can limit delegation depth, call count, and execution time, and check the routing results.
12. When to use LangGraph?
LangGraph is suitable when you need explicit control over execution order, parallel nodes, conditional branches, state sharing, and interrupt recovery.
Summary
Multi-agent is an important architectural pattern in LangChain for implementing complex task collaboration.
This chapter introduces:
Subagents: Wrap specialized Agents as tools.Supervisor: Have the main Agent coordinate multiple sub-Agents.Router: Dispatch to different Agents by task category.Handoffs: Switch specialized processing stages according to state.Skills: Load professional knowledge on demand.- Sequential workflows and parallel tasks.
- Agent naming and context isolation.
- Use Middleware to dynamically select tools.
- Cost, permission, and tracing management of multi-agent systems.
The simplest way to write a multi-agent system:
subagent = create_agent(
model="deepseek:deepseek-flash",
tools=[...]
)
@tool
def ask_subagent(question: str) -> str:
"""向子 Agent 委派任务。"""
result = subagent.invoke({
"messages": [{"role": "user", "content": question}]
})
return result["messages"][-1].content
coordinator = create_agent(
model="deepseek:deepseek-flash",
tools=[ask_subagent]
)
Core principles:The value of multiple agents lies not in their number, but in the division of responsibilities and context management. Agents should only be added when distinct specialized capabilities, task distribution, or execution flows genuinely bring benefits.