第 10 章:多 Agent 模式:Agents as Tools
第 10 章:多 Agent 模式:Agents as Tools
关于本课
本课程的视频是当时的一个快照。Strands 一直在积极开发,所以本页展示的代码反映的是最新的写法,但视频里讲的概念依然成立。拿不准的时候,以代码为准。
本课代码:samples/10-agents-as-tools
三种多 Agent 模式
Strands 提供三种可组合的多 Agent 模式。每一种解决不同的协作问题,而且它们可以互相嵌套。本课讲第一种,接下来两课讲 Graph 和 Swarm。
| 模式 | 结构 | 适用场景 |
|---|---|---|
| Agents as Tools | 中心辐射式。Orchestrator 调用 specialist | 经理与专家的关系明确,上下文需要隔离 |
| Graph | 带显式边的 DAG | 你能把工作流画在白板上 |
| Swarm | 自主交接,没有预定义结构 | 结构要靠团队一起摸索出来 |
Agents as Tools
最简单的多 Agent 模式:一个 orchestrator agent 把 specialist agent 当 tool 调用。orchestrator 一直掌握控制权,决定什么时候委派,最后把结果综合起来。
每个 specialist 拿到自己独立的上下文窗口。这是最关键的好处:specialist 可以跑那些输出很吵的 tool(日志读取器、网页抓取器、话很多的 API),处理几千 token 的原始输出,然后只回传一小段结论。orchestrator 的上下文始终是干净的。
直接把 Agent 传进去
最快的方式。把 agent 放进另一个 agent 的 tools 列表,Strands 会自动包装它,用 agent 的 name 和 description 作为 tool spec:
from strands import Agent
from strands.vended_tools.web_fetch import web_fetch
researcher = Agent(
name="researcher",
system_prompt="You are a research specialist. Find factual information.",
tools=[web_fetch],
)
writer = Agent(
name="writer",
system_prompt="You are a technical writer. Use the researcher to gather facts.",
tools=[researcher], # Pass agent directly as a tool
)
writer("Research the FastAPI GitHub repo and write a 3-sentence summary.")用 @tool 包装
如果想完全控制 prompt、模型选择以及结果怎么返回,就把 specialist 包进一个 @tool 函数:
from strands import Agent, tool
from strands.models.bedrock import BedrockModel
from strands.vended_tools.web_fetch import web_fetch
orchestrator_model = BedrockModel(model_id="us.anthropic.claude-opus-5")
specialist_model = BedrockModel(model_id="us.anthropic.claude-sonnet-5")
@tool
def research_assistant(query: str, depth: str = "normal") -> str:
"""Research a topic and return sourced findings.
Args:
query: The research question
depth: How thorough - "quick", "normal", or "deep"
"""
research_agent = Agent(
model=specialist_model,
system_prompt=f"You are a research specialist. Research depth: {depth}.",
tools=[web_fetch],
callback_handler=None, # Run silently
)
response = research_agent(query)
return str(response)
writer = Agent(
model=orchestrator_model,
system_prompt="You are a technical writer. Use the research assistant.",
tools=[research_assistant],
)
数据流:orchestrator 发过去一个字符串,specialist 跑自己的循环,再返回一个字符串。两次调用之间上下文会重置,所以每次委派都是干净的开始。
关键概念
- docstring 就是路由逻辑。 它告诉 orchestrator 什么时候该委派。模型根据 tool 的描述来路由,你永远不用写
if语句。 - Agent 隔离。 每个 sub-agent 有自己的上下文窗口、模型和 tool。一个 agent 的上下文不会漏进另一个里。
- Orchestrator 的控制权。 什么时候调用 specialist、问什么、怎么用返回的结果,都由 orchestrator 决定。这是一次函数调用,不是交接。
- 模型混用。 orchestrator 用更强的模型(它要推理该委派什么),specialist 用更便宜的模型(它们只做聚焦的工作)。
- 安静运行的 sub-agent。 在 sub-agent 上设
callback_handler=None,就能压掉它们的 streaming 输出,只让 orchestrator 向用户 streaming。
当你要处理的领域能清楚切开、想让一个 agent 把结果统一综合起来,或者需要 agent 之间有 request/response 语义时,就用这个模式。