知识模块
🤖 Agent 知识模块
十、多 Agent 协作
AutoGen 框架

AutoGen 框架

AutoGen 是微软研究院开发的多智能体对话框架,通过自然语言对话实现 Agent 间的协作。它强调"对话式协作"和"代码执行",非常适合代码开发、复杂推理和问题解决场景。


一、核心原理

1.1 AutoGen 设计哲学

AutoGen 的核心思想是将 Agent 间的协作建模为"对话":

┌─────────────────────────────────────────────────────────────┐
│                    AutoGen 设计哲学                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   传统协作:                                                │
│   ┌─────────────────────────────────────────────────────┐  │
│   │                                                      │  │
│   │   Agent A ──→ [结构化消息] ──→ Agent B              │  │
│   │                                                      │  │
│   │   问题:消息格式固定,灵活性差                        │  │
│   │                                                      │  │
│   └─────────────────────────────────────────────────────┘  │
│                                                             │
│   AutoGen 对话式协作:                                      │
│   ┌─────────────────────────────────────────────────────┐  │
│   │                                                      │  │
│   │   Agent A: "我来帮你分析这个问题..."                │  │
│   │   Agent B: "好的,我执行了代码,结果是..."          │  │
│   │   Agent A: "根据结果,我建议..."                    │  │
│   │   Agent B: "同意,我来修改代码..."                  │  │
│   │                                                      │  │
│   │   优势:自然语言交互,灵活性高,协作流畅             │  │
│   │                                                      │  │
│   └─────────────────────────────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 核心概念

概念英文描述示例
ConversableAgent可对话代理能够发送和接收消息的 AgentAssistantAgent、UserProxyAgent
AssistantAgent助手代理提供 AI 建议和解决方案代码生成、问题分析
UserProxyAgent用户代理代表用户执行操作执行代码、人工确认
GroupChat群组对话多 Agent 群聊模式团队讨论
Conversation对话Agent 间的消息交换请求-响应循环

1.3 架构图

┌─────────────────────────────────────────────────────────────┐
│                    AutoGen 架构图                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   ┌─────────────────────────────────────────────────────┐  │
│   │                  Conversation                        │  │
│   │                    Manager                          │  │
│   └──────────────────────┬──────────────────────────────┘  │
│                          │                                  │
│                          ↓                                  │
│   ┌─────────────────────────────────────────────────────┐  │
│   │                  Message Queue                       │  │
│   │                                                      │  │
│   │   [msg1] → [msg2] → [msg3] → [msg4] → ...          │  │
│   │                                                      │  │
│   └──────────────────────┬──────────────────────────────┘  │
│                          │                                  │
│         ┌────────────────┼────────────────┐               │
│         ↓                ↓                ↓               │
│   ┌───────────┐    ┌───────────┐    ┌───────────┐        │
│   │Assistant  │    │UserProxy  │    │GroupChat  │        │
│   │Agent      │    │Agent      │    │Manager    │        │
│   │           │    │           │    │           │        │
│   │ • LLM驱动 │    │ • 代码执行│    │ • 多Agent │        │
│   │ • 建议生成│    │ • 人工确认│    │ • 路由分发│        │
│   │ • 问题分析│    │ • 结果反馈│    │ • 协调管理│        │
│   └───────────┘    └───────────┘    └───────────┘        │
│         │                │                │               │
│         └────────────────┴────────────────┘               │
│                          │                                  │
│                          ↓                                  │
│   ┌─────────────────────────────────────────────────────┐  │
│   │                   Execution                          │  │
│   │                    Environment                       │  │
│   │                                                      │  │
│   │   ┌─────────┐  ┌─────────┐  ┌─────────┐            │  │
│   │   │ Python  │  │ Docker  │  │ Custom  │            │  │
│   │   │ REPL    │  │ Sandbox │  │ Executor│            │  │
│   │   └─────────┘  └─────────┘  └─────────┘            │  │
│   │                                                      │  │
│   └─────────────────────────────────────────────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

二、核心组件详解

2.1 ConversableAgent

所有 Agent 的基类,提供核心对话能力:

from autogen import ConversableAgent
 
# 创建基础对话 Agent
agent = ConversableAgent(
    name="assistant",                    # Agent 名称
    system_message="你是一个有帮助的助手", # 系统提示
    llm_config={                         # LLM 配置
        "model": "gpt-4",
        "api_key": "your-api-key"
    },
    human_input_mode="NEVER",             # 人工输入模式
    max_consecutive_auto_reply=10,        # 最大自动回复次数
    code_execution_config=False,          # 代码执行配置
)
 
