Doramagic 项目包 · 项目说明书

autogen 项目

生成时间:2026-05-31 16:29:44 UTC

AutoGen项目简介

AutoGen是微软开发的一个开源编程框架,旨在构建多代理(Multi-Agent)对话和协作应用程序。该项目支持创建能够相互通信、协作完成复杂任务的AI代理系统。AutoGen被设计为高度可扩展的,允许开发者根据需求定制代理、工具和工作流程。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 多语言支持

继续阅读本节完整说明和来源证据。

章节 架构设计原则

继续阅读本节完整说明和来源证据。

章节 订阅机制

继续阅读本节完整说明和来源证据。

项目概述

AutoGen是微软开发的一个开源编程框架,旨在构建多代理(Multi-Agent)对话和协作应用程序。该项目支持创建能够相互通信、协作完成复杂任务的AI代理系统。AutoGen被设计为高度可扩展的,允许开发者根据需求定制代理、工具和工作流程。

AutoGen目前处于维护模式(Maintenance Mode),主要接收错误修复、安全补丁和文档改进方面的贡献。新功能开发已转移至Microsoft Agent Framework

资料来源:README.md:1-50

核心架构

多语言支持

AutoGen采用跨平台架构,同时支持Python和.NET两大生态系统:

语言包/SDK用途
Pythonautogen-core核心运行时
Pythonautogen-agentchat代理聊天框架
Pythonautogen-ext扩展组件库
PythonautogenstudioWeb UI界面
.NETMicrosoft.AutoGen核心运行时
.NETAutoGen.Core基础组件
.NETAutoGen.SourceGenerator代码生成工具

架构设计原则

AutoGen基于发布-订阅(Publish-Subscribe)消息模型运行。代理通过TopicId标识主题进行消息广播,每个主题由类型(Type)和源(Source)组成。

graph TD
    A[Agent A] -->|TopicId| B[Message Broker]
    C[Agent B] -->|TopicId| B
    D[Agent C] -->|TopicId| B
    B -->|订阅匹配| A
    B -->|订阅匹配| C
    B -->|订阅匹配| D

资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs:1-30

订阅机制

AutoGen提供两种主要的订阅类型:

订阅类型说明
TypeSubscription精确类型匹配,每个源创建独立代理实例
TypePrefixSubscription前缀匹配,支持通配符模式
// 精确匹配示例
var subscription = new TypeSubscription("t1", "a1");
// 匹配: type="t1", source="s1" → 由 "a1" 代理处理
// 匹配: type="t1", source="s2" → 由 "a1" 代理处理

// 前缀匹配示例
var prefixSubscription = new TypePrefixSubscription("t1", "a1");
// 匹配: type="t1", type="t1SUFFIX" 等

资料来源:dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cs:1-40

核心组件

Python生态

#### autogen-core

autogen-core是AutoGen的底层运行时,提供代理生命周期管理、消息传递和任务调度等核心功能。

支持的模型家族:

class ModelFamily:
    GPT_5 = "gpt-5"
    GPT_41 = "gpt-41"
    GPT_45 = "gpt-45"
    GPT_4O = "gpt-4o"
    O1 = "o1"
    O3 = "o3"
    O4 = "o4"
    GPT_4 = "gpt-4"
    GPT_35 = "gpt-35"
    R1 = "r1"
    GEMINI_1_5_FLASH = "gemini-1.5-flash"
    GEMINI_1_5_PRO = "gemini-1.5-pro"
    GEMINI_2_0_FLASH = "gemini-2.0-flash"
    GEMINI_2_5_PRO = "gemini-2.5-pro"

资料来源:python/packages/autogen-core/src/autogen_core/models/_model_client.py:1-50

#### autogen-agentchat

autogen-agentchat是高级代理对话框架,提供会话式代理、群聊(GroupChat)、工具调用等高级功能。

主要代理类型:

代理类型功能描述
AssistantAgent通用助手代理
CodeExecutorAgent代码执行代理
FileSurfer本地文件预览代理
WebSurfer网页浏览代理

#### autogen-ext

autogen-ext包含AutoGen项目维护的各种扩展组件,包括预构建的代理、工具和运行时集成:

  • MagenticOne代理:用于复杂多代理工作流
  • 代码执行器:支持本地和远程代码执行
  • 文件代理:本地文件系统浏览
  • 网页代理:Web内容浏览和搜索

资料来源:python/packages/autogen-ext/README.md:1-20

.NET生态

#### AutoGen.SourceGenerator

AutoGen的.NET包包含一个源代码生成器,简化类型安全的函数定义创建:

<PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="AutoGen.SourceGenerator" />
</ItemGroup>

使用示例:

using AutoGen;

public partial class MyFunctions
{
    [Function]
    public Task<string> AddAsync(int a, int b)
    {
        return Task.FromResult($"{a} + {b} = {a + b}");
    }
}

资料来源:dotnet/src/AutoGen.SourceGenerator/README.md:1-60

代理系统

代理架构

AutoGen中的代理是基于组件(Component)模式设计的,支持配置化实例化:

class FileSurferConfig(BaseModel):
    """FileSurfer代理配置"""
    name: str
    model_client: ComponentModel
    description: str | None = None

class FileSurfer(BaseChatAgent, Component[FileSurferConfig]):
    """本地文件预览代理"""
    ...

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py:1-50

工具定义

每个工具通过ToolSchema定义,包含函数名称、描述和参数模式:

TOOL_SUMMARIZE_PAGE: ToolSchema = _load_tool({
    "type": "function",
    "function": {
        "name": "summarize_page",
        "description": "使用AI总结整个页面内容",
        "parameters": {
            "type": "object",
            "properties": {
                "reasoning": {
                    "type": "string",
                    "description": REASONING_TOOL_PROMPT,
                },
            },
            "required": ["reasoning"],
        },
    }
})

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_tool_definitions.py:1-80

代码执行流程

sequenceDiagram
    participant Agent as 代理
    participant Model as 模型
    participant Executor as 代码执行器
    participant Context as 上下文
    
    Agent->>Model: 生成响应
    Model-->>Agent: 返回内容
    Agent->>Agent: 提取代码块
    Agent->>Executor: 执行代码
    Executor-->>Agent: 执行结果
    Agent->>Context: 更新上下文
    Context-->>Agent: 确认更新

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:1-50

多代理协作

群聊(GroupChat)

GroupChat允许多个代理在同一会话中协作:

public class GroupChatOptions(string groupTopicType, string outputTopicType)
{
    public string GroupChatTopicType { get; }
    public string OutputTopicType { get; }
    
    public ITerminationCondition? TerminationCondition { get; set; }
    public int? MaxTurns { get; set; }
    public Dictionary<string, GroupParticipant> Participants { get; }
}

资料来源:dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.cs:1-30

任务分配

Apprentice类提供任务中心的内存管理功能:

class ApprenticeConfig(TypedDict, total=False):
    name_of_agent_or_team: str
    disable_prefix_caching: bool
    MemoryController: "MemoryControllerConfig"

资料来源:python/packages/autogen-ext/src/autogen_ext/experimental/task_centric_memory/utils/apprentice.py:1-40

部署模式

本地部署

本地部署适用于开发测试环境,代理直接在同一进程中运行:

from autogen_ext.agents import FileSurfer

agent = FileSurfer(
    name="file_surfer",
    model_client=model_client
)

分布式部署

分布式运行时允许跨进程、跨机器的代理协作。当前使用asyncio.Queue进行任务管理。

⚠️ 已知限制:当前分布式运行时不支持任务持久化,服务重启后任务会丢失。
资料来源:Issue #5327

安全考虑

沙箱执行

LocalCommandLineCodeExecutor直接将LLM生成的代码写入磁盘并以子进程执行,无沙箱隔离、无文件系统限制或网络隔离。

⚠️ 安全警告:在生产环境中使用Docker容器执行代码。
资料来源:Issue #7462

威胁类型

社区已识别以下安全威胁:

威胁类型描述
提示注入工具输出中的恶意提示
数据泄露代理输出中的敏感信息
内存污染代理记忆被恶意篡改

社区正在考虑集成OWASP Agent Memory Guard等安全工具。

资料来源:Issue #7671

安全建议

  1. 使用Docker容器执行不受信任的代码
  2. 实施代理输出过滤
  3. 限制文件系统访问权限
  4. 监控代理行为和输出

AutoGen Studio

AutoGen Studio是基于AutoGen框架构建的Web用户界面,用于快速原型设计多代理工作流:

graph LR
    A[用户界面] --> B[代理定义]
    A --> C[技能配置]
    A --> D[工作流编排]
    B --> E[运行时]
    C --> E
    D --> E
⚠️ 重要提示:AutoGen Studio是研究原型,不适合生产环境使用
资料来源:python/packages/autogen-studio/README.md:1-30

入门指南

安装

Python:

# 核心包
pip install autogen-core autogen-agentchat

# 扩展组件
pip install "autogen-ext[all]"

# Studio UI
pip install autogenstudio

.NET:

dotnet add package Microsoft.AutoGen.Core

快速开始

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import TextMessage
from autogen_core.models import OpenAIChatCompletionClient

# 创建模型客户端
model_client = OpenAIChatCompletionClient(model="gpt-4o")

# 创建代理
assistant = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message="你是一个有帮助的助手。"
)

# 运行对话
result = await assistant.run(task="帮我写一个Hello World程序")

版本信息

最新版本

分支版本主要更新
Pythonv0.7.5修复Bedrock流式响应、Redis线性内存支持
Pythonv0.7.4修复Redis反序列化错误
Pythonv0.7.3扩展Pydantic模型能力

资料来源:Release Notes

相关资源

资源类型链接
官方文档https://microsoft.github.io/autogen
GitHub仓库https://github.com/microsoft/autogen
社区讨论https://github.com/microsoft/autogen/discussions
Discordhttps://aka.ms/autogen-discord
文档https://microsoft.github.io/autogen/stable/user-guide/extensions-user-guide/index.html

常见问题

Q: AutoGen适合生产环境吗? A: 核心框架可用于生产,但AutoGen Studio和研究原型组件不适合生产部署。

Q: 支持哪些语言模型? A: AutoGen支持多种模型家族,包括GPT系列、Claude系列、Gemini系列、O系列等。

Q: 如何贡献代码? A: 请参考CONTRIBUTING.md。由于AutoGen处于维护模式,新功能开发请考虑Microsoft Agent Framework

Q: GroupChat中的轮次限制有bug吗? A: 已知问题:当代理数量为3、最大轮次为4时,第三个代理可能不会被选中。资料来源:Issue #7670

资料来源:README.md:1-50

快速入门指南

AutoGen 是一个由微软开发的开源编程框架,用于构建多智能体(Multi-Agent)应用程序。它支持多个 AI 代理之间的对话协作,允许开发者创建复杂的自动化工作流。AutoGen 提供 Python 和 .NET 两种实现版本,本指南主要聚焦于 Python 版本的快速上手。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 系统要求

继续阅读本节完整说明和来源证据。

章节 安装方式

继续阅读本节完整说明和来源证据。

章节 环境配置

继续阅读本节完整说明和来源证据。

概述

AutoGen 是一个由微软开发的开源编程框架,用于构建多智能体(Multi-Agent)应用程序。它支持多个 AI 代理之间的对话协作,允许开发者创建复杂的自动化工作流。AutoGen 提供 Python 和 .NET 两种实现版本,本指南主要聚焦于 Python 版本的快速上手。

本指南涵盖从环境安装、基础概念到实际应用的全流程,帮助开发者快速掌握 AutoGen 的核心用法。

环境要求与安装

系统要求

要求说明
Python 版本3.10 及以上
操作系统Windows、macOS、Linux
网络需要访问 LLM API(如 OpenAI、Azure OpenAI 等)

安装方式

AutoGen 提供两种安装级别,开发者可根据需求选择:

# 基础安装(仅核心功能)
pip install autogen-agentchat

# 扩展安装(包含更多工具和功能)
pip install autogen-ext

# 完整安装
pip install autogen-agentchat autogen-ext

资料来源:python/docs/src/user-guide/agentchat-user-guide/installation.md

环境配置

安装完成后,需要配置 LLM 连接信息。AutoGen 支持多种模型服务:

from autogen_agentchat import UserProxyAgent, AssistantAgent

# 配置模型
config = {
    "model": "gpt-4",
    "api_key": "your-api-key"
}

核心概念

