ag2ai/ag2 · 上手攻略

  • 仓库:ag2ai/ag2
  • 链接:https://github.com/ag2ai/ag2
  • 分类:skill
  • 作者:Jay
  • 更新:2026-09-02

这是什么

AG2(前身为 Microsoft AutoGen)是一个开源多智能体编程框架,用于构建 AI Agent 并协调多个 Agent 协作完成任务。2026 年 4 月 3 日,微软将 AutoGen 与 Semantic Kernel 合并,推出 Microsoft Agent Framework(MAF),AutoGen 团队转向独立维护,品牌更名为 AG2

当前 pip install ag2 对应的是 AG2 v1.0 协议驱动框架,已完全重写(异步优先、事件驱动),与旧版 AutoGen(import autogen不再兼容

⚠️ 版本警告:AG2 v1.0 (pip install ag2) 不是 Classic AutoGen (pip install ag2-classic) 的直接升级。Agent 模型、编排方式、import 语句全部改变,详情见 迁移指南


解决什么问题

痛点 AG2 如何解决
单 Agent 能力有限 多 Agent 通过消息对话协作,可分配专业角色(reviewer、coder、writer)
需要 LLM 工具调用能力 @tool 装饰器,普通 Python 函数直接注册为 Agent 工具
需要人类在环审批 Human-in-the-loop 支持暂停等待人工输入
多 Agent 编排复杂 Network(Hub + Channels)提供结构化多 Agent 协调
Agent 长期记忆缺失 Agent Harness 提供持久知识、上下文组装、历史压缩
企业级可观测性需求 中间件、Observer、遥测开箱即用

快速安装

环境要求:Python ≥ 3.10

# 基础安装(推荐)
pip install ag2[openai]

# 完整安装(含所有主流模型提供商)
pip install 'ag2[openai,anthropic,gemini,ollama]'

API Key 配置

环境变量方式(推荐,不硬编码):

export OPENAI_API_KEY="sk-..."        # 或 ANTHROPIC_API_KEY / GEMINI_API_KEY / ...
# 对应 config 中写 OpenAIConfig(model="gpt-4o-mini", api_key=None)

每次请求自带 key(不依赖环境变量):

from ag2.config import OpenAIConfig

config = OpenAIConfig(model="gpt-4o-mini", api_key="sk-...")

核心用法

1. 单 Agent

import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig

agent = Agent(
    "assistant",
    prompt="You are a helpful assistant.",
    config=OpenAIConfig(model="gpt-4o-mini"),
)

async def main() -> None:
    reply = await agent.ask("Summarize the main differences between Python lists and tuples.")
    print(reply.body)

asyncio.run(main())

2. 多 Agent 对话(Conversational)

import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig

reviewer = Agent(
    "reviewer",
    prompt="You review Python code for correctness and style.",
    config=OpenAIConfig(model="gpt-4o"),
)

coder = Agent(
    "coder",
    prompt="You write Python code based on requirements.",
    config=OpenAIConfig(model="gpt-4o-mini"),
)

async def main() -> None:
    # coder 写代码,reviewer 审阅
    code_reply = await coder.ask("Write a function that reverses a linked list.")
    review_reply = await reviewer.ask(f"Review this code:\n{code_reply.body}")
    print(review_reply.body)

asyncio.run(main())

3. 注册工具(@tool 装饰器)

from ag2 import tool

@tool
def get_weather(city: str) -> str:
    """Get current weather for a city."""
    return f"The weather in {city} is sunny."

agent = Agent(
    "assistant",
    prompt="You are a helpful assistant that can check weather.",
    config=OpenAIConfig(model="gpt-4o-mini"),
    tools=[get_weather],
)

# Agent 会自动判断何时调用 get_weather

4. 人类在环(Human-in-the-Loop)

from ag2 import Agent, UserInput

agent = Agent(
    "assistant",
    prompt="You are a helpful assistant.",
    config=OpenAIConfig(model="gpt-4o-mini"),
    human_input=UserInput(),  # 暂停等待人工输入
)

async def main() -> None:
    reply = await agent.ask("Should I send this email now? Reply yes or no.")
    # 在这里会暂停,接收人工输入后再继续

5. 多 Agent 网络编排(Network)

from ag2 import Agent, Network, Channel
from ag2.config import OpenAIConfig

# Hub + Channels 模式
hub = Agent("hub", prompt="Route tasks to the appropriate agent.",
             config=OpenAIConfig(model="gpt-4o"))

coder = Agent("coder", ...)
reviewer = Agent("reviewer", ...)

network = Network(hub=hub)
network.register_channel("coding", coder)
network.register_channel("reviewing", reviewer)

async def main() -> None:
    reply = await hub.ask("Write and review a quicksort implementation.")
    print(reply.body)

asyncio.run(main())

6. Agent Harness(知识与上下文压缩)

from ag2 import Agent, AgentHarness
from ag2.config import OpenAIConfig

agent = Agent(
    "assistant",
    prompt="You know about the company's internal APIs.",
    config=OpenAIConfig(model="gpt-4o-mini"),
)

harness = AgentHarness(agent=agent)
harness.add_knowledge("The internal API base URL is https://api.example.com")
harness.add_knowledge("Authentication uses Bearer tokens")

# 长期知识注入,Agent 在对话中自动调用

典型适用场景

场景 为什么用 AG2
代码生成 + 评审流水线 Agent A 写代码 → Agent B 审阅 → Agent A 修订
研究报告多角色协作 规划 Agent、搜索 Agent、写作 Agent、总结 Agent 分工
企业工作流自动化 Human-in-the-loop 审批 + 多模型提供商统一接口
研究实验编排 多 Agent 辩论 + 迭代优化(类似 AutoGen Studio 理念)
.NET + Python 混合团队 MAF 统一 SDK,一套 API 同时服务两个语言生态

坑与注意

⚠️ v1.0 与 Classic AutoGen 不兼容

  • import autogen → 迁移到 pip install ag2-classic
  • import ag2(v1.0)代码完全重写,旧代码不可直接升级
  • 如果代码里有 ConversableAgentGroupChatUserProxyAgent——你用的是 Classic,留在 ag2-classic

⚠️ Python 3.10+ 硬性要求

  • 不支持 Python 3.9,老项目升级需注意

⚠️ 异步优先

  • 所有 ask() 调用返回 AgentReply,需要 awaitasyncio.run()
  • 同步写法(如 Classic AutoGen 的阻塞调用)已不支持

⚠️ 网络编排(Network)复杂度

  • Hub + Channels 模式适合复杂多 Agent 场景,但学习曲线比简单单 Agent 调用高很多
  • 建议先从单 Agent → 双 Agent 对话 → 再进入 Network 编排

⚠️ 工具注册与调用

  • @tool 装饰的函数必须直接是 Python 函数(不接受类或实例方法)
  • Agent 对工具的选择是 LLM 自行决策,无法精确控制

⚠️ API Key 安全

  • 不要把 key 硬编码在代码里——使用环境变量或动态传入 OpenAIConfig(api_key=...)

与同类对比

框架 核心模型 多 Agent 模式 生态 维护方 备注
AG2 任意(OpenAI/Anthropic/Gemini/Ollama…) Network(Hub+Channels)/ GroupChat 独立开源 AG2 社区(微软原 AutoGen 团队) v1.0 协议驱动,异步优先
LangGraph 任意 图节点 + 边 + 状态机 LangChain 生态 LangChain 团队 图结构状态管理,v1.0 GA
CrewAI 任意 角色型 Agent + 任务流水线 独立 CrewAI 团队 强调角色定义,v1.0
Semantic Kernel 微软系优先 技能(Skills)/ 插件 微软生态 微软 企业友好,已合并入 MAF
AutoGen Classic 任意 GroupChat / nested chats 独立(已归档) 微软维护(仅 Bug fix) 2026 进入维护模式

AG2 的核心差异化:异步优先 + 协议驱动 + 微软团队独立维护 + Classic 兼容分支 + Hub/Channels 多 Agent 编排。


一句话推荐结论

多 Agent 协作场景,AG2 是 AutoGen 的精神继承者,异步协议驱动、工具注册简洁、Hub/Channels 编排灵活——若从 AutoGen Classic 迁移需注意 v1.0 是完全重写(不走 import autogen),新项目想构建多 Agent 流水线值得一试;若偏好图结构状态管理则选 LangGraph,偏好角色型流水线则选 CrewAI。