第 12 章 StrandsMulti-AgentSwarm
第 12 章:多 Agent 模式:Agent Swarms
第 12 章:多 Agent 模式:Agent Swarms
关于本课
本课程的视频是当时的一个快照。Strands 一直在积极开发,所以本页展示的代码反映的是最新的写法,但视频里讲的概念依然成立。有疑问时,以代码为准。
本课代码:samples/12-swarms
Agent Swarms
在 swarm 里,Agent 之间自主交接,没有任何预先定义的结构。没有编排器决定下一个谁跑,也没有 Graph 把顺序钉死。执行路径是从每个 Agent 自己发现的东西里长出来的。
当你没法提前把流程画出来时,这个模式最合适:排查线上故障、开放式调研,或者任何下一步取决于上一步发现了什么的问题。
from strands import Agent
from strands.multiagent import Swarm
triage = Agent(
name="triage",
system_prompt="Initial assessment. Hand off to the relevant specialist.",
)
log_analyst = Agent(
name="log_analyst",
system_prompt="Analyze application logs. Hand off if you find infra/deployment issues.",
tools=[check_application_logs],
)
metrics_analyst = Agent(
name="metrics_analyst",
system_prompt="Analyze system metrics. Hand off based on findings.",
tools=[check_metrics_dashboard],
)
deployment_reviewer = Agent(
name="deployment_reviewer",
system_prompt="Review recent deployments and infrastructure changes.",
tools=[check_recent_deployments, check_infrastructure_status],
)
debugging_swarm = Swarm(
[triage, log_analyst, metrics_analyst, deployment_reviewer],
entry_point=triage,
max_handoffs=10,
max_iterations=10,
execution_timeout=300.0,
node_timeout=120.0,
repetitive_handoff_detection_window=6,
repetitive_handoff_min_unique_agents=2,
)
result = debugging_swarm(
"Payment service returning 500 errors for 25% of requests. Started 30 min ago."
)
Swarm 有什么不同
- Handoff 是控制权的完整转移,不是一次函数调用。当
log_analyst交接给deployment_reviewer,log analyst 就结束了,它拿不到返回结果。 - Agent 之间共享累积起来的上下文。 每个 Agent 都能看到前面几个 Agent 发现了什么,调查因此能一层层叠上去。
- Strands 会自动注入一个
handoff_to_agenttool。 你不需要写交接逻辑;每个 Agent 的 system prompt 告诉它什么时候该交接,具体由 Model 决定。
安全控制
结构上没有任何东西阻止一个 swarm 在几个 Agent 之间来回弹,所以限制一定要配。不配的话,swarm 可以无限 ping-pong 下去。
| 设置 | 作用 |
|---|---|
max_handoffs |
交接总次数上限 |
max_iterations |
Agent 执行总次数上限 |
execution_timeout |
整个 swarm 的墙钟时间上限 |
node_timeout |
每个 Agent 单轮的时间上限 |
repetitive_handoff_detection_window |
检测同样几个 Agent 之间来回打乒乓的循环 |
组合这些模式
三种多 Agent 模式是可以互相嵌套的:一个 swarm 可以是 Graph 里的一个节点,一个 Graph 里可以装 agents-as-tools,而一个 agent-as-tool 内部又能跑一个 Graph。从满足你协调需求的最简单模式开始,再往上组合。
| 模式 | 结构 | 什么时候用 |
|---|---|---|
| Agents as Tools | Hub-and-spoke。编排器调用各个 specialist | 管理者-专家关系清晰,上下文需要隔离 |
| Graph | 带显式边的 DAG | 你能把工作流画在白板上 |
| Swarm | 自主交接,没有预定义结构 | 需要这队 Agent 一起把问题摸清楚 |