智能体(Agent)

AutoGen 中的智能体是能够执行特定任务的基本单元。主要类型包括:

智能体类型说明使用场景
AssistantAgentAI 助手代理,执行 LLM 调用通用对话和任务处理
UserProxyAgent用户代理,处理用户输入用户交互入口
CodeExecutorAgent代码执行代理代码生成和执行
WebSurfer网页浏览代理网络搜索和信息获取

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/__init__.py

话题订阅模型

AutoGen 采用发布-订阅模式管理消息流转。核心组件包括:

  • TopicId:标识消息主题,包含 TypeSource 两个属性,符合 CloudEvents 规范
  • 订阅类型:支持精确匹配(TypeSubscription)和前缀匹配(TypePrefixSubscription)
graph TD
    A[发布者] -->|TopicId| B[消息路由]
    B --> C{匹配订阅}
    C -->|TypeSubscription| D[精确匹配]
    C -->|TypePrefixSubscription| E[前缀匹配]
    D --> F[对应Agent处理]
    E --> F

资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs 资料来源:dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cs

工具(Tools)

智能体可以通过工具扩展能力。AutoGen 提供了标准化的工具定义接口:

from autogen_core.tools import BaseTool, ToolSchema

# 工具定义示例
TOOL_SUMMARIZE_PAGE: ToolSchema = {
    "type": "function",
    "function": {
        "name": "summarize_page",
        "description": "使用 AI 总结整个页面内容",
        "parameters": {
            "type": "object",
            "properties": {
                "reasoning": {
                    "type": "string",
                    "description": "推理过程说明"
                }
            },
            "required": ["reasoning"]
        }
    }
}

资料来源:python/packages/autogen-core/src/autogen_core/tools/_base.py 资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_tool_definitions.py

基础使用流程

步骤一:创建智能体

from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.messages import TextMessage

# 创建助手代理
assistant = AssistantAgent(
    name="assistant",
    system_message="你是一个有帮助的AI助手"
)

# 创建用户代理
user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="ALWAYS"  # 始终需要用户确认
)

步骤二:定义对话任务

# 创建任务描述
task = "请帮我写一个Python函数,计算斐波那契数列的前n项"

步骤三:运行对话

# 启动对话流
result = await assistant.run(task=task, agents=[user_proxy])

# 获取结果
for message in result.messages:
    print(f"{message.source}: {message.content}")

步骤四:处理代码执行

当智能体生成代码时,CodeExecutorAgent 会自动执行并返回结果:

# 代码执行流程
async def execute_code_workflow():
    # 1. 生成代码
    code_blocks = extract_markdown_code_blocks(model_result.content)
    
    # 2. 执行代码
    execution_result = await executor.execute_code_block(code_blocks)
    
    # 3. 返回执行结果
    return execution_result.output

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py

群组对话(GroupChat)

AutoGen 支持多个智能体之间的群组对话,实现更复杂的协作模式。

基本配置

from autogen_agentchat.groupchat import GroupChat, GroupChatManager

# 定义参与者
participants = [
    GroupParticipant(topic_type="A", description="助手A"),
    GroupParticipant(topic_type="B", description="助手B"),
    GroupParticipant(topic_type="C", description="助手C")
]

# 创建群组聊天配置
group_chat_options = GroupChatOptions(
    group_topic_type="group_chat",
    output_topic_type="output"
)
group_chat_options.Participants = {p.TopicType: p for p in participants}
group_chat_options.MaxTurns = 10

群组聊天执行流程

graph TD
    A[用户发起任务] --> B[GroupChat管理器]
    B --> C{选择发言者}
    C -->|Round Robin| D[按顺序轮询]
    C -->|自定义选择| E[基于策略选择]
    D --> F[当前Agent处理]
    E --> F
    F --> G[检查终止条件]
    G -->|未终止| C
    G -->|已终止| H[输出结果]

注意事项

已知问题GroupChat 的轮询模式在 max_round 为偶数时存在逻辑缺陷,可能导致最后一个智能体无法参与对话。建议开发者使用奇数值的 max_round,或关注官方更新。

资料来源:python/docs/src/user-guide/agentchat-user-guide/tutorial/index.md 资料来源:dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.cs

安全考量

代码执行安全

LocalCommandLineCodeExecutor 会将 LLM 生成的代码直接写入磁盘并执行,没有沙箱隔离。生产环境中使用时:

  1. 限制可执行的操作:仅允许安全的命令和路径
  2. 使用资源限制:配置 CPU、内存限制
  3. 考虑替代方案:使用 Docker 容器或虚拟机隔离执行环境
# 推荐的安全配置示例
from autogen_ext.code_executors import DockerCommandLineCodeExecutor

executor = DockerCommandLineCodeExecutor(
    image="python:3.10-slim",
    timeout=30,
    workspace_dir="/secure/workspace"
)
安全公告:社区已报告 LocalCommandLineCodeExecutor 执行 LLM 生成代码时缺少沙箱保护的问题。详情参见 Issue #7462

提示注入防护

AutoGen 智能体在处理外部输入(如工具输出)时可能面临提示注入风险。建议:

  • 对工具返回内容进行过滤和验证
  • 考虑使用 OWASP Agent Memory Guard 等安全工具

高级功能

MCP 工具集成

AutoGen 支持 Model Context Protocol (MCP) 工具扩展:

from autogen_ext.tools import MCP

# 连接 MCP 工具服务器
mcp_tools = MCP.from_server("path/to/server")

记忆与状态管理

对于需要持久化状态的应用,AutoGen 支持 Redis 等后端存储:

# Redis 记忆配置
memory = RedisMemory(
    connection_string="redis://localhost:6379",
    ttl=3600  # 过期时间(秒)
)
注意:Redis 当前不支持流式响应,如需此功能请关注后续版本更新。

资料来源:python/docs/src/user-guide/agentchat-user-guide/quickstart.ipynb

常见问题排查

问题可能原因解决方案
消息未路由到正确的智能体TopicId 配置错误检查 Type 和 Source 属性匹配
非英文环境报错编码问题使用 encoding='utf-8'
GroupChat 智能体跳过max_round 为偶数使用奇数值或关注官方修复
Token 统计不准确缓存 Token 未正确计算确认模型支持 usage 数据

下一步

资料来源:python/docs/src/user-guide/agentchat-user-guide/installation.md

分层架构设计

AutoGen 采用多语言、多层次的模块化架构设计,分别在 Python 和 .NET 平台实现了核心运行时、代理框架和扩展组件。本页面详细阐述 AutoGen 的分层架构设计理念、各层职责及其交互关系。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 技术栈分层

继续阅读本节完整说明和来源证据。

章节 架构层次图

继续阅读本节完整说明和来源证据。

章节 消息传递机制

继续阅读本节完整说明和来源证据。

架构概览

AutoGen 的分层架构遵循清晰的分层原则,将系统划分为核心运行时层、代理框架层、扩展组件层和工具层。这种分层设计使得各模块可以独立演进,同时保持整体系统的内聚性和低耦合性。

技术栈分层

层级Python 实现.NET 实现主要职责
核心运行时autogen_coreMicrosoft.AutoGen.Core消息传递、订阅管理、组件注册
代理框架autogen_agentchatMicrosoft.AutoGen.AgentChat代理定义、对话管理、团队协作
扩展组件autogen_extAutoGen.SemanticKernel专用代理、工具集、运行时扩展
工具层autogen_core.toolsN/A工具定义、Schema 生成、执行

架构层次图

graph TB
    subgraph "工具层 Tools"
        T1[BaseTool]
        T2[ToolSchema]
    end
    
    subgraph "扩展组件层 autogen_ext"
        E1[WebSurfer]
        E2[FileSurfer]
        E3[CodeExecutor]
    end
    
    subgraph "代理框架层 autogen_agentchat"
        A1[BaseChatAgent]
        A2[CodeExecutorAgent]
        A3[GroupChat]
    end
    
    subgraph "核心运行时层 autogen_core"
        R1[AgentRuntime]
        R2[Subscription]
        R3[Message]
        R4[ModelClient]
    end
    
    T1 --> A1
    T2 --> A2
    E1 --> A1
    E2 --> A1
    A1 --> R1
    A2 --> R1
    A3 --> R1
    R2 --> R1
    R3 --> R1
    R4 --> A1

核心运行时层

核心运行时层是整个 AutoGen 架构的基础,负责管理代理生命周期、消息路由和订阅分发。该层在 Python 和 .NET 中有对应的实现,保持了跨语言的一致性。

消息传递机制

消息是代理间通信的基本单元。AutoGen 定义了丰富的消息类型体系:

# 资料来源:python/packages/autogen-core/src/autogen_core/models/_model_client.py:1-35
class RequestUsage:
    """Token 使用统计"""
    prompt_tokens: int
    completion_tokens: int

消息类型包括:

  • UserMessage: 用户输入消息
  • AssistantMessage: 助手响应消息
  • SystemMessage: 系统配置消息
  • FunctionCall: 函数调用消息

订阅与主题分发

AutoGen 采用发布-订阅模式进行消息路由,支持基于主题类型的精确匹配和前缀匹配:

// 资料来源:dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cs:1-30
public class TypeSubscription : ISubscriptionDefinition
{
    // 订阅匹配规则:
    // - 精确类型匹配:TopicId.type == _topicType
    // - 源映射:TopicId.source 作为代理键
}
订阅类型匹配方式适用场景
TypeSubscription精确类型匹配一对一的消息路由
PrefixSubscription前缀匹配通配符模式的消息路由
GuidSubscriptionGUID精确匹配特定会话的消息路由

代理注册表

运行时维护一个代理注册表,管理代理类型、主题和订阅关系:

// 资料来源:dotnet/src/Microsoft.AutoGen/RuntimeGateway.Grpc/Abstractions/AgentsRegistryState.cs:1-30
public class AgentsRegistryState
{
    public ConcurrentDictionary<string, HashSet<string>> AgentsToTopicsMap { get; set; }
    public ConcurrentDictionary<string, HashSet<string>> TopicToAgentTypesMap { get; set; }
    public string Etag { get; set; }  // 乐观并发控制
}

代理框架层

代理框架层建立在核心运行时之上,提供高级的代理抽象和对话管理能力。

基础代理接口

# 资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:50-80
class BaseChatAgent(ABC):
    """代理基类,定义核心接口"""
    
    async def on_messages(self, messages, cancellation_token):
        """处理消息并生成响应"""
        pass
    
    async def on_reset(self, cancellation_token=None):
        """重置代理状态"""
        pass

代理执行流程

代码执行代理展示了典型的代理执行流程:

sequenceDiagram
    participant User as 用户消息
    participant Agent as CodeExecutorAgent
    participant Model as ChatCompletionClient
    participant Executor as CodeExecutor
    participant Context as ModelContext

    User->>Agent: 发送消息
    Agent->>Model: 请求 LLM 推理
    Model-->>Agent: 返回推理结果
    Agent->>Agent: 提取代码块
    Agent->>Executor: 执行代码
    Executor-->>Agent: 返回执行结果
    Agent->>Context: 更新上下文
    Agent-->>User: 返回响应

对话消息结构

# 资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/messages.py:200-250
class StructureMessageConfig(BaseModel):
    """结构化输出的声明式配置"""
    json_schema: Dict[str, Any]
    format_string: Optional[str] = None
    content_model_name: str

工具层

工具层为代理提供调用外部功能的能力,是 AutoGen 扩展性的重要体现。

工具定义基类

# 资料来源:python/packages/autogen-core/src/autogen_core/tools/_base.py:20-45
class BaseTool(ABC, Tool, Generic[ArgsT, ReturnT], ComponentBase[BaseModel]):
    component_type = "tool"

    def __init__(
        self,
        args_type: Type[ArgsT],
        return_type: Type[ReturnT],
        name: str,
        description: str,
        strict: bool = False,
    ) -> None:
        self._args_type = args_type
        self._return_type = normalize_annotated_type(return_type)
        self._name = name
        self._description = description
        self._strict = strict  # 严格模式:所有参数必须提供

工具 Schema 生成

工具通过 Pydantic 模型自动生成 OpenAI 兼容的 Schema:

配置项说明默认值
strict严格模式,禁用默认参数False
required必需参数列表自动推断
properties参数属性定义从模型推断

内置工具示例

