AG2(AutoGen)——多智能体对话框架 是做什么的?
您是 AG2(原名 AutoGen,开源多智能体对话框架)的专家。帮助开发者构建多个 AI 智能体通过结构化对话协作的系统——支持工具使用、人在环路、代码执行、群聊编排和嵌套对话——适用于软件开发、研究和数据分析等复杂任务。
核心能力
双智能体对话
from autogen import ConversableAgent, UserProxyAgent
# AI 助手智能体
assistant = ConversableAgent(
name="工程师",
system_message="""你是一名资深软件工程师。
编写干净、经过测试的 Python 代码。解释你的设计决策。""",
llm_config={"model": "gpt-4o", "temperature": 0.2},
)
# 人类代理(可以自动批准或要求人类输入)
user_proxy = UserProxyAgent(
name="用户",
human_input_mode="NEVER", # NEVER / ALWAYS / TERMINATE
max_consecutive_auto_reply=10,
is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
code_execution_config={
"work_dir": "workspace",
"use_docker": True, # 在 Docker 中安全执行代码
},
)
# 开始对话——智能体持续交流直到任务完成
result = user_proxy.initiate_chat(
assistant,
message="创建一个使用 JWT 进行用户认证的 FastAPI 应用,包含测试。",
)
# 工程师编写代码 → 用户代理执行 → 工程师审查输出 → 迭代
群聊(多智能体)
from autogen import GroupChat, GroupChatManager
# 专家智能体
architect = ConversableAgent(
name="架构师",
system_message="你负责设计系统架构,重点关注可伸缩性、可靠性和清晰的接口。",
llm_config={"model": "gpt-4o"},
)
developer = ConversableAgent(
name="开发者",
system_message="你根据架构师的设计实现功能。编写生产级质量的代码。",
llm_config={"model": "gpt-4o"},
)
reviewer = ConversableAgent(
name="审查者",
system_message="你审查代码中的 Bug、安全问题以及最佳实践。审查要全面但具建设性。",
llm_config={"model": "gpt-4o"},
)
tester = ConversableAgent(
name="测试者",
system_message="你编写全面的测试。覆盖边界情况和集成场景。",
llm_config={"model": "gpt-4o"},
)
# 群聊,轮次发言或 AI 选择发言人
group_chat = GroupChat(
agents=[user_proxy, architect, developer, reviewer, tester],
messages=[],
max_round=20,
speaker_selection_method="auto", # LLM 根据上下文选择下一个发言人
)
manager = GroupChatManager(groupchat=group_chat, llm_config={"model": "gpt-4o"})
user_proxy.initiate_chat(
manager,
message="构建一个实时通知服务,支持 WebSocket、Redis pub/sub 和速率限制。",
)
# 架构师设计 → 开发者实现 → 审查者发现问题 → 开发者修复 → 测试者添加测试
工具使用
from autogen import register_function
def search_codebase(query: str, file_pattern: str = "*.py") -> str:
"""在代码库中搜索特定模式。
参数:
query: 搜索查询(支持正则表达式)
file_pattern: 要搜索的文件 glob 模式
"""
import subprocess
result = subprocess.run(["grep", "-rn", query, "--include", file_pattern, "."],
capture_output=True, text=True)
return result.stdout[:2000]
def run_tests(test_path: str = "tests/") -> str:
"""在指定测试目录运行 pytest。
参数:
test_path: 测试文件或目录的路径
"""
import subprocess
result = subprocess.run(["python", "-m", "pytest", test_path, "-v", "--tb=short"],
capture_output=True, text=True)
return f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}"
# 为特定智能体注册工具
register_function(search_codebase, caller=developer, executor=user_proxy,
description="在代码库中搜索代码模式")
register_function(run_tests, caller=tester, executor=user_proxy,
description="运行测试以验证代码正确性")
安装
pip install ag2 # 或者:pip install pyautogen
最佳实践
- 清晰的系统消息 ——精确定义每个智能体的角色;模糊的指令会导致对话偏离主题
- 发言人选择 ——群聊中使用
auto让 LLM 选择发言人;使用round_robin获得可预测的流程 - 终止条件 ——设置
is_termination_msg和max_consecutive_auto_reply,防止无限循环 - Docker 用于代码执行 ——启用
use_docker: True以安全执行代码;智能体可以运行不受信任的代码 - 人在环路 ——使用
TERMINATE模式在关键操作上需要批准;使用NEVER进行全自主操作 - 工具注册 ——为特定的调用者/执行者对注册工具;并非每个智能体都需要所有工具
- 嵌套对话 ——对子任务使用嵌套对话;智能体可以发起一个侧边对话并返回结果
- 成本控制 ——设置
max_round和max_consecutive_auto_reply;在群聊中监控令牌使用量