Multi-Agent System
Multi-Agent System
This chapter introduces the Multi-Agent System.
Multi-Agent Systems complete complex tasks through the collaboration of multiple Agents.
This is a key technology for building large-scale AI systems, enabling complex functions that a single Agent cannot achieve.
Multi-Agent Architecture Fundamentals
The core challenges of a Multi-Agent System include three aspects.
Task distribution problem: How to reasonably allocate tasks to different Agents.
Communication issues: How to pass information between Agents.
Coordination issues: How to ensure that the actions of multiple Agents are consistent and efficient.
Basic architectural patterns
Hierarchical architecture
The hierarchical architecture uses a tree structure, with a main Agent responsible for scheduling.
The main Agent (Orchestrator) is responsible for task decomposition and result integration.
Subagents are responsible for executing specific tasks.
Original prompt (Chinese, left untranslated)
Orchestrator (调度者)
|
+-- Agent A (专家A)
+-- Agent B (专家B)
+-- Agent C (专家C)
Peer-to-Peer architecture
In a peer-level architecture, all Agent positions are equal and communicate and collaborate directly.
Suitable for scenarios where Agents need frequent peer-to-peer interaction.
Agent A <--> Agent B
| |
v v
Agent C <--> Agent D
Role division and collaboration
An effective multi-Agent system requires clearly defined roles.
Each Agent should have its own expertise and scope of responsibility.
The collaboration mechanism ensures that multiple Agents can coordinate their work.
Common role definitions
Planner: Decomposes complex tasks and formulates execution plans.
Executor: Calls tools and executes specific operations.
Reviewer: Evaluates results and proposes improvement suggestions.
Coordinator: Manages communication and task distribution between Agents.
Code implementation
Basic implementation of multi-Agent system
class
Agent:
"""
Basic Agent class
Each Agent has its own role, tools, and execution logic
"""
def
init
(
self
,
role
,
llm
,
tools
)
:
Agent role name
self
.
role
=
role
Associated language model
self
.
llm
=
llm
List of available tools
self
.
tools
=
tools
def
execute
(
self
,
task
,
context
=
None
)
:
"""
Execute task
:param task: Task description
:param context: Context information
:return: Execution result
"""
Construct prompt
prompt
=
self
.
build_prompt
(
task
,
context
)
Generate response
response
=
self
.
llm
.
generate
(
prompt
)
If tool calling is required
if
response.
needs_tool_call
:
return
self
.
execute_tool
(
response
)
return
response.
content
def
build_prompt
(
self
,
task
,
context
)
:
"""Construct the prompt for the Agent"""
return
f
"Role: {self.role}\nTask: {task}\nContext: {context}"
def
execute_tool
(
self
,
response
)
:
"""Execute tool call"""
tool_name
=
response.
tool_name
tool_input
=
response.
tool_input
Find the corresponding tool from the list of tools
tool
=
self
.
get_tool
(
tool_name
)
Execution tool
return
tool.
execute
(
tool_input
)
class
MultiAgentSystem:
"""
Multi-Agent Collaboration System
Responsible for managing collaboration between multiple Agents
"""
def
init
(
self
,
agents
,
coordinator
)
:
Agent dictionary, key is the character name
self
.
agents
=
{
a.
role
: a
for
a
in
agents
}
Coordinator Agent
self
.
coordinator
=
coordinator
def
solve
(
self
,
task
)
:
"""
Solve complex tasks
By coordinating multiple Agents to complete
"""
Step one: The coordinator analyzes the task and decides which Agents need to participate
plan
=
self
.
coordinator
.
decompose
(
task
)
Step 2: Distribute tasks to the corresponding Agent
results
=
{
}
for
role
,
subtask
in
plan.
subtasks
.
items
(
)
:
Get the Agent for the corresponding character
agent
=
self
.
agents
.
get
(
role
)
if
agent:
Execute subtasks
results
[
role
]
=
agent.
execute
(
subtask
)
Step three: Coordinator integrates results
final_result
=
self
.
coordinator
.
integrate
(
results
)
return
final_result
class
CoordinatorAgent:
Coordinator Agent
def
init
(
self
,
llm
)
:
self
.
llm
=
llm
def
decompose
(
self
,
task
)
:
"""
Decompose the task
Analyze the task, decide which Agents are needed and how to divide the work
"""
prompt
=
f
"""
Analyze the following task, break it down into subtasks, and assign them to the appropriate Agent.
Task: {task}
Please output:
- Which Agents (roles) are needed
- What subtasks each Agent is responsible for
- Dependencies between subtasks
Output format: JSON
"""
response
=
self
.
llm
.
generate
(
prompt
)
return
Plan.
parse
(
response
)
def
integrate
(
self
,
results
)
:
"""
Integrate the results of multiple Agents
"""
prompt
=
f
"""
Integrate the execution results of the following Agents to generate the final answer.
Result list:
{results}
Please integrate and output the final result.
"""
return
self
.
llm
.
generate
(
prompt
)
AutoGen framework
AutoGen is a multi-agent programming framework developed by Microsoft.
It provides a set of simple APIs to build multi-agent conversational systems.
AutoGen greatly simplifies the development complexity of multi-agent systems.
Core Concepts
AssistantAgent: An intelligent assistant Agent capable of calling tools.
UserProxyAgent: Represents user behavior and can execute code and tool calls.
GroupChat: Supports group chat collaboration among multiple Agents.
GroupChatManager: Manages Agent interactions within a group chat.
Code Example
AutoGen Basic Usage
Import the autogen framework
import
autogen
from
autogen
import
AssistantAgent
,
UserProxyAgent
,
GroupChat
,
GroupChatManager
==================== Configure LLM ====================
Create a configuration dictionary
llm_config
=
{
"model"
:
"gpt-4"
,
"api_key"
:
"your-api-key"
,
Read from environment variables when actually using
"temperature"
:
0.7
}
==================== Create a single Agent ====================
Create assistant Agent
assistant
=
AssistantAgent
(
name
=
"assistant"
,
system_message
=
"""
You are a useful Python programming assistant.
You can help users write, debug, and optimize code.
"""
,
llm_config
=
llm_config
)
Create user agent Agent
human_input_mode="NEVER" means no manual input is required
max_consecutive_auto_reply=10 means a maximum of 10 consecutive automatic replies
user_proxy
=
UserProxyAgent
(
name
=
"user_proxy"
,
human_input_mode
=
"NEVER"
,
max_consecutive_auto_reply
=
10
)
==================== Single Agent Conversation ====================
Start conversation
user_proxy.
initiate_chat
(
assistant
,
message
=
"Help me write a quicksort algorithm"
)
==================== Multi-Agent Chat ====================
Create multiple Agents
coder
=
AssistantAgent
(
name
=
"coder"
,
system_message
=
"You are a Python programming expert responsible for writing code."
,
llm_config
=
llm_config
)
reviewer
=
AssistantAgent
(
name
=
"reviewer"
,
system_message
=
"You are a code review expert responsible for reviewing code quality."
,
llm_config
=
llm_config
)
Create group chat
group_chat
=
GroupChat
(
agents
=
[
coder
,
reviewer
]
,
messages
=
[
]
,
max_round
=
10
Maximum 10 turns of conversation
)
Create group chat manager
manager
=
GroupChatManager
(
groupchat
=
group_chat
,
llm_config
=
llm_config
)
Start group chat
user_proxy.
initiate_chat
(
manager
,
message
=
"Write a quicksort algorithm and review the code"
)
More complex AutoGen examples
AutoGen tool calling
import
autogen
from
autogen
import
AssistantAgent
,
UserProxyAgent
Define the list of tools
These tools will be registered to the Agent's tool list
tools
=
[
{
"name"
:
"calculate"
,
"description"
:
"Perform mathematical calculations"
,
"parameters"
:
{
"type"
:
"object"
,
"properties"
:
{
"expression"
:
{
"type"
:
"string"
,
"description"
:
"The mathematical expression to be calculated, such as '2+3*5'"
}
}
,
"required"
:
[
"expression"
]
}
}
,
{
"name"
:
"search_web"
,
"description"
:
"Search web information"
,
"parameters"
:
{
"type"
:
"object"
,
"properties"
:
{
"query"
:
{
"type"
:
"string"
,
"description"
:
"Search keywords"
}
}
,
"required"
:
[
"query"
]
}
}
]
Create an Agent with tool calling capabilities
assistant
=
AssistantAgent
(
name
=
"assistant"
,
system_message
=
"""
You are a helpful assistant.
When you need to perform calculations or look up information, you can call relevant tools.
"""
,
llm_config
=
{
"model"
:
"gpt-4"
,
"api_key"
:
"your-api-key"
}
,
tools
=
tools
Register tool
)
Create user agent
user_proxy
=
UserProxyAgent
(
name
=
"user_proxy"
,
human_input_mode
=
"NEVER"
)
Start the conversation, and the Agent will automatically call tools
user_proxy.
initiate_chat
(
assistant
,
message
=
"What is (15 + 25) * 2?"
)
Reply example:
The Agent might reply:
"Let me calculate: (15 + 25) * 2 = 40 * 2 = 80"
Or directly call the calculate tool to get the result
A2A and MCP protocols
Multi-Agent systems require standardized communication protocols.
A2A and MCP are two important protocol standards.
A2A (Agent-to-Agent) protocol
The A2A protocol defines the standard format for communication between Agents.
It supports agent discovery, task collaboration, and state synchronization.
Core features
Agent Discovery: Agents can discover the capabilities and services of other Agents.
Task Collaboration: Multiple Agents can collaborate to complete complex tasks.
State Synchronization: Agents can synchronize state information among themselves.
MCP (Model Context Protocol) protocol
MCP is an open standard protocol.
It enables AI models to securely connect with external tools and data sources.
MCP is the standard protocol for tool access, similar to the function of a USB interface.
Core Components
Host: The host environment where AI applications run.
Client: The client that establishes a connection with the MCP server.
Server: The server that provides tools and resources.
MCP Tool Definition Example
MCP Tool Definition
{
"name": "filesystem",
"description": "File system operation tool",
"version": "1.0.0",
"tools": [
{
"name": "read_file",
"description": "Read file content",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "File path, required"
},
"encoding": {
"type": "string",
"description": "File encoding, optional, defaults to utf-8"
}
},
"required": ["path"]
}
},
{
"name": "write_file",
"description": "Write file content",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "File path, required"
},
"content": {
"type": "string",
"description": "File content, required"
}
},
"required": ["path", "content"]
}
},
{
"name": "list_directory",
"description": "List directory contents",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path"
}
}
}
}
],
"resources": [
{
"uri": "file://config",
"description": "Configuration file"
}
]
}
Note: A2A and MCP solve different problems. A2A solves communication issues between Agents, while MCP solves connection issues between Agents and external tools. Both can be used together to build a complete multi-Agent system.
Master-Slave Agent Mode
The master-slave mode is a classic multi-Agent architecture pattern.
The main Agent (Orchestrator) is responsible for task decomposition and result integration.
The Subagent is responsible for executing specific tasks.
Applicable Scenarios
Scenarios where tasks can be clearly decomposed into independent subtasks.
Scenarios where Agents with different professional skills need to collaborate to complete the task.
Complex workflows that require central coordination and control.
Code Implementation
Main-Sub Agent Mode Implementation
class
OrchestratorAgent:
"""
Editor Agent (Main Agent)
Responsible for task decomposition, assignment, and result integration
"""
def
init
(
self
,
llm
,
subagents
)
:
Language model
self
.
llm
=
llm
From the Agent dictionary
self
.
subagents
=
{
a.
role
: a
for
a
in
subagents
}
def
handle_request
(
self
,
request
)
:
"""
Process user request
Complete orchestration process
"""
==================== Analysis Phase ====================
Analyze the request and decide whether multiple Agents need to collaborate
plan
=
self
.
llm
.
plan
(
request
)
if
len
(
plan.
subtasks
)
==
1
:
Single task, directly dispatched to the corresponding Agent
target_role
=
plan.
target_role
return
self
.
subagents
[
target_role
]
.
execute
(
plan.
subtasks
[
0
]
)
==================== Multi-Agent Collaboration Phase ====================
Create task queue
task_queue
=
self
.
create_task_queue
(
plan.
subtasks
)
Store the completed results
results
=
[
]
Process the loop until all tasks are completed
while
task_queue:
Get tasks that can be executed in parallel
parallel_tasks
=
self
.
get_parallel_tasks
(
task_queue
)
Parallel execution
parallel_results
=
self
.
execute_in_parallel
(
parallel_tasks
)
results.
extend
(
parallel_results
)
Update task queue
Process dependencies, remove completed tasks, and add new tasks
task_queue
=
self
.
update_queue
(
task_queue
,
parallel_results
)
==================== Integration Phase ====================
Integrate all results
return
self
.
integrate_results
(
results
)
def
create_task_queue
(
self
,
subtasks
)
:
"""Create task queue"""
return
TaskQueue
(
subtasks
)
def
get_parallel_tasks
(
self
,
task_queue
)
:
"""
Get tasks that can be executed in parallel
Exclude tasks with dependencies
"""
ready_tasks
=
[
]
for
task
in
task_queue.
tasks
:
Check if all task dependencies are met
if
all
(
dep
in
task_queue.
completed
for
dep
in
task.
dependencies
)
:
ready_tasks.
append
(
task
)
return
ready_tasks
def
execute_in_parallel
(
self
,
tasks
)
:
"""Execute multiple tasks in parallel"""
import
concurrent.
futures
results
=
[
]
with
concurrent.
futures
.
ThreadPoolExecutor
(
)
as
executor:
Submit all tasks
future_to_task
=
{
executor.
submit
(
self
.
execute_task
,
task
)
: task
for
task
in
tasks
}
Collect results
for
future
in
concurrent.
futures
.
as_completed
(
future_to_task
)
:
task
=
future_to_task
[
future
]
try
:
result
=
future.
result
(
)
results.
append
(
result
)
except
Exception
as
e:
results.
append
(
TaskResult
(
task
=
task
,
error
=
str
(
e
)
)
)
return
results
def
execute_task
(
self
,
task
)
:
"""Execute a single task"""
agent
=
self
.
subagents
.
get
(
task.
role
)
if
not
agent:
return
TaskResult
(
task
=
task
,
error
=
f
"Unknown role: {task.role}"
)
return
agent.
execute
(
task.
description
)
def
update_queue
(
self
,
task_queue
,
completed_results
)
:
"Update task queue"
Mark completed tasks as finished
for
result
in
completed_results:
task_queue.
completed
.
add
(
result.
task
.
id
)
Remove completed tasks
task_queue.
tasks
=
[
t
for
t
in
task_queue.
tasks
if
t.
id
not
in
task_queue.
completed
]
return
task_queue
def
integrate_results
(
self
,
results
)
:
"""
Integrate the results of multiple Agents
Generate the final answer
"""
prompt
=
f
"""
Integrate the execution results of the following Agents to generate the final answer.
Results list:
{results}
Please integrate them into one complete and coherent answer.
"""
return
self
.
llm
.
generate
(
prompt
)
class
Subagent:
"""From Agent base class"""
def
init
(
self
,
role
,
llm
,
tools
=
None
)
:
self
.
role
=
role
self
.
llm
=
llm
self
.
tools
=
tools
or
[
]
def
execute
(
self
,
task
)
:
"The specific logic for executing the task"
raise
NotImplementedError
Advantages and disadvantages of master-slave mode
| Advantages | Disadvantages |
|---|---|
| Clear structure, easy to understand and implement | The main Agent becomes a single point of failure |
| Centralized coordination, easy to control | The main Agent may become a performance bottleneck |
| Suitable for tasks with clear hierarchy | Lower flexibility, difficult to adjust dynamically |
| Convenient for debugging, can track each sub-task | Not suitable for scenarios with frequent peer-to-peer interactions |
Chapter Summary
This chapter introduces the core concepts and implementation methods of multi-agent systems.
Multi-Agent Architecture Basics introduces two basic models: hierarchical and flat architecture.
Role Division and Collaboration improves system efficiency through clear role definitions.
AutoGen framework provides a programming framework to simplify multi-agent development.
A2A and MCP protocols are standard protocols for Agent communication and tool access.
Master-Slave Agent mode is suitable for complex tasks with a clear hierarchical structure.
Choosing the appropriate multi-Agent architecture depends on the specific scenario.
For simple scenarios, a single Agent is sufficient.
For complex scenarios, the appropriate architecture pattern needs to be selected based on the task characteristics.