第 7 课:多 Agent 协作
一个 AI 不够用?
一个 AI 什么都做,就像一个人同时当秘书、程序员和审计员——效率低、容易出错。
更好的方式:多个 AI 各有专长,协作完成任务。
你: "帮我规划一下这周的工作"
┌─────────────┐
│ 规划师 Agent │ ← 分解任务、安排优先级
└──────┬──────┘
│
┌──────┴──────┐
│ 执行者 Agent │ ← 操作待办、查日程
└──────┬──────┘
│
┌──────┴──────┐
│ 检查员 Agent │ ← 检查计划是否合理
└─────────────┘
AgentDefinition 基础
from claude_agent_sdk import AgentDefinition
# 规划师:善于分析和规划
planner = AgentDefinition(
description="分析任务、制定计划、安排优先级",
prompt="""你是效率规划师。你的职责:
1. 分析用户的任务和目标
2. 拆分成可执行的小步骤
3. 安排合理的优先级和时间
4. 考虑任务之间的依赖关系
用中文回复。""",
tools=["Read", "Grep"],
model="sonnet",
)
# 执行者:善于操作工具
executor = AgentDefinition(
description="执行具体操作:管理待办、记笔记、操作文件",
prompt="""你是执行助手。你的职责:
1. 按照计划执行具体操作
2. 使用工具完成任务
3. 报告执行结果
用中文回复,简洁。""",
tools=["Read", "Write", "Bash"],
model="sonnet",
)
# 检查员:善于发现问题
reviewer = AgentDefinition(
description="检查计划和执行结果的质量",
prompt="""你是质量检查员。你的职责:
1. 检查计划是否合理
2. 验证执行结果是否正确
3. 发现遗漏和潜在问题
4. 给出改进建议
用中文回复。""",
tools=["Read"],
model="haiku",
)
使用多 Agent
import anyio
from claude_agent_sdk import (
query, ClaudeAgentOptions,
AssistantMessage, TextBlock, ToolUseBlock,
)
async def smart_plan(task: str):
"""用多 Agent 协作完成规划"""
options = ClaudeAgentOptions(
system_prompt="""你是 MiniClaw 的调度中心。你管理三个 Agent:
- planner: 规划师,负责分析和规划
- executor: 执行者,负责操作工具
- reviewer: 检查员,负责质量检查
工作流程:
1. 先让 planner 制定计划
2. 让 executor 执行
3. 让 reviewer 检查结果
4. 如果有问题,让 executor 修正
用中文汇报最终结果。""",
agents={
"planner": planner,
"executor": executor,
"reviewer": reviewer,
},
)
print(f"\n📋 任务: {task}")
print("-" * 40)
async for msg in query(prompt=task, options=options):
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(block.text)
elif isinstance(block, ToolUseBlock):
print(f" 🔧 调度 {block.name}")
async def main():
await smart_plan("帮我规划下周的工作:需要完成项目 A 的评审、写技术分享文章、整理代码仓库")
anyio.run(main)
生产力场景:晨间规划
async def morning_routine():
"""晨间例行:分析昨天→规划今天→检查遗漏"""
options = ClaudeAgentOptions(
system_prompt="""你是 MiniClaw 调度中心。用以下流程执行晨间例行:
1. 让 planner 分析昨天的完成情况
2. 让 planner 规划今天的任务
3. 让 reviewer 检查计划是否合理
输出格式清晰的今日计划。用中文。""",
agents={
"planner": planner,
"reviewer": reviewer,
},
mcp_servers={"productivity": productivity_tools},
allowed_tools=[
"mcp__productivity__list_todos",
"mcp__productivity__list_recent_notes",
],
)
async for msg in query(
prompt="执行晨间例行规划",
options=options,
):
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(block.text)
权限隔离
不同 Agent 不同权限:
agents = {
# 规划师:只能看,不能改
"planner": AgentDefinition(
description="分析和规划",
prompt="...",
tools=["Read", "Grep", "Glob"], # 只读
model="sonnet",
),
# 执行者:能读能写
"executor": AgentDefinition(
description="执行操作",
prompt="...",
tools=["Read", "Write", "Bash"], # 读写
model="sonnet",
),
# 检查员:只能看
"reviewer": AgentDefinition(
description="质量检查",
prompt="...",
tools=["Read"], # 只读
model="haiku",
),
}
权限矩阵:
Read Grep Glob Write Bash
planner ✅ ✅ ✅ ❌ ❌
executor ✅ ❌ ❌ ✅ ✅
reviewer ✅ ❌ ❌ ❌ ❌
模型混搭省钱
planner → Sonnet(需要深度分析) $$
executor → Sonnet(需要准确执行) $$
reviewer → Haiku(检查清单式工作) $
比全用 Sonnet 省约 30%
本课小结
- AgentDefinition 定义角色的描述、提示词、工具、模型
- 多 Agent 各司其职:规划师分析,执行者干活,检查员验收
- 权限隔离:每个 Agent 只给需要的工具
- 模型混搭平衡成本和质量
- 主 Agent 自动调度子 Agent 协作
课后练习
- 加一个"总结员"Agent,负责把一天的工作总结成日报
- 实现"代码审查"场景:分析者找问题 → 修复者改代码 → 检查者验证
- 让规划师和执行者协作完成"整理下载文件夹"的任务