# 发送消息
agent.send(
    message="你好,请帮我分析这个问题",
    recipient=other_agent
)

2.2 AssistantAgent

专门用于提供 AI 建议的 Agent:

from autogen import AssistantAgent
 
# 创建助手 Agent
assistant = AssistantAgent(
    name="coding_assistant",
    system_message="""你是一个专业的编程助手。
    
    你可以:
    1. 编写和修改代码
    2. 解释代码逻辑
    3. 调试和修复问题
    4. 优化代码性能
    
    当需要执行代码时,请使用 Python 代码块格式。
    """,
    llm_config={
        "model": "gpt-4",
        "temperature": 0.7,
    },
)

2.3 UserProxyAgent

代表用户执行操作的 Agent:

from autogen import UserProxyAgent
 
# 创建用户代理
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="TERMINATE",         # 在终止时请求人工输入
    max_consecutive_auto_reply=10,
    code_execution_config={
        "work_dir": "coding",              # 工作目录
        "use_docker": False,               # 是否使用 Docker
    },
)
 
# 发起对话
user_proxy.initiate_chat(
    assistant,
    message="请帮我写一个 Python 函数,计算斐波那契数列"
)

2.4 GroupChat

多 Agent 群聊模式:

from autogen import GroupChat, GroupChatManager
 
# 创建多个 Agent
planner = AssistantAgent(
    name="planner",
    system_message="你负责规划任务步骤",
)
 
coder = AssistantAgent(
    name="coder",
    system_message="你负责编写代码",
)
 
reviewer = AssistantAgent(
    name="reviewer",
    system_message="你负责代码审查",
)
 
# 创建群组对话
group_chat = GroupChat(
    agents=[user_proxy, planner, coder, reviewer],
    messages=[],
    max_round=20,                    # 最大轮数
    speaker_selection_method="round_robin",  # 发言选择方式
)
 
# 创建群聊管理器
manager = GroupChatManager(
    groupchat=group_chat,
    llm_config={"model": "gpt-4"}
)
 
# 发起群聊
user_proxy.initiate_chat(
    manager,
    message="开发一个简单的 TODO 应用"
)

三、代码实现

3.1 基础示例:代码助手

"""
AutoGen 基础示例:代码助手
展示 AssistantAgent 和 UserProxyAgent 的协作
"""
 
import autogen
 
# 配置 LLM
llm_config = {
    "model": "gpt-4",
    "api_key": "your-api-key",
    "temperature": 0.7,
}
 
# 创建助手 Agent
assistant = autogen.AssistantAgent(
    name="coding_assistant",
    system_message="""
    你是一个专业的 Python 编程助手。
    
    你的职责:
    1. 理解用户需求
    2. 编写高质量代码
    3. 解释代码逻辑
    4. 调试和修复问题
    
    代码格式要求:
    - 使用 ```python 代码块
    - 包含必要的注释
    - 遵循 PEP 8 规范
    """,
    llm_config=llm_config,
)
 
# 创建用户代理
user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="TERMINATE",  # 任务完成后等待用户确认
    max_consecutive_auto_reply=10,
    code_execution_config={
        "work_dir": "./workspace",
        "use_docker": False,
    },
)
 
# 发起对话
def solve_coding_task(task: str):
    """解决编程任务"""
    user_proxy.initiate_chat(
        assistant,
        message=task
    )
 
if __name__ == "__main__":
    solve_coding_task("""
    请编写一个 Python 函数,实现以下功能:
    1. 读取 CSV 文件
    2. 按指定列分组
    3. 计算每组的统计信息(均值、中位数、标准差)
    4. 输出结果到新的 CSV 文件
    
    请提供完整的代码和示例用法。
    """)

3.2 进阶示例:多 Agent 协作

"""
AutoGen 进阶示例:多 Agent 协作开发
展示 GroupChat 多智能体协作
"""
 
import autogen
 
# LLM 配置
llm_config = {
    "model": "gpt-4",
    "api_key": "your-api-key",
    "temperature": 0.7,
}
 
# ==================== 创建专业 Agent ====================
 
# 产品经理 Agent
product_manager = autogen.AssistantAgent(
    name="product_manager",
    system_message="""
    你是产品经理,负责:
    1. 分析需求
    2. 定义功能规格
    3. 编写用户故事
    
    输出格式:
    - 功能清单
    - 优先级排序
    - 验收标准
    """,
    llm_config=llm_config,
)
 