# 资料来源:python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_markdown_file_browser.py:30-60
class MarkdownFileBrowser:
    """基于 Markdown 的文件浏览器"""
    
    TOOL_OPEN_PATH: ToolSchema  # 打开文件/目录
    TOOL_PAGE_UP: ToolSchema    # 向上翻页
    TOOL_PAGE_DOWN: ToolSchema # 向下翻页
    TOOL_FIND_ON_PAGE: ToolSchema  # 页面内搜索

扩展组件层

扩展组件层包含预构建的专用代理和工具集,可以直接集成到应用程序中。

WebSurfer 代理

# 资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_tool_definitions.py:20-50
TOOL_NAVIGATE_URL: ToolSchema = {
    "name": "navigate_url",
    "description": "导航到指定的 URL 地址",
    "parameters": {
        "type": "object",
        "properties": {
            "reasoning": {"type": "string"},
            "url": {"type": "string"}
        }
    }
}

FileSurfer 代理

# 资料来源:python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py:30-60
class FileSurfer(BaseChatAgent):
    """本地文件预览代理"""
    
    def __init__(
        self,
        name: str,
        model_client: ChatCompletionClient,
        description: str | None = None,
        base_path: str | None = None,
    ):
        # base_path 限制文件访问范围
        self._browser = MarkdownFileBrowser(base_path=base_path)

组件架构

graph LR
    subgraph "组件注册表"
        Registry[ComponentRegistry]
    end
    
    subgraph "组件类型"
        T1[Tool]
        T2[Agent]
        T3[Memory]
    end
    
    Registry --> T1
    Registry --> T2
    Registry --> T3
    
    T1 -->|"component_type='tool'"| Registry
    T2 -->|"component_type='agent'"| Registry

跨语言架构一致性

AutoGen 在 Python 和 .NET 平台保持了架构的一致性:

主题模型对比

概念Python.NET
主题标识TopicIdTopicId
主题类型type: strType: string
消息源source: strSource: string
// 资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs:10-25
public struct TopicId
{
    public string Type { get; }  // CloudEvents 规范
    public string Source { get; }  // 事件来源标识
    public const string DefaultSource = ...;
}

代理运行时对应

Python.NET功能
AgentRuntimeAgentRuntime运行时管理
SingleThreadedAgentRuntimeN/A单线程执行
SubscriptionISubscriptionDefinition订阅管理

安全性考量

分层架构中的安全性设计:

层级安全措施实现位置
工具层路径验证MarkdownFileBrowser._validate_path()
代理层沙箱执行LocalCommandLineCodeExecutor
运行时消息验证Schema 校验