# 架构师 Agent
architect = autogen.AssistantAgent(
    name="architect",
    system_message="""
    你是系统架构师,负责:
    1. 技术选型
    2. 系统设计
    3. 接口定义
    
    输出格式:
    - 架构图描述
    - 技术栈选择
    - API 设计
    """,
    llm_config=llm_config,
)
 
# 开发者 Agent
developer = autogen.AssistantAgent(
    name="developer",
    system_message="""
    你是全栈开发者,负责:
    1. 编写代码
    2. 单元测试
    3. 代码优化
    
    代码要求:
    - 清晰的注释
    - 遵循最佳实践
    - 包含测试用例
    """,
    llm_config=llm_config,
)
 
# 测试工程师 Agent
tester = autogen.AssistantAgent(
    name="tester",
    system_message="""
    你是测试工程师,负责:
    1. 编写测试用例
    2. 执行测试
    3. 报告缺陷
    
    测试范围:
    - 功能测试
    - 边界测试
    - 异常测试
    """,
    llm_config=llm_config,
)
 
# 用户代理
user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="TERMINATE",
    code_execution_config={
        "work_dir": "./dev_workspace",
        "use_docker": False,
    },
)
 
# ==================== 创建群组对话 ====================
 
group_chat = autogen.GroupChat(
    agents=[user_proxy, product_manager, architect, developer, tester],
    messages=[],
    max_round=30,
    speaker_selection_method="auto",  # 自动选择下一个发言者
)
 
manager = autogen.GroupChatManager(
    groupchat=group_chat,
    llm_config=llm_config,
)
 
# ==================== 执行协作 ====================
 
def develop_feature(requirement: str):
    """协作开发功能"""
    user_proxy.initiate_chat(
        manager,
        message=f"""
        新功能需求:
        {requirement}
        
        请按照以下流程协作:
        1. 产品经理分析需求
        2. 架构师设计方案
        3. 开发者实现代码
        4. 测试工程师验证
        
        完成后请总结交付物。
        """
    )
 
if __name__ == "__main__":
    develop_feature("""
    开发一个用户注册登录系统:
    - 用户名/邮箱注册
    - 密码加密存储
    - JWT Token 认证
    - 登录状态保持
    """)

3.3 代码执行环境

"""
AutoGen 代码执行配置
展示不同的代码执行方式
"""
 
import autogen
 
# 方式1: 本地 Python 执行
local_executor_config = {
    "work_dir": "./workspace",
    "use_docker": False,
    "timeout": 60,
}
 
# 方式2: Docker 沙箱执行(推荐生产环境)
docker_executor_config = {
    "work_dir": "./workspace",
    "use_docker": True,
    "timeout": 120,
    # Docker 镜像
    "docker_image": "python:3.10-slim",
}
 
# 方式3: 禁用代码执行
no_execution_config = False
 
# 创建支持代码执行的 Agent
coding_agent = autogen.UserProxyAgent(
    name="coding_agent",
    human_input_mode="NEVER",
    code_execution_config=docker_executor_config,
    max_consecutive_auto_reply=20,
)
 
# 自定义代码执行器
class CustomCodeExecutor:
    """自定义代码执行器"""
    
    def __init__(self, work_dir: str):
        self.work_dir = work_dir
    
    def execute(self, code: str, language: str = "python") -> dict:
        """执行代码并返回结果"""
        import subprocess
        import tempfile
        import os
        
        # 创建临时文件
        with tempfile.NamedTemporaryFile(
            mode='w',
            suffix=f'.{language}',
            dir=self.work_dir,
            delete=False
        ) as f:
            f.write(code)
            temp_file = f.name
        
        try:
            # 执行代码
            result = subprocess.run(
                ["python", temp_file],
                capture_output=True,
                text=True,
                timeout=60,
                cwd=self.work_dir
            )
            
            return {
                "success": result.returncode == 0,
                "output": result.stdout,
                "error": result.stderr
            }
        finally:
            # 清理临时文件
            os.unlink(temp_file)

四、对话模式

4.1 双 Agent 对话

┌─────────────────────────────────────────────────────────────┐
│                    双 Agent 对话模式                         │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   UserProxyAgent ←────────────────→ AssistantAgent          │
│        │                                  │                 │
│        │  1. 发送任务请求                  │                 │
│        │ ─────────────────────────────→  │                 │
│        │                                  │                 │
│        │  2. 返回解决方案(含代码)        │                 │
│        │ ←─────────────────────────────  │                 │
│        │                                  │                 │
│        │  3. 执行代码,返回结果           │                 │
│        │ ─────────────────────────────→  │                 │
│        │                                  │                 │
│        │  4. 根据结果优化                 │                 │
│        │ ←─────────────────────────────  │                 │
│        │                                  │                 │
│        │  ... 循环直到任务完成            │                 │
│        │                                  │                 │
│        │  N. 最终答案                     │                 │
│        │ ←─────────────────────────────  │                 │
│        │                                  │                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