社区反馈:社区关注 LocalCommandLineCodeExecutor 的安全性问题(Issue #7462),建议在执行前进行代码审查和沙箱隔离。

扩展指南

创建自定义工具

from autogen_core.tools import BaseTool
from pydantic import BaseModel

class MyToolInput(BaseModel):
    query: str

class MyToolOutput(BaseModel):
    result: str

class MyTool(BaseTool[MyToolInput, MyToolOutput]):
    def __init__(self):
        super().__init__(
            args_type=MyToolInput,
            return_type=MyToolOutput,
            name="my_tool",
            description="自定义工具描述"
        )
    
    async def _run(self, input: MyToolInput) -> MyToolOutput:
        return MyToolOutput(result=f"处理: {input.query}")

创建自定义代理

class MyAgent(BaseChatAgent):
    async def on_messages(self, messages, cancellation_token):
        # 处理消息逻辑
        return Response(...)

总结

AutoGen 的分层架构设计体现了以下核心原则:

  1. 清晰的分层边界:核心运行时、代理框架、扩展组件和工具层各司其职
  2. 跨语言一致性:Python 和 .NET 实现保持架构对齐
  3. 组件化设计:通过 Component 注册表实现动态发现和扩展
  4. 订阅路由:基于主题的发布-订阅模式支持灵活的消息路由
  5. 安全隔离:通过路径验证、沙箱执行等机制保障安全性

这种架构设计使得 AutoGen 能够支持从简单单代理到复杂多代理系统的各种用例,同时保持代码的可维护性和可扩展性。

来源:https://github.com/microsoft/autogen / 项目说明书

运行时模型与消息机制

AutoGen 的运行时模型与消息机制是支撑多代理协作的核心基础设施。它基于发布-订阅(Publish-Subscribe)模式,通过 CloudEvents 规范实现事件化消息传递,支持分布式部署和横向扩展。运行时负责管理代理生命周期、消息路由、订阅匹配以及并发任务调度。

章节 相关页面

继续阅读本节完整说明和来源证据。

概述

AutoGen 的运行时模型与消息机制是支撑多代理协作的核心基础设施。它基于发布-订阅(Publish-Subscribe)模式,通过 CloudEvents 规范实现事件化消息传递,支持分布式部署和横向扩展。运行时负责管理代理生命周期、消息路由、订阅匹配以及并发任务调度。

该机制的核心设计目标包括:

  • 解耦通信:代理之间无需直接引用,通过主题(Topic)进行间接通信
  • 分布式支持:支持跨进程、跨节点的代理协作
  • 可扩展性:通过订阅机制动态扩展消息路由规则
  • 类型安全:使用强类型的主题标识确保消息路由的准确性

来源:https://github.com/microsoft/autogen / 项目说明书

分布式运行时

AutoGen 的分布式运行时(Distributed Runtime)是一个跨进程、跨节点的智能体运行时架构,基于 gRPC 通信协议实现。该运行时允许将智能体部署在多个进程中或不同机器上运行,通过远程过程调用(RPC)实现智能体之间的消息传递和任务协调。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 核心组件

继续阅读本节完整说明和来源证据。

章节 系统架构图

继续阅读本节完整说明和来源证据。

章节 发布-订阅消息模型

继续阅读本节完整说明和来源证据。

概述

AutoGen 的分布式运行时(Distributed Runtime)是一个跨进程、跨节点的智能体运行时架构,基于 gRPC 通信协议实现。该运行时允许将智能体部署在多个进程中或不同机器上运行,通过远程过程调用(RPC)实现智能体之间的消息传递和任务协调。

分布式运行时解决了单进程智能体系统的扩展性限制,使得大规模多智能体协作成为可能。在微软的分布式 Agent Runtime 中,任务目前通过 asyncio 的 Queue 进行管理,但存在服务重启后任务不持久化的问题(参见 Issue #5327)。

架构设计

核心组件

AutoGen 分布式运行时包含以下核心组件:

组件语言职责
WorkerRuntimePython工作节点运行时,执行具体的智能体任务
WorkerRuntimeHostPython工作节点宿主,管理 WorkerRuntime 的生命周期
GrpcAgentRuntime.NET.NET 平台的 gRPC 代理运行时
TopicId.NET主题标识符,用于发布-订阅消息模型

系统架构图

graph TD
    subgraph "客户端进程"
        A[客户端代码] --> B[WorkerRuntimeHost]
        B --> C[WorkerRuntime]
    end
    
    subgraph "远程运行时"
        D[GrpcAgentRuntime] --> E[Agent 实例]
        D --> F[Agent 实例]
    end
    
    C -->|gRPC 通信| D
    
    subgraph "消息路由"
        D --> G[Topic Router]
        G -->|发布| H[消息队列]
        H -->|订阅| E
        H -->|订阅| F
    end
    
    style D fill:#e1f5fe
    style B fill:#fff3e0
    style G fill:#f3e5f5

发布-订阅消息模型

分布式运行时采用 CloudEvents 规范定义的主题标识符(TopicId)来实现消息路由:

  • Type: 事件类型,必须匹配模式 ^[\w\-\.\:\=]+$
  • Source: 事件发生的上下文标识

资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs

public struct TopicId
{
    public string Type { get; }
    public string Source { get; }
    public const string DefaultSource = ...;
}

Python 分布式运行时

WorkerRuntime

WorkerRuntime 是 Python 端的分布式工作节点实现,负责在远程进程中执行智能体逻辑。

主要功能:

  • 注册本地智能体到远程运行时
  • 处理远程方法调用
  • 管理消息队列和事件循环
  • 支持流式响应和取消操作

WorkerRuntimeHost

WorkerRuntimeHost 作为 WorkerRuntime 的宿主进程,提供网络绑定和连接管理功能。

关键配置参数:

参数类型说明
hoststr绑定的主机地址
portint监听端口号
runtimeWorkerRuntime关联的工作运行时实例

gRPC 服务定义

gRPC 通信层使用 Protocol Buffers 定义服务接口:

service AgentWorker {
    rpc CreateAgent(CreateAgentRequest) returns (CreateAgentResponse);
    rpc DeleteAgent(DeleteAgentRequest) returns (DeleteAgentResponse);
    rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
    rpc StreamedSendMessage(StreamedSendMessageRequest) returns (stream StreamingMessage);
}

资料来源:python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/protos/agent_worker_pb2_grpc.py

.NET 分布式运行时

GrpcAgentRuntime

GrpcAgentRuntime 是 .NET 平台的分布式运行时实现,提供了与 Python 端兼容的 gRPC 通信能力。

public class GrpcAgentRuntime : IAgentRuntime
{
    // 基于 CloudEvents 规范的消息处理
    // 支持主题路由和发布-订阅模式
}

核心特性:

  • 实现了 IAgentRuntime 接口
  • 支持 CloudEvents 格式的消息序列化
  • 提供主题(Topic)级别的消息路由
  • 支持与 Python WorkerRuntime 互操作

资料来源:dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentRuntime.cs

使用示例

Python 分布式组聊天示例

以下示例展示如何使用分布式运行时构建多智能体协作系统:

# 资料来源:python/samples/core_distributed-group-chat/_agents.py

from autogen_ext.runtimes.grpc import WorkerRuntime, WorkerRuntimeHost
from autogen_core import CancellationToken

# 创建工作节点运行时
runtime = WorkerRuntime(host="localhost", port=50051)

# 启动宿主进程
host = WorkerRuntimeHost(runtime)
await host.start()

分布式组聊天配置

# 资料来源:python/samples/core_distributed-group-chat/README.md

from autogen_agentchat.teams import RoundRobinGroupChat

# 配置分布式组聊天
team = RoundRobinGroupChat(
    participants=[agent_a, agent_b, agent_c],
    max_turns=10
)

消息路由机制

TopicId 路由

分布式运行时通过 TopicId 实现消息的发布-订阅路由:

graph LR
    A[发布者] -->|Publish Message| B[Topic Router]
    B --> C[Topic: "agent.chat"]
    B --> D[Topic: "agent.result"]
    
    C --> E[订阅者 A]
    C --> F[订阅者 B]
    D --> G[订阅者 C]

消息生命周期

阶段说明
发布消息携带 TopicId 发布到运行时
路由Topic Router 根据 Type 和 Source 路由消息
投递消息放入订阅者的接收队列
处理订阅者异步处理消息

已知限制与问题

Issue #5327: 任务持久化

当前分布式运行时使用 asyncio Queue 管理任务,存在以下问题:

目前使用 asyncio 的 Queue 管理任务,这种方法无法在服务重启后持久化任务。

问题描述:

  • 服务重启后,所有排队中的任务会丢失
  • 无法保证任务的可靠执行
  • 不支持故障恢复后的任务继续

建议方案:

  • 引入持久化队列(如 Redis、RabbitMQ)
  • 支持任务状态持久化
  • 实现任务恢复机制

Issue #4501: 消息路由问题

从 Python 发布的消息可能被路由到智能体后产生 "Unhandled Message" 或 "Unknown Payload" 错误。

症状:

INFO:autogen_core:Put message in receive queue
error: "Unhandled Message"
error: "Unknown Payload"

安全考虑

分布式运行时涉及跨进程通信,需要注意以下安全事项:

  1. 网络隔离: 确保 gRPC 端口只在可信网络范围内暴露
  2. 消息验证: 对传入消息进行有效性验证
  3. 身份认证: 生产环境应配置 TLS 双向认证
  4. 沙箱隔离: 远程执行的代码应使用沙箱机制限制权限

相关文档

总结

AutoGen 分布式运行时通过 gRPC 提供了跨进程、跨节点的多智能体协作能力。其核心组件包括 Python 端的 WorkerRuntime/WorkerRuntimeHost 和 .NET 端的 GrpcAgentRuntime,通过 TopicId 实现了基于 CloudEvents 规范的发布-订阅消息路由。

当前实现的主要限制是任务不持久化,建议在生产环境中结合外部消息队列实现可靠的任务管理。

资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs

多智能体编排

多智能体编排(Multi-Agent Orchestration)是 AutoGen 框架的核心功能,用于协调多个 AI 代理(Agent)之间的协作、任务分配和消息传递。通过编排机制,开发者可以构建复杂的自动化工作流,实现代理间的动态交接、团队协作和层次化任务处理。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 团队架构概览

继续阅读本节完整说明和来源证据。

章节 代理组件

继续阅读本节完整说明和来源证据。

章节 团队配置

继续阅读本节完整说明和来源证据。

概述

AutoGen 的多智能体编排系统建立在以下核心概念之上:

概念说明
Agent(代理)独立执行特定任务的基本单元,可以是对话代理、工具代理或自定义代理
Team(团队)由多个代理组成的协作单元,支持多种编排策略
Handoff(交接)代理之间转移控制权的机制,允许动态路由
Message(消息)代理间通信的基本载体
Termination(终止条件)控制团队何时结束执行

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py:1-100

核心架构

团队架构概览

graph TD
    A[用户任务] --> B[Team 团队]
    B --> C[Agent A]
    B --> D[Agent B]
    B --> E[Agent C]
    C --> F[执行任务]
    D --> G[交接给其他代理]
    G --> C
    G --> E
    F --> H[终止条件检查]
    H --> I{是否终止?}
    I -->|否| B
    I -->|是| J[返回结果]

AutoGen 支持多种团队类型,包括:

  • RoundRobinGroupChat:轮询组聊,所有代理按顺序发言
  • SelectorGroupChat:选择器组聊,基于 LLM 选择下一个发言者
  • Team:基础团队,支持层次化任务分配

代理组件

classDiagram
    class BaseChatAgent {
        +name: str
        +description: str
        +run(task: str): Response
        +run_stream(task: str): Stream
    }
    
    class CodeExecutorAgent {
        +execute_code_block()
        +_extract_markdown_code_blocks()
    }
    
    class FileSurfer {
        +打开和预览本地文件
        +文件导航工具
    }
    
    class MultimodalWebSurfer {
        +浏览器自动化
        +网页交互工具
    }
    
    BaseChatAgent <|-- CodeExecutorAgent
    BaseChatAgent <|-- FileSurfer
    BaseChatAgent <|-- MultimodalWebSurfer

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:1-50

团队管理

团队配置

AutoGen 的团队配置通过 Team 类进行管理,支持以下关键参数:

参数类型说明
participantsList[BaseChatAgent]团队参与者列表
termination_conditionTerminationCondition终止条件
max_turnsint最大轮次限制
message_processorMessageProcessor消息处理器
team = RoundRobinGroupChat(
    participants=[writer_agent, critique_agent],
    termination_condition=TextMentionTermination("TERMINATE"),
    max_turns=10,
)

await team.run(task="创建儿童故事")

资料来源:python/packages/autogen-core/src/autogen_core/_agent_proxy.py:1-50

消息流处理

graph LR
    A[UserMessage] --> B[MessageProcessor]
    B --> C{Handoff?}
    C -->|是| D[执行交接]
    C -->|否| E[普通消息处理]
    D --> F[目标代理]
    E --> G[当前代理]
    G --> H[Response]
    F --> H

消息处理器负责:

  1. 解析传入的用户消息
  2. 检查是否触发交接条件
  3. 将消息路由到适当的代理
  4. 收集并聚合代理响应

代理交接机制

交接概述

交接(Handoff)机制允许一个代理主动将控制权转移给另一个代理。这是实现复杂工作流的关键功能,支持:

  • 顺序交接:按预定顺序转移控制权
  • 条件交接:基于特定条件选择交接目标
  • 动态交接:根据运行时状态动态决定交接目标

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/base/_handoff.py:1-80

Handoff 类结构

@dataclass
class Handoff:
    name: str
    description: str
    target: Union[BaseChatAgent, str]
    
@dataclass
class HandoffMessage(OM):
    source: str
    target: str
    handoff: Handoff
    context: Optional[str] = None

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/base/_handoff.py:50-100

交接流程

sequenceDiagram
    participant U as 用户
    participant A as Agent A
    participant H as Handoff Handler
    participant B as Agent B
    
    U->>A: 发送任务
    A->>A: 执行任务
    A->>H: 发起交接请求
    H->>B: 传递控制权
    B->>B: 执行新任务
    B->>U: 返回结果

工具集成

代理作为工具

AutoGen 支持将代理本身作为工具使用,实现代理间的调用和协作:

# 创建代理工具
agent_as_tool = AgentTool(agent=assistant_agent)

# 在其他代理中使用
coding_agent = CodingAgent(
    tools=[agent_as_tool, ...]
)

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/tools/_agent.py:1-100

工具架构

graph TD
    A[BaseTool] --> B[T]
    A --> C[FunctionCall]
    B --> D[ArgsT]
    B --> E[ReturnT]
    
    class BaseTool {
        +schema: ToolSchema
        +name: str
        +description: str
        +strict: bool
    }

工具必须实现以下方法:

  • schema:返回工具的 JSON Schema 定义
  • name:工具的唯一名称
  • description:工具功能描述
  • strict:是否启用严格模式(所有参数必须提供)

资料来源:python/packages/autogen-core/src/autogen_core/tools/_base.py:1-80

团队工具

TeamTool 功能

团队工具允许代理在运行时创建和管理子团队:

team_tool = TeamTool(team=team)

# 代理可以调用此工具来创建子团队处理子任务

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/tools/_team.py:1-100

层次化任务处理

graph TD
    A[主任务] --> B[主团队]
    B --> C[Agent 1]
    B --> D[Agent 2]
    D --> E[子任务]
    E --> F[子团队]
    F --> G[子Agent 1]
    F --> H[子Agent 2]
    G --> I[执行完成]
    H --> I
    I --> J[结果汇总]
    J --> K[主团队继续]

消息与订阅

TopicId 机制

在分布式环境中,AutoGen 使用 TopicId 进行消息路由:

public struct TopicId
{
    public string Type { get; }   // 事件类型
    public string Source { get; } // 事件来源
    
    public static TopicId FromStr(string topicId) 
        => new TopicId(topicId.ToKVPair("Type", "Source"));
}

TopicId 遵循 CloudEvents 规范,格式为 type/source

资料来源:dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs:1-50

订阅管理

graph LR
    A[Agent] -->|订阅| B[TopicId]
    C[事件发布] -->|路由| B
    B -->|分发| A

TypeSubscription 用于将 TopicId 映射到具体的 AgentId:

public class TypeSubscription
{
    public bool Matches(TopicId topic);
    public AgentId MapToAgent(TopicId topic);
}

资料来源:dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cs:1-80

终止条件

内置终止条件

终止条件说明
TextMentionTermination当消息包含特定文本时终止
MaxMessageTermination当消息数量达到上限时终止
TokenUsageTermination当 Token 使用量达到阈值时终止
StopMessageTermination当收到停止消息时终止

自定义终止条件

class CustomTermination(BaseTerminationCondition):
    async def should_terminate(self, messages: List[ChatMessage]) -> bool:
        # 自定义终止逻辑
        return len(messages) >= self.max_messages

流式处理

Streaming Handoffs

AutoGen 支持流式交接,实现实时消息传递:

async for chunk in agent.run_stream(task):
    if isinstance(chunk, HandoffRequestEvent):
        # 处理交接请求
        await handle_handoff(chunk)

资料来源:python/samples/core_streaming_handoffs_fastapi/README.md:1-50

社区相关讨论

已知问题

Issue描述状态
#7670GroupChat 轮询模式下,当 max_round 为偶数时,最后一个代理可能被跳过待修复
#5327分布式运行时的任务持久化需求功能请求

安全考虑

使用多智能体编排时需注意:

  • LocalCommandLineCodeExecutor:执行 LLM 生成的代码时缺少沙箱保护
  • 提示注入:代理间的消息传递可能包含恶意内容
  • 工具调用:代理调用外部工具时需验证输入

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py:100-200

最佳实践

1. 团队设计原则

  • 单一职责:每个代理应专注于特定任务
  • 清晰的交接协议:明确定义代理间的交接条件和数据传递
  • 适当的终止条件:设置合理的终止条件避免无限循环

2. 性能优化

  • 使用 max_turns 限制最大执行轮次
  • 合理配置消息缓存大小
  • 对频繁使用的工具启用流式处理

3. 错误处理

try:
    result = await team.run(task="复杂任务")
except HandoffError as e:
    # 处理交接失败
    await fallback_agent.run(task=e.original_task)
except MaxTurnsExceeded:
    # 处理超限
    await team.stop()

快速入门示例

创建基础团队

from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination

# 定义代理
assistant = AssistantAgent(name="assistant")
critic = CriticAgent(name="critic")

# 创建团队
team = RoundRobinGroupChat(
    participants=[assistant, critic],
    termination_condition=TextMentionTermination("TERMINATE")
)

# 运行任务
async def main():
    async for message in team.run_stream(task="帮我写一首诗"):
        print(message)

使用交接功能

from autogen_agentchat.handoffs import Handoff, HandoffContext

# 定义交接
handoff_to_critic = Handoff(
    name="handoff_to_critic",
    description="交接给批评代理",
    target=critic_agent
)

# 在代理中使用
@agentai.chat_interface(
    system_message="你可以使用 handoff_to_critic 来请求批评"
)
class AssistantWithHandoff(BaseChatAgent):
    ...

总结

多智能体编排是 AutoGen 框架的核心能力,通过团队管理、交接机制、工具集成和消息订阅等组件的协作,开发者可以构建复杂的自动化工作流。理解这些核心概念和它们的交互方式,是有效使用 AutoGen 构建多智能体系统的基础。

如需更多信息,请参考:

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py:1-100

群聊模式与选择器

群聊模式(Group Chat)是 AutoGen 中实现多智能体协作的核心机制。在群聊场景中,多个代理(Agent)需要相互通信、共享信息并协作完成复杂任务。选择器(Selector) 是决定下一个发言者(Speaker)的关键组件,它根据预定义的策略、图结构或运行时状态来选择下一个执行任务的代理。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 核心接口

继续阅读本节完整说明和来源证据。

章节 工作原理

继续阅读本节完整说明和来源证据。

章节 配置选项

继续阅读本节完整说明和来源证据。

概述

群聊模式(Group Chat)是 AutoGen 中实现多智能体协作的核心机制。在群聊场景中,多个代理(Agent)需要相互通信、共享信息并协作完成复杂任务。选择器(Selector) 是决定下一个发言者(Speaker)的关键组件,它根据预定义的策略、图结构或运行时状态来选择下一个执行任务的代理。

AutoGen 提供了多种群聊模式实现,每种模式使用不同的选择器策略:

群聊模式选择策略适用场景
RoundRobinGroupChat轮询制固定顺序执行、均匀分布任务
SelectorGroupChatLLM 驱动选择动态决策、上下文感知
DiGraphGroupChat图结构依赖有向无环图工作流
SwarmGroupChat话题转移动态协作、开放式任务
MagenticOneGroupChat协调器控制复杂多步骤任务

架构设计

核心接口

群聊系统基于 BaseGroupChat 抽象基类构建,所有具体实现都继承自该基类:

classDiagram
    class BaseGroupChat {
        <<abstract>>
        +agents: List[BaseChatAgent]
        +termination_condition: TerminationCondition
        +max_turns: Optional[int]
        +reset_on_agent_start: bool
        +async run() StreamResponse
        +async reset() None
    }
    
    class RoundRobinGroupChat {
        +run()
    }
    
    class SelectorGroupChat {
        +selector_prompt: str
        +allow_repeated_speaker: bool
        +run()
    }
    
    class DiGraphGroupChat {
        +graph: DiGraph
        +run()
    }
    
    class SwarmGroupChat {
        +allow_repeated_speaker: bool
        +run()
    }
    
    BaseGroupChat <|-- RoundRobinGroupChat
    BaseGroupChat <|-- SelectorGroupChat
    BaseGroupChat <|-- DiGraphGroupChat
    BaseGroupChat <|-- SwarmGroupChat

RoundRobinGroupChat(轮询制群聊)

工作原理

RoundRobinGroupChat 采用简单的轮询策略,按照代理在列表中的顺序依次选择发言者。当一个代理完成发言后,下一个代理自动成为下一个发言者。

flowchart TD
    A[开始群聊] --> B{当前轮次 < max_turns?}
    B -->|是| C[获取当前发言者索引]
    C --> D[发言者执行任务]
    D --> E{发言者是否为终止代理?}
    E -->|是| F[终止群聊]
    E -->|否| G[更新发言者索引]
    G --> B
    B -->|否| F

配置选项

参数类型默认值说明
agentsList[BaseChatAgent]必填参与群聊的代理列表
max_turnsOptional[int]None最大轮次数,None 表示无限制
termination_conditionTerminationConditionNone终止条件
reset_on_agent_startboolTrue代理开始时是否重置计数器

已知问题

Issue #7670: 当使用 3 个代理且 max_round=4 时,代理 C 永远不会被选中。这是由发言者选择循环中的 off-by-one 错误导致的。

# 问题代码示例(简化)
for i in range(max_rounds):
    current_index = i % len(agents)  # 当 max_rounds=4, agents=3 时
    # 索引序列: 0, 1, 2, 0 (代理 C 跳过)

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py:1-100

SelectorGroupChat(选择器群聊)

工作原理

SelectorGroupChat 使用 LLM 驱动的选择策略。在每次需要选择下一个发言者时,系统会向 LLM 发送包含当前上下文和可用代理信息的提示词,由 LLM 决定下一个发言者。

sequenceDiagram
    participant User as 用户
    participant LLM as 选择器 LLM
    participant Agents as 代理池
    
    User->>LLM: 请求选择下一个发言者
    LLM->>LLM: 分析上下文和代理描述
    LLM-->>Agents: 返回选中的代理名称
    Agents->>Agents: 选中的代理执行任务
    Agents->>LLM: 任务完成,请求下一轮选择

配置选项

参数类型默认值说明
agentsList[BaseChatAgent]必填参与群聊的代理列表
selector_promptstr默认提示词选择器的系统提示词模板
selector_model_clientChatCompletionClient必填用于选择器的模型客户端
allow_repeated_speakerboolFalse是否允许同一代理连续发言
max_turnsOptional[int]None最大轮次数
termination_conditionTerminationConditionNone终止条件

选择器提示词模板

默认的选择器提示词包含以下关键元素:

  1. 代理描述: 每个代理的角色和能力描述
  2. 对话历史: 最近的对话内容摘要
  3. 可选代理列表: 当前可以选择的代理
  4. 选择理由: LLM 需要输出的选择理由
SELECTOR_PROMPT_TEMPLATE = """
You are in a role-play game. ...
The available agents to speak next are:
{agent_list}

Based on the above conversation, who should speak next?
...
"""

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py:1-150

DiGraphGroupChat(图结构群聊)

工作原理

DiGraphGroupChat 基于有向无环图(DAG)定义工作流程。每个节点代表一个代理或一组代理,边定义执行顺序和依赖关系。

flowchart LR
    A[Start] --> B[Researcher]
    B --> C[Planner]
    C --> D[Executor]
    C --> E[Coder]
    D --> F[Reviewer]
    E --> F
    F --> G[End]

图配置

参数类型说明
graphDiGraph定义节点和边的有向图
agentsList[BaseChatAgent]代理列表
allow_repeated_speakerbool是否允许重复发言

节点定义

@dataclass
class DiGraphNode:
    name: str                          # 节点名称
    agent: Optional[BaseChatAgent]     # 关联的代理
    next_nodes: List[str]             # 后继节点列表

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py:1-100

SwarmGroupChat(蜂群群聊)

工作原理

SwarmGroupChat 实现了一种动态协作模式,代理之间可以基于话题进行转移。当一个代理完成当前任务后,它可以:

  1. 继续处理同一话题
  2. 将控制权转移给另一个代理
  3. 声明任务完成并退出群聊
flowchart TD
    A[代理 A 处理话题 T1] --> B{是否完成?}
    B -->|否| C[是否转移话题?]
    C -->|是| D[声明新话题 T2]
    C -->|否| E[继续处理 T1]
    D --> F[选择下一代理]
    E --> F
    B -->|是| G{是否退出?}
    G -->|是| H[移除出群聊]
    G -->|否| F
    F --> I[代理 B 接手]

特殊消息类型

SwarmGroupChat 使用特殊的 HandoffMessage 来实现话题转移:

消息类型说明
HandoffMessage声明目标代理和可选的话题
FunctionCallROUMessage代理调用工具
TextMessage纯文本消息

配置

参数类型说明
agentsList[BaseChatAgent]初始代理列表
allow_repeated_speakerbool是否允许重复发言
max_turnsOptional[int]最大轮次

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py:1-100

MagenticOneGroupChat

工作原理

MagenticOneGroupChat 是 AutoGen 最复杂的群聊实现,它使用一个协调器(Orchestrator)来管理整个任务执行流程。协调器负责任务分解、子任务分配和结果整合。

flowchart TD
    subgraph 协调器
        A[任务规划] --> B[子任务分配]
        B --> C[结果验证]
        C -->|需要修正| D[重新规划]
        D --> B
        C -->|完成| E[任务汇总]
    end
    
    E --> F[生成最终报告]
    
    subgraph 执行代理
        G[FileSurfer]
        H[WebSurfer]
        I[CodeExecutor]
    end
    
    B --> G
    B --> H
    B --> I

组件构成

组件类型说明
OrchestratorAgent核心协调器
FileSurferAgent本地文件浏览
WebSurferAgent网页浏览和搜索
CodeExecutorAgent代码执行

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.py:1-150

.NET 实现

GroupChatOptions

.NET 端的群聊配置通过 GroupChatOptions 类管理:

public class GroupChatOptions(string groupTopicType, string outputTopicType)
{
    public string GroupChatTopicType { get; } = groupTopicType;
    public string OutputTopicType { get; } = outputTopicType;
    public ITerminationCondition? TerminationCondition { get; set; }
    public int? MaxTurns { get; set; }
    public Dictionary<string, GroupParticipant> Participants { get; } = new Dictionary<string, GroupParticipant>();
}

GroupParticipant

public struct GroupParticipant(string topicType, string description)
{
    public string TopicType { get; } = topicType;
    public string Description { get; } = description;
    
    // 支持元组隐式转换
    public static implicit operator GroupParticipant((string topicType, string description) tuple)
}

资料来源:dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.cs:1-50

终止条件

所有群聊模式都支持通过 TerminationCondition 接口定义终止条件:

终止条件类型说明
MaxMessageTermination达到最大消息数时终止
TextMentionTermination当消息包含特定文本时终止
StopMessageTermination当代理发送停止信号时终止
TokenUsageTermination达到令牌使用上限时终止

最佳实践

选择合适的群聊模式

场景推荐模式
均匀分配任务的批处理RoundRobinGroupChat
需要 LLM 智能决策SelectorGroupChat
有明确工作流程的 DAGDiGraphGroupChat
开放式协作任务SwarmGroupChat
复杂多步骤项目MagenticOneGroupChat

常见配置建议

  1. 设置合理的 max_turns: 防止无限循环,默认为消息数 * 代理数
  2. 配置终止条件: 明确任务完成标准
  3. 选择合适的模型: 选择器 LLM 应具有良好的推理能力
  4. 监控令牌使用: 群聊可能产生大量消息

社区相关讨论

已知问题

  • Issue #7670: GroupChat round-robin 在 max_round 为偶数时跳过最后一个代理
  • Issue #5327: 分布式环境中任务持久化的需求

扩展方向

  • 支持更复杂的选择策略(如基于强化学习)
  • 增强 Swarm 模式的话题跟踪能力
  • 改进令牌使用监控和报告

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py:1-100

代码执行器

代码执行器(Code Executor)是 AutoGen 框架中负责安全执行 LLM 生成代码的核心组件。在多智能体系统中,LLM 生成的代码需要在一个受控环境中执行,以完成各种任务。代码执行器提供了代码执行的抽象接口,支持多种执行后端,包括本地命令行、Docker 容器、Jupyter 内核和 Azure 容器实例。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 基类设计

继续阅读本节完整说明和来源证据。

章节 执行结果模型

继续阅读本节完整说明和来源证据。

章节 代码执行器智能体

继续阅读本节完整说明和来源证据。

概述

代码执行器(Code Executor)是 AutoGen 框架中负责安全执行 LLM 生成代码的核心组件。在多智能体系统中,LLM 生成的代码需要在一个受控环境中执行,以完成各种任务。代码执行器提供了代码执行的抽象接口,支持多种执行后端,包括本地命令行、Docker 容器、Jupyter 内核和 Azure 容器实例。

代码执行器的主要职责包括:

  • 接收并验证 LLM 生成的代码块
  • 在隔离环境中执行代码
  • 捕获执行结果、输出和错误信息
  • 管理执行超时和重试机制
  • 提供代码执行历史记录
graph TD
    A[LLM 生成代码] --> B[代码执行器]
    B --> C{执行后端类型}
    C --> D[LocalCommandLineCodeExecutor]
    C --> E[DockerCommandLineCodeExecutor]
    C --> F[JupyterCodeExecutor]
    C --> G[AzureContainerCodeExecutor]
    D --> H[本地进程执行]
    E --> I[Docker 容器隔离]
    F --> J[Jupyter 内核]
    G --> K[Azure Container Instances]
    H --> L[执行结果]
    I --> L
    J --> L
    K --> L

核心架构

基类设计

AutoGen 的代码执行器采用分层架构设计。BaseCodeExecutor 作为所有执行器的抽象基类,定义了统一的接口和行为规范。

# 伪代码展示基类结构
class BaseCodeExecutor(ABC):
    component_type = "code_executor"
    
    def __init__(
        self,
        timeout: Optional[float] = None,
        work_dir: Optional[str] = None,
    ):
        self._timeout = timeout
        self._work_dir = work_dir or tempfile.gettempdir()

基类的核心职责:

  • 管理代码执行超时设置
  • 维护工作目录和文件路径
  • 提供代码执行结果的统一样式
  • 支持组件化加载和保存

资料来源:python/packages/autogen-core/src/autogen_core/code_executor/_base.py:1-50

执行结果模型

代码执行后,结果以结构化形式返回,包含执行状态和输出信息:

字段类型说明
exit_codeint退出码,0 表示成功
outputstr标准输出内容
errorOptional[str]错误信息(如果有)

资料来源:python/packages/autogen-core/src/autogen_core/code_executor/_base.py:80-120

代码执行器智能体

CodeExecutorAgent 是专门用于处理代码生成和执行的智能体。它通过以下流程工作:

  1. 调用 LLM 生成代码
  2. 从 LLM 输出中提取 Markdown 代码块
  3. 将代码块传递给代码执行器执行
  4. 收集执行结果并反馈给 LLM
  5. 根据退出码决定是否重试
graph LR
    A[LLM 生成代码] --> B[提取代码块]
    B --> C{有代码块?}
    C -->|是| D[执行代码]
    C -->|否| E[输出文本回复]
    D --> F{执行成功?}
    F -->|是| G[结束]
    F -->|否| H{重试次数<最大?}
    H -->|是| A
    H -->|否| G

代码执行器智能体的关键配置参数:

参数类型默认值说明
max_retries_on_errorint3执行失败时的最大重试次数
code_block_separatorstr包含代码块的分割符用于分隔多个代码块
model_clientAny必需LLM 模型客户端
code_executorBaseCodeExecutor必需代码执行器实例

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:1-150

执行器类型

LocalCommandLineCodeExecutor

本地命令行代码执行器是最基础的执行器,它直接在当前系统中创建子进程执行代码。

安全警告:此执行器直接将 LLM 生成的代码写入磁盘并作为本地子进程执行,没有任何沙箱机制、文件系统隔离或网络限制。这意味着恶意代码可能对系统造成损害。

资料来源:github.com/microsoft/autogen/issues/7462

# 使用示例
from autogen_core.code_executor import LocalCommandLineCodeExecutor

executor = LocalCommandLineCodeExecutor(
    timeout=60,
    work_dir="./workspace"
)

适用场景

  • 受信任的本地开发环境
  • 快速原型开发和测试
  • 离线隔离环境

DockerCommandLineCodeExecutor

Docker 代码执行器在隔离的 Docker 容器中执行代码,提供更好的安全隔离。

from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor

executor = DockerCommandLineCodeExecutor(
    image="python:3.11-slim",
    timeout=60,
)
参数类型说明
imagestrDocker 镜像名称
timeoutfloat执行超时时间(秒)
work_dirstr容器内工作目录
bind_dirOptional[str]宿主机挂载目录

资料来源:python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py:1-100

优势

  • 进程级别隔离
  • 可配置的资源限制
  • 独立的文件系统视图
  • 网络隔离可选

JupyterCodeExecutor

Jupyter 代码执行器通过 Jupyter 内核执行代码,适合需要持久化执行状态和变量共享的场景。

from autogen_ext.code_executors.jupyter import JupyterCodeExecutor

executor = JupyterCodeExecutor(
    kernel_name="python3",
    timeout=60,
)

资料来源:python/packages/autogen-ext/src/autogen_ext/code_executors/jupyter/_jupyter_code_executor.py:1-80

特点

  • 支持代码状态持久化
  • 变量和函数可在多次执行间共享
  • 适合数据分析和探索性编程

AzureContainerCodeExecutor

Azure 容器代码执行器在 Azure Container Instances 中执行代码,适合大规模云端部署场景。

from autogen_ext.code_executors.azure import AzureContainerCodeExecutor

executor = AzureContainerCodeExecutor(
    image="mcr.microsoft.com/azure-cli:latest",
    timeout=300,
    container_name="autogen-executor",
)
参数类型说明
imagestrAzure Container Instance 镜像
timeoutfloat执行超时时间(秒)
container_namestr容器实例名称
resource_groupstrAzure 资源组
subscription_idstrAzure 订阅 ID

资料来源:python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py:1-100

代码块提取

代码执行器智能体使用正则表达式从 LLM 输出中提取 Markdown 格式的代码块:

def _extract_markdown_code_blocks(self, text: str) -> List[str]:
    """从 Markdown 文本中提取所有代码块内容"""
    pattern = r'```(?:\w+)?\n(.*?)```'
    return re.findall(pattern, text, re.DOTALL)

支持的代码块格式:

  • 标准 Markdown 代码块:\\\python ... \\\
  • 无语言标识的代码块:\\\ ... \\\
  • 包含在文本中的代码块

安全考虑

已知安全风险

风险类型影响缓解措施
代码注入可能执行恶意代码使用 Docker/Jupyter 执行器隔离
文件系统访问可能读取敏感文件限制 work_dir 范围
网络访问可能进行未授权网络操作使用网络隔离的容器镜像
资源耗尽可能占用大量 CPU/内存设置 timeout 和资源限制

资料来源:github.com/microsoft/autogen/issues/7462

安全建议

  1. 生产环境:始终使用 Docker 或 Azure Container 执行器
  2. 工作目录限制:明确设置 work_dir 参数,避免访问敏感路径
  3. 超时设置:为长时间运行的代码设置合理的 timeout
  4. 镜像选择:使用最小化的基础镜像,减少攻击面
  5. 网络隔离:对于不需要网络的场景,使用 --network none 选项

社区安全提案

OWASP Agent Memory Guard 等安全工具正在被提议集成到 autogen-ext 中,以提供额外的内存污染防护层。

资料来源:github.com/microsoft/autogen/issues/7671

配置指南

基础配置

from autogen_core.code_executor import LocalCommandLineCodeExecutor

# 基础配置
executor = LocalCommandLineCodeExecutor(
    timeout=60,          # 超时时间(秒)
    work_dir="./work",  # 工作目录
)

高级配置

# Docker 执行器完整配置
executor = DockerCommandLineCodeExecutor(
    image="python:3.11-slim",
    timeout=120,
    work_dir="/workspace",
    bind_dir="./shared_data",  # 挂载宿主机目录
    auto_remove=True,          # 执行后自动删除容器
)

环境变量

某些执行器支持通过环境变量配置:

变量名适用执行器说明
DOCKER_DEFAULT_PLATFORMDocker设置默认平台
AZURE_SUBSCRIPTION_IDAzureAzure 订阅 ID
AZURE_RESOURCE_GROUPAzureAzure 资源组

与智能体的集成

代码执行器可以通过以下方式与智能体系统集成:

方式一:直接注入工具

from autogen_core import AgentProxy, FunctionCall

# 将执行器作为工具注册到智能体
agent = AssistantAgent(
    name="coding_assistant",
    tools=[code_executor.as_tool()],
)

方式二:使用 CodeExecutorAgent

from autogen_agentchat.agents import CodeExecutorAgent

# 创建专用的代码执行智能体
code_agent = CodeExecutorAgent(
    name="code_executor",
    source="assistant",
    code_executor=executor,
    max_retries_on_error=3,
)

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:100-150

常见问题

Q: 代码执行超时怎么办?

A: 可以通过以下方式处理:

  • 增加 timeout 参数值
  • 将长时间任务分解为多个短任务
  • 检查代码是否有死循环或无限等待

Q: 如何在执行器间共享文件?

A: 使用 Docker 执行器的 bind_dir 参数将宿主机目录挂载到容器中。

Q: 执行器支持哪些编程语言?

A: 这取决于执行环境:

  • Local/Docker:依赖系统安装的语言
  • Jupyter:依赖内核配置
  • Azure:依赖容器镜像

Q: 如何处理执行器的安全限制?

A: 评估代码来源的可信度,使用适当的执行器类型,并配置安全策略。

最佳实践

  1. 开发环境:使用 LocalCommandLineCodeExecutor 进行快速迭代
  2. 测试环境:使用 Docker 执行器进行隔离测试
  3. 生产环境:使用 Azure Container 执行器或自托管 Kubernetes
  4. 数据处理:使用 Jupyter 执行器保持状态
  5. 大规模并行:考虑分布式执行架构

相关资源

资料来源:python/packages/autogen-core/src/autogen_core/code_executor/_base.py:1-50

MCP协议集成

MCP(Model Context Protocol)协议集成是AutoGen框架中用于实现代理(Agent)与外部工具和服务之间标准化通信的核心组件。该集成允许AutoGen代理通过统一的协议接口调用MCP服务器提供的工具,同时支持MCP服务器向代理发起请求(如采样、用户交互等)。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 整体架构

继续阅读本节完整说明和来源证据。

章节 组件职责

继续阅读本节完整说明和来源证据。

章节 工具调用(Tool Calling)

继续阅读本节完整说明和来源证据。

概述

MCP(Model Context Protocol)协议集成是AutoGen框架中用于实现代理(Agent)与外部工具和服务之间标准化通信的核心组件。该集成允许AutoGen代理通过统一的协议接口调用MCP服务器提供的工具,同时支持MCP服务器向代理发起请求(如采样、用户交互等)。

AutoGen的MCP集成主要包含两个核心模块:

  • MCP Workbench:作为工具调用的入口点,管理代理与MCP服务器之间的通信
  • MCP Session Host:处理MCP服务器向客户端的请求,支持采样(sampling)、用户交互(elicitation)和文件系统根目录(roots)等高级功能

资料来源:python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md

架构设计

整体架构

AutoGen的MCP协议集成采用客户端-服务器架构,核心组件之间的关系如下图所示:

flowchart LR
    subgraph Source_Agent ["代理层"]
        WB[MCP Workbench]
        HS[MCP Session Host]
        
        subgraph Abstract_Components ["抽象组件"]
            R[RootsProvider]
            S[Sampler]
            E[Elicitor]
        end

        subgraph Component_Subclasses ["具体实现"]
            CCCS[ChatCompletionClientSampler]
            SE[StdioElicitor]
            SRP[StaticRootsProvider]
        end
    end

    subgraph MCP_Server ["MCP服务器层"]
        MS[MCP Server]
    end

    CCC[Chat Completion Client]

    WB -->|"tool call"| MS
    MS -.->|"sampling/elicitation/roots requests"| WB
    WB -->|"sampling/elicitation/roots requests"| HS
    HS -->|"sampling"| S
    S --> CCCS
    CCCS -->|"completion"| CCC

组件职责

组件类型职责
MCP Workbench核心组件管理工具调用生命周期,处理MCP协议消息路由
MCP Session Host核心组件处理服务器端发起的请求(sampling/elicitation/roots)
RootsProvider抽象接口提供文件系统根目录访问控制
Sampler抽象接口定义语言模型采样行为
Elicitor抽象接口定义用户交互和数据收集行为
ChatCompletionClientSampler具体实现使用AutoGen的ChatCompletionClient实现采样
StdioElicitor具体实现通过标准输入/输出实现用户交互
StaticRootsProvider具体实现提供静态配置的文件系统根目录

资料来源:python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md

核心功能

工具调用(Tool Calling)

MCP Workbench支持代理调用MCP服务器暴露的各种工具。工具调用流程如下:

sequenceDiagram
    participant Agent as 代理
    participant WB as MCP Workbench
    participant MS as MCP Server
    
    Agent->>WB: 请求调用工具
    WB->>MS: 发送tool call请求
    MS->>MS: 执行工具逻辑
    MS-->>WB: 返回工具结果
    WB-->>Agent: 返回执行结果

采样支持(Sampling)

MCP协议支持服务器请求客户端使用语言模型进行文本生成。ChatCompletionClientSampler实现类使用AutoGen的ChatCompletionClient完成采样:

  • 服务器发送sampling请求到Workbench
  • Workbench转发请求到Session Host
  • Session Host调用Sampler接口
  • ChatCompletionClientSampler使用配置的模型生成回复
  • 结果通过协议返回给服务器

资料来源:python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md

用户交互(Elicitation)

Elicitation功能允许MCP服务器向用户请求结构化数据或确认信息。StdioElicitor通过标准输入/输出实现此功能:

  • 服务器发送elicitation请求
  • Session Host调用Elicitor接口
  • StdioElicitor显示提示信息并收集用户输入
  • 输入结果格式化后返回

文件系统根目录(Roots)

Roots机制提供对文件系统访问的安全控制:

  • RootsProvider接口定义了根目录的查询方式
  • StaticRootsProvider提供静态配置的根目录列表
  • 代理只能访问配置的根目录范围内的文件

资料来源:python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md

安装与配置

依赖安装

使用MCP功能需要安装相应的扩展包:

pip install "autogen-ext[mcp]"

基本使用示例

以下示例展示如何配置MCP Workbench并调用MCP服务器工具:

from autogen_ext.tools.mcp import McpWorkbench

# 初始化MCP Workbench
workbench = McpWorkbench()

# 连接MCP服务器
await workbench.connect("path/to/mcp_server")

# 调用工具
result = await workbench.call_tool("tool_name", {"param": "value"})

# 断开连接
await workbench.disconnect()

安全性考虑

根据社区反馈(issue #7669),MCP工具集成涉及以下安全考量:

  1. 内容级威胁:MCP服务器返回的工具输出可能包含提示注入(prompt injection)内容
  2. 数据泄露风险:代理通过MCP工具访问的数据可能被不当外泄
  3. 根目录隔离:Roots机制应正确配置以防止未授权的文件系统访问

建议在生产环境中:

  • 对MCP工具返回的内容进行验证和过滤
  • 限制代理可访问的文件系统范围
  • 监控工具调用日志

资料来源:https://github.com/microsoft/autogen/issues/7669

错误处理

常见错误类型

错误类型描述处理方式
ConnectionError无法连接到MCP服务器检查服务器地址和网络连接
TimeoutError工具执行超时增加超时配置或优化工具逻辑
InvalidResponseError服务器返回格式无效检查MCP服务器实现
RootsAccessError尝试访问根目录外的文件验证路径配置

编码问题

在非英语环境下,文件操作可能需要指定UTF-8编码。相关代码示例:

# 使用markitdown处理HTML内容时指定编码
html.encode("utf-8")

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/playwright_controller.py

与其他组件的集成

WebSurfer代理集成

MCP协议也应用于AutoGen的WebSurfer组件,用于网页内容提取和处理:

flowchart TD
    subgraph WebSurfer
        PC[Playwright Controller]
        MC[MarkItDown Converter]
    end
    
    PC -->|"获取HTML"| page
    PC -->|"转换"| MC
    MC -->|"Markdown"| Agent

FileSurfer代理集成

FileSurfer代理使用MCP协议扩展文件浏览功能,支持本地文件系统和Markdown文件预览:

# FileSurfer使用McpWorkbench扩展能力
from autogen_ext.tools.mcp import McpWorkbench

class FileSurfer:
    def __init__(self, model_client):
        self._mcp_workbench = McpWorkbench()

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py

版本历史

版本重要变更
0.7.3修复MCP示例文档错误
0.7.x完善MCP协议支持,增加sampling/elicitation/roots功能

资料来源:https://github.com/microsoft/autogen/releases/tag/python-v0.7.3

相关资源

资料来源:python/packages/autogen-ext/src/autogen_ext/tools/mcp/_host/README.md

内置智能体

AutoGen 框架提供了一系列内置智能体(Built-in Agents),旨在简化多智能体系统的构建流程。这些智能体封装了常见的任务处理能力,包括代码执行、网页浏览、文件操作等,使开发者能够快速构建复杂的人工智能应用而无需从零开始实现核心逻辑。

章节 相关页面

继续阅读本节完整说明和来源证据。

章节 AssistantAgent - 助手智能体

继续阅读本节完整说明和来源证据。

章节 CodeExecutorAgent - 代码执行智能体

继续阅读本节完整说明和来源证据。

章节 MultimodalWebSurfer - 多模态网页浏览器

继续阅读本节完整说明和来源证据。

概述

AutoGen 框架提供了一系列内置智能体(Built-in Agents),旨在简化多智能体系统的构建流程。这些智能体封装了常见的任务处理能力,包括代码执行、网页浏览、文件操作等,使开发者能够快速构建复杂的人工智能应用而无需从零开始实现核心逻辑。

内置智能体基于 ChatAgent 基类构建,提供了标准化的接口和事件模型。每个智能体都支持异步消息处理、工具调用、流式响应等核心功能,并可无缝集成到团队(Team)协作框架中。

核心内置智能体类型

AssistantAgent - 助手智能体

AssistantAgent 是 AutoGen 中最基础的对话智能体,负责与大型语言模型交互并生成响应。它通过模型客户端与 LLM 通信,支持系统消息配置、工具绑定以及上下文管理。

主要特性:

  • 支持系统消息自定义
  • 可绑定多种工具函数
  • 维护对话历史和模型上下文
  • 支持流式和非流式响应

基本用法:

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(model="gpt-4")
assistant = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message="你是一个有用的AI助手。"
)

# 运行智能体
result = await assistant.run(task="解释量子计算的基本原理")

CodeExecutorAgent - 代码执行智能体

CodeExecutorAgent 专门用于接收 LLM 生成的代码并执行。它通过 CodeExecutor 接口支持多种执行环境,包括本地执行、Docker 容器执行等。

执行流程:

graph TD
    A[接收模型响应] --> B{检测代码块}
    B -->|无代码块| C[直接返回文本]
    B -->|有代码块| D[提取代码块]
    D --> E[执行代码]
    E --> F{执行结果}
    F -->|成功| G[返回输出]
    F -->|失败| H{重试次数}
    H -->|可重试| E
    H -->|已达上限| G

关键参数:

参数类型说明
max_retries_on_errorint代码执行失败时的最大重试次数
code_executorCodeExecutor代码执行器实例
model_clientChatCompletionClient用于代码生成的模型客户端

代码执行智能体的核心逻辑位于源码中的执行循环:

# 提取 markdown 代码块
code_blocks = self._extract_markdown_code_blocks(str(model_result.content))

# 执行代码块
execution_result = await self.execute_code_block(
    inferred_text_message.code_blocks, 
    cancellation_token
)

# 将执行结果添加到上下文
await model_context.add_message(
    UserMessage(
        content=execution_result.output,
        source=agent_name,
    )
)

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:70-100

MultimodalWebSurfer - 多模态网页浏览器

MultimodalWebSurfer 是一个高级智能体,能够通过 Playwright 控制真实浏览器进行网页交互。它结合了视觉模型和多模态推理能力,可以理解网页截图并执行相应操作。

支持的工具操作:

工具名称功能描述
goto导航到指定 URL
click点击页面元素
hover悬停在元素上
fill填写表单字段
select_option选择下拉选项
drag拖拽操作
screenshot截取页面截图
scroll滚动页面
keyboard模拟键盘输入
summarize_page总结当前页面内容
answer_question回答关于页面的问题
sleep等待页面加载

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_tool_definitions.py:1-80

架构设计:

graph TB
    A[用户请求] --> B[构建提示词]
    B --> C[SOM截图 + 历史消息]
    C --> D[模型推理]
    D --> E{响应类型}
    E -->|文本| F[直接返回答案]
    E -->|工具调用| G[执行工具]
    G --> H[Playwright控制器]
    H --> I[浏览器状态更新]
    I --> J[返回执行结果]

初始化配置:

from autogen_ext.agents.web_surfer import MultimodalWebSurfer

web_surfer = MultimodalWebSurfer(
    name="web_surfer",
    model_client=model_client,
    downloads_folder="/tmp/downloads",
    headless=True,
    start_page="https://www.bing.com/",
    animate_actions=False,
)

配置参数说明:

参数类型默认值说明
namestr必需智能体名称
model_clientChatCompletionClient必需多模态模型客户端
downloads_folderstrNone下载文件保存目录
headlessboolTrue是否无头模式运行
start_pagestrbing.com起始页面 URL
animate_actionsboolFalse是否动画展示操作
to_save_screenshotsboolFalse是否保存截图

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/web_surfer/_multimodal_web_surfer.py:80-120

安全注意事项:

请注意,使用 MultimodalWebSurfer 涉及与为人类设计的数字世界交互,存在固有风险。智能体可能会偶尔尝试危险操作,如招募人类帮助或未经人类授权接受 Cookie 协议。建议在受控环境中监控智能体运行。
同时,MultimodalWebSurfer 可能容易受到来自网页的提示词注入攻击。

FileSurfer - 文件浏览器

FileSurfer 智能体提供本地文件系统浏览能力,支持目录导航、文件预览和内容搜索。它使用 Markdown 文件浏览器后端,支持多种文件格式的预览。

核心功能:

  • 目录浏览和导航
  • 文件内容预览
  • 多种格式支持(Markdown、TXT、HTML 等)
  • Markdown 格式转换

目录列表渲染:

当浏览目录时,FileSurfer 会生成格式化的目录索引:

def _fetch_local_dir(self, local_path: str) -> str:
    """渲染本地目录列表为 HTML 格式"""
    listing = f"""
# Index of {local_path}

[返回上级目录](../)

{目录内容...}
"""
    return listing

资料来源:python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_markdown_file_browser.py:60-90

SocietyOfMindAgent - 思维社会智能体

SocietyOfMindAgent 实现了一种多智能体协作模式,其中一个主智能体协调多个子智能体共同完成任务。每个子智能体专注于特定领域,通过消息传递共享信息和协调工作。

协作架构:

graph LR
    A[用户请求] --> B[主智能体]
    B --> C[子智能体1]
    B --> D[子智能体2]
    B --> E[子智能体N]
    C --> F[结果汇总]
    D --> F
    E --> F
    F --> B
    B --> G[最终响应]

使用示例:

from autogen_agentchat.agents import SocietyOfMindAgent

team = SocietyOfMindAgent(
    name="research_team",
    participants=[researcher, writer, critic],
)

智能体基类架构

ChatAgent 基类

所有内置智能体都继承自 ChatAgent 基类,提供了统一的消息处理和生命周期管理接口。

核心方法:

方法说明
run(task, cancellation_token)运行智能体处理任务
run_stream(task, cancellation_token)流式运行,返回异步生成器
on_messages(messages, cancellation_token)处理消息流
on_messages_stream(messages, cancellation_token)消息流处理(异步生成器)

事件模型

智能体通过事件流与外部系统通信,主要事件类型包括:

事件类型说明
CodeGenerationEvent代码生成事件,包含代码块内容
CodeExecutionEvent代码执行结果事件
TextMessage文本消息事件
FunctionCall函数调用请求
FunctionExecutionResult函数执行结果

安全考量

根据社区反馈和已知问题,在使用内置智能体时需要注意以下安全事项:

LocalCommandLineCodeExecutor 安全风险

安全问题 #7462LocalCommandLineCodeExecutor 将 LLM 生成的代码直接写入磁盘并作为本地子进程执行,没有任何沙箱、文件系统隔离或网络限制。

风险场景:

  • LLM 可能生成恶意代码并执行
  • 没有资源限制或超时保护
  • 可以访问本地文件系统和网络

缓解措施:

  1. 使用 Docker 代码执行器提供隔离环境
  2. 限制可访问的文件系统路径
  3. 设置执行超时和资源限制

提示词注入风险

安全问题 #7669:智能体调用 shell、浏览器、文件和 MCP 工具时,存在内容级别的威胁,包括工具输出中的提示词注入和数据泄露风险。

防护建议:

  • 对外部内容进行过滤和验证
  • 使用 OWASP Agent Memory Guard 等安全工具
  • 实施输出内容的审查机制

团队协作与集成

内置智能体可以组合成团队进行复杂任务处理:

from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination

team = RoundRobinGroupChat(
    participants=[assistant, web_surfer, code_executor],
    termination_condition=TextMentionTermination("TERMINATE"),
    max_turns=10,
)

await team.run(task="帮我搜索最新的人工智能研究并总结")

MagenticOne 组聊天

MagenticOneGroupChat 提供了一个复杂的多智能体协调框架:

from autogen_agentchat.teams import MagenticOneGroupChat

m1_team = MagenticOneGroupChat(
    participants=[planner, web_surfer, file_surfer, code_executor],
    max_turns=50,
    max_stalls=3,
)

配置序列化和反序列化:

# 导出配置
config = team._to_config()

# 从配置恢复
restored_team = MagenticOneGroupChat._from_config(config)

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.py:50-80

配置与序列化

所有内置智能体支持组件化配置和序列化:

# 获取智能体配置
config = agent.dump_component()

# 从配置加载智能体
loaded_agent = ChatAgent.load_component(config)

配置结构示例

@dataclass
class AssistantAgentConfig:
    name: str
    description: str
    model_client: Any
    system_message: str
    tools: List[Tool] = field(default_factory=list)

常见问题与限制

非英语环境编码问题

问题 #5566:在非英语环境下,playwright_controller.py 中的 open() 函数需要指定 encoding='utf-8' 参数。

解决方案: 确保在读取或写入文件时明确指定编码格式。

GroupChat 轮询限制

问题 #7670:当 max_round 为偶数时,GroupChat 轮询模式下最后一个智能体可能无法被选中。

症状: 3 个智能体设置 max_round=4 时,智能体 C 永远不会被选中。

模型成本追踪

问题 #4835:模型成本和缓存令牌的追踪机制存在缺陷,需要改进 RequestUsage 类的逻辑。

最佳实践

  1. 选择合适的智能体:根据任务需求选择最合适的内置智能体类型
  2. 资源限制:为代码执行设置合理的超时和重试策略
  3. 安全隔离:在可能的情况下使用 Docker 或沙箱环境执行代码
  4. 错误处理:实现完善的错误处理和降级策略
  5. 监控日志:启用详细日志以便问题排查和性能分析
  6. 团队配置:合理设计智能体团队的职责分工和通信模式

扩展内置智能体

开发者可以通过继承 ChatAgent 基类或组合现有智能体来创建自定义智能体:

from autogen_agentchat.agents import ChatAgent
from autogen_core import CancellationToken

class CustomAgent(ChatAgent):
    def __init__(self, name: str):
        super().__init__(name=name)
    
    async def on_messages(self, messages, cancellation_token: CancellationToken):
        # 自定义消息处理逻辑
        pass

资料来源:python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:70-100

失败模式与踩坑日记

保留 Doramagic 在发现、验证和编译中沉淀的项目专属风险,不把社区讨论只当作装饰信息。

high 来源证据:Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node

可能增加新用户试用和生产接入成本。

high 来源证据:[Feature] FunASR as self-hosted speech-to-text tool for voice agents

可能增加新用户试用和生产接入成本。

high 来源证据:RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)

可能增加新用户试用和生产接入成本。

high 失败模式:security_permissions: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec

Developers may expose sensitive permissions or credentials: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec

Pitfall Log / 踩坑日志

项目:microsoft/autogen

摘要:发现 31 个潜在踩坑项,其中 8 个为 high/blocking;最高优先级:安装坑 - 来源证据:Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node。

1. 安装坑 · 来源证据:Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安装相关的待验证问题:Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_850c646256974bf887dcfebeae9a7286 | https://github.com/microsoft/autogen/issues/7487 | 来源讨论提到 node 相关条件,需在安装/试用前复核。

2. 安装坑 · 来源证据:[Feature] FunASR as self-hosted speech-to-text tool for voice agents

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安装相关的待验证问题:[Feature] FunASR as self-hosted speech-to-text tool for voice agents
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0583aa188952475b905a04658c2a82e8 | https://github.com/microsoft/autogen/issues/7742 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

3. 配置坑 · 来源证据:RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个配置相关的待验证问题:RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_cf0842636cfd495e8993e39e969d192b | https://github.com/microsoft/autogen/issues/7748 | 来源类型 github_issue 暴露的待验证使用条件。

4. 安全/权限坑 · 失败模式:security_permissions: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec

  • 严重度:high
  • 证据强度:source_linked
  • 发现:Developers should check this security_permissions risk before relying on the project: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec
  • 对用户的影响:Developers may expose sensitive permissions or credentials: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec. Context: Observed when using node
  • 防护动作:Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/microsoft/autogen/issues/7724
  • 证据:failure_mode_cluster:github_issue | fmev_9e6caea1ca7b69ebf5b4767ec0ee2b9b | https://github.com/microsoft/autogen/issues/7724 | Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec

5. 安全/权限坑 · 失败模式:security_permissions: [Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard

  • 严重度:high
  • 证据强度:source_linked
  • 发现:Developers should check this security_permissions risk before relying on the project: [Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard
  • 对用户的影响:Developers may expose sensitive permissions or credentials: [Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: [Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard. Context: Observed when using python
  • 防护动作:Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/microsoft/autogen/issues/7783
  • 证据:failure_mode_cluster:github_issue | fmev_2f20b0c2046b47a5b5c05f1437c92ff3 | https://github.com/microsoft/autogen/issues/7783 | [Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard

6. 安全/权限坑 · 来源证据:Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Discussion: standardising the agent-task marketplace surface — draft AIP-1 spec
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_9ac9d80f24ec4c59bc8f142b0e8882a5 | https://github.com/microsoft/autogen/issues/7724 | 来源讨论提到 node 相关条件,需在安装/试用前复核。

7. 安全/权限坑 · 来源证据:Feature proposal: Backpressure contract declarations for multi-agent coordination

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Feature proposal: Backpressure contract declarations for multi-agent coordination
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_e6095aa394984c59b3dbc72bb1022927 | https://github.com/microsoft/autogen/issues/7321 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

8. 安全/权限坑 · 来源证据:Payment primitive for multi-agent systems - how are teams handling this?

  • 严重度:high
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Payment primitive for multi-agent systems - how are teams handling this?
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_35f60f0f1011435394f5e2583cd804a6 | https://github.com/microsoft/autogen/issues/7492 | 来源类型 github_issue 暴露的待验证使用条件。

9. 安装坑 · 失败模式:installation: [Feature] FunASR as self-hosted speech-to-text tool for voice agents

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this installation risk before relying on the project: [Feature] FunASR as self-hosted speech-to-text tool for voice agents
  • 对用户的影响:Developers may fail before the first successful local run: [Feature] FunASR as self-hosted speech-to-text tool for voice agents
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: [Feature] FunASR as self-hosted speech-to-text tool for voice agents. Context: Observed when using python, cuda
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_eb4ef4bf1d7dc63fc84e0d3693c929f8 | https://github.com/microsoft/autogen/issues/7742 | [Feature] FunASR as self-hosted speech-to-text tool for voice agents

10. 安装坑 · 失败模式:installation: python-v0.6.2

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this installation risk before relying on the project: python-v0.6.2
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.6.2
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.6.2. Context: Observed when using python, docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_0a7e034c78e6a265885801941e670b18 | https://github.com/microsoft/autogen/releases/tag/python-v0.6.2 | python-v0.6.2

11. 安装坑 · 失败模式:installation: python-v0.7.1

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this installation risk before relying on the project: python-v0.7.1
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.7.1
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.7.1. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_5a51ab3e316847feb8a1e4dddf355fec | https://github.com/microsoft/autogen/releases/tag/python-v0.7.1 | python-v0.7.1

12. 配置坑 · 失败模式:configuration: Feature proposal: Backpressure contract declarations for multi-agent coordination

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: Feature proposal: Backpressure contract declarations for multi-agent coordination
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: Feature proposal: Backpressure contract declarations for multi-agent coordination
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Feature proposal: Backpressure contract declarations for multi-agent coordination. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_05bbb1ed008f581f8fe3400a4c4728fd | https://github.com/microsoft/autogen/issues/7321 | Feature proposal: Backpressure contract declarations for multi-agent coordination

13. 配置坑 · 失败模式:configuration: Payment primitive for multi-agent systems - how are teams handling this?

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: Payment primitive for multi-agent systems - how are teams handling this?
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: Payment primitive for multi-agent systems - how are teams handling this?
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Payment primitive for multi-agent systems - how are teams handling this?. Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_7f0c1a345395da925bd384da1a535b52 | https://github.com/microsoft/autogen/issues/7492 | Payment primitive for multi-agent systems - how are teams handling this?

14. 配置坑 · 失败模式:configuration: RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_76f9f898d0743e7dfe2ebc62c46da33e | https://github.com/microsoft/autogen/issues/7748 | RFC: Cross-agent shared memory store with on-demand capsule recall (agent/group/global scopes)

15. 配置坑 · 失败模式:configuration: Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)
  • 对用户的影响:Developers may misconfigure credentials, environment, or host setup: Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss). Context: Source discussion did not expose a precise runtime context.
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_6ac7e01ab2b3ede21419a81bd4132d34 | https://github.com/microsoft/autogen/issues/7770 | Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)

16. 配置坑 · 失败模式:configuration: python-v0.6.0

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: python-v0.6.0
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.6.0
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.6.0. Context: Observed when using python, docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_f24708f1efbf6cd45f51d05cf23604a6 | https://github.com/microsoft/autogen/releases/tag/python-v0.6.0 | python-v0.6.0

17. 配置坑 · 失败模式:configuration: python-v0.7.2

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this configuration risk before relying on the project: python-v0.7.2
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.7.2
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.7.2. Context: Observed when using python, docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_db62372ac052c839b032fb4484abaac7 | https://github.com/microsoft/autogen/releases/tag/python-v0.7.2 | python-v0.7.2

18. 能力坑 · 能力判断依赖假设

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:README/documentation is current enough for a first validation pass.
  • 对用户的影响:假设不成立时,用户拿不到承诺的能力。
  • 建议检查:将假设转成下游验证清单。
  • 防护动作:假设必须转成验证项;没有验证结果前不能写成事实。
  • 证据:capability.assumptions | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | README/documentation is current enough for a first validation pass.

19. 运行坑 · 失败模式:runtime: python-v0.5.7

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this runtime risk before relying on the project: python-v0.5.7
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.5.7
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.5.7. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_675ad7963bf4efce625e54e689bfbe18 | https://github.com/microsoft/autogen/releases/tag/python-v0.5.7 | python-v0.5.7

20. 维护坑 · 失败模式:migration: python-v0.6.4

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:Developers should check this migration risk before relying on the project: python-v0.6.4
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.6.4
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.6.4. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_40423aae7c69942f7f03284e7624e5e2 | https://github.com/microsoft/autogen/releases/tag/python-v0.6.4 | python-v0.6.4

21. 维护坑 · 来源证据:_rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant mess…

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题:_rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant message.
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_f98ce071eb68498ea53d55541e0bf413 | https://github.com/microsoft/autogen/issues/7768 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

22. 维护坑 · 维护活跃度未知

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:未记录 last_activity_observed。
  • 对用户的影响:新项目、停更项目和活跃项目会被混在一起,推荐信任度下降。
  • 建议检查:补 GitHub 最近 commit、release、issue/PR 响应信号。
  • 防护动作:维护活跃度未知时,推荐强度不能标为高信任。
  • 证据:evidence.maintainer_signals | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | last_activity_observed missing

23. 安全/权限坑 · 下游验证发现风险项

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:下游已经要求复核,不能在页面中弱化。
  • 建议检查:进入安全/权限治理复核队列。
  • 防护动作:下游风险存在时必须保持 review/recommendation 降级。
  • 证据:downstream_validation.risk_items | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | no_demo; severity=medium

24. 安全/权限坑 · 存在评分风险

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:no_demo
  • 对用户的影响:风险会影响是否适合普通用户安装。
  • 建议检查:把风险写入边界卡,并确认是否需要人工复核。
  • 防护动作:评分风险必须进入边界卡,不能只作为内部分数。
  • 证据:risks.scoring_risks | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | no_demo; severity=medium

25. 安全/权限坑 · 来源证据:Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:Safety Report: AI Agent Guardrails Do Not Work — 56-Day Proof (06K Loss)
  • 对用户的影响:可能影响授权、密钥配置或安全边界。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_ed5f9599f46f4353814aae56487fa735 | https://github.com/microsoft/autogen/issues/7770 | 来源类型 github_issue 暴露的待验证使用条件。

26. 安全/权限坑 · 来源证据:[Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard

  • 严重度:medium
  • 证据强度:source_linked
  • 发现:GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题:[Feature Request] Memory Poisoning Protection for AutoGen Agents via OWASP Agent Memory Guard
  • 对用户的影响:可能增加新用户试用和生产接入成本。
  • 建议检查:来源问题仍为 open,Pack Agent 需要复核是否仍影响当前版本。
  • 防护动作:不得脱离来源链接放大为确定性结论;需要标注适用版本和复核状态。
  • 证据:community_evidence:github | cevd_0de33858db1a468a8499c998186b0c41 | https://github.com/microsoft/autogen/issues/7783 | 来源讨论提到 python 相关条件,需在安装/试用前复核。

27. 能力坑 · 失败模式:capability: Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal int...

  • 严重度:low
  • 证据强度:source_linked
  • 发现:Developers should check this capability risk before relying on the project: Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node
  • 对用户的影响:Developers may hit a documented source-backed failure mode: Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node. Context: Observed when using node
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_f8be78df0f98c1279b85ea47849866f8 | https://github.com/microsoft/autogen/issues/7487 | Multi-agent systems need a 'mission keeper' role — not a Boss Agent, but a dedicated goal integrity node

28. 能力坑 · 失败模式:capability: _rstrip_last_assistant_message only strips trailing whitespace from the content — it does not...

  • 严重度:low
  • 证据强度:source_linked
  • 发现:Developers should check this capability risk before relying on the project: _rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant message.
  • 对用户的影响:Developers may hit a documented source-backed failure mode: _rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant message.
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: _rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant message.. Context: Observed when using python
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_issue | fmev_bd382458f825fe0e88b80f76d7052bc9 | https://github.com/microsoft/autogen/issues/7768 | _rstrip_last_assistant_message only strips trailing whitespace from the content — it does not remove the assistant message.

29. 运行坑 · 失败模式:performance: python-v0.7.5

  • 严重度:low
  • 证据强度:source_linked
  • 发现:Developers should check this performance risk before relying on the project: python-v0.7.5
  • 对用户的影响:Upgrade or migration may change expected behavior: python-v0.7.5
  • 建议检查:Before packaging this project, run the relevant install/config/quickstart check for: python-v0.7.5. Context: Observed when using python, docker
  • 防护动作:State this as source-backed community evidence, not as Doramagic reproduction.
  • 证据:failure_mode_cluster:github_release | fmev_211ecdadb7d40356be2b3dc71aa6abf0 | https://github.com/microsoft/autogen/releases/tag/python-v0.7.5 | python-v0.7.5

30. 维护坑 · issue/PR 响应质量未知

  • 严重度:low
  • 证据强度:source_linked
  • 发现:issue_or_pr_quality=unknown。
  • 对用户的影响:用户无法判断遇到问题后是否有人维护。
  • 建议检查:抽样最近 issue/PR,判断是否长期无人处理。
  • 防护动作:issue/PR 响应未知时,必须提示维护风险。
  • 证据:evidence.maintainer_signals | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | issue_or_pr_quality=unknown

31. 维护坑 · 发布节奏不明确

  • 严重度:low
  • 证据强度:source_linked
  • 发现:release_recency=unknown。
  • 对用户的影响:安装命令和文档可能落后于代码,用户踩坑概率升高。
  • 建议检查:确认最近 release/tag 和 README 安装命令是否一致。
  • 防护动作:发布节奏未知或过期时,安装说明必须标注可能漂移。
  • 证据:evidence.maintainer_signals | art_9fdcc1bb2e6f43da98af4b9c7cf038b8 | https://github.com/microsoft/autogen#readme | release_recency=unknown

来源:Doramagic 发现、验证与编译记录