4.2 群组对话模式

┌─────────────────────────────────────────────────────────────┐
│                    群组对话模式                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│                    ┌─────────────┐                         │
│                    │   Manager   │                         │
│                    │   (协调者)  │                         │
│                    └──────┬──────┘                         │
│                           │                                │
│                           ↓                                │
│   ┌───────────────────────────────────────────────────┐   │
│   │               Speaker Selection                    │   │
│   │              (选择下一个发言者)                    │   │
│   └───────────────────────┬───────────────────────────┘   │
│                           │                                │
│         ┌─────────────────┼─────────────────┐             │
│         ↓                 ↓                 ↓             │
│   ┌───────────┐    ┌───────────┐    ┌───────────┐        │
│   │  Agent A  │    │  Agent B  │    │  Agent C  │        │
│   │           │    │           │    │           │        │
│   │  发言 ────┼───→ 接收 ────┼───→ 响应     │        │
│   │           │    │           │    │           │        │
│   └───────────┘    └───────────┘    └───────────┘        │
│         │                 │                 │             │
│         └─────────────────┴─────────────────┘             │
│                           │                                │
│                           ↓                                │
│                    ┌─────────────┐                         │
│                    │ 共享消息池  │                         │
│                    └─────────────┘                         │
│                                                             │
│   发言者选择方式:                                          │
│   - round_robin: 轮流发言                                   │
│   - auto: 自动选择最合适的发言者                            │
│   - random: 随机选择                                        │
│   - manual: 手动指定                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

五、适用场景

5.1 最佳适用场景

场景描述配置建议
代码开发代码生成、调试、优化AssistantAgent + UserProxyAgent
数据分析数据处理、可视化启用代码执行
复杂推理多步骤问题解决GroupChat 多专家协作
研究探索开放性问题讨论多 Agent 自由对话

5.2 与 CrewAI 对比

对比项AutoGenCrewAI
协作模式对话式角色扮演式
灵活性
代码执行内置支持需配置工具
流程控制动态协商预定义流程
适用场景开发、研究内容创作、工作流

5.3 不适用场景

场景原因推荐替代
固定流程任务对话开销大CrewAI
实时响应对话轮次多单 Agent
大规模部署资源消耗大自定义架构

六、优缺点分析

6.1 优点

优点描述
灵活对话自然语言交互,协作流畅
代码执行内置安全的代码执行环境
微软支持企业级支持,持续更新
扩展性强易于自定义 Agent 和工具
多模态支持支持文本、图像、代码

6.2 缺点

缺点描述缓解方案
对话开销多轮对话消耗 Token设置 max_round 限制
不确定性对话路径不可预测使用 GroupChatManager
调试困难对话历史复杂启用详细日志

七、面试问答

Q1: AutoGen 的核心概念是什么?

回答: AutoGen 的核心概念包括:

  • ConversableAgent:可对话代理基类
  • AssistantAgent:AI 助手,提供建议
  • UserProxyAgent:用户代理,执行操作
  • GroupChat:多 Agent 群聊模式

Q2: AutoGen 如何实现代码执行?

回答

  1. 本地执行:在本地 Python 环境执行
  2. Docker 执行:在 Docker 容器中安全执行
  3. 自定义执行器:实现自定义的执行逻辑
  4. 执行结果反馈:将执行结果返回给对话

Q3: AutoGen 和 CrewAI 如何选择?

回答

场景推荐
代码开发、调试AutoGen
内容创作流水线CrewAI
需要灵活对话AutoGen
流程固定可控CrewAI

Q4: AutoGen 如何处理 Agent 间的冲突?

回答

  1. 对话协商:Agent 通过对话解决分歧
  2. Manager 决策:GroupChatManager 进行仲裁
  3. 人工干预:设置 human_input_mode 请求人工决策

八、小结

概念一句话总结面试关键词
AutoGen微软的对话式多智能体协作框架ConversableAgent、GroupChat
对话模式双 Agent、群组对话initiate_chat、GroupChatManager
代码执行内置安全代码执行环境Docker 沙箱、本地执行
适用场景代码开发、复杂推理灵活对话、协作探索

一句话总结:AutoGen 通过自然语言对话实现 Agent 间的灵活协作,内置代码执行能力,非常适合代码开发和复杂问题解决场景。


最后更新:2026年3月19日