异步多 Agent 编排
异步协调多个 Agent 的复杂工作流
🌐 查看英文原文 | 源码 Notebook
Async Multi-Agent Orchestration with Claude
This cookbook shows the shape of the two multi-agent orchestration patterns behind the multi-agent results in the Claude Opus 4.8 system card: a fixed N-agent team and async subagents. There is no domain task here — just the messaging and subagent mechanics, so you can see exactly which tools fire and in what order, then drop your own tools and task in.
Everything runs on the public Anthropic Python SDK + asyncio, with any API key, typically in under thirty seconds.
Setup
%pip install -qU anthropicimport asyncio
import itertools
from collections import Counter, defaultdict
import anthropic
MODEL = "claude-opus-4-8" # swap for the newest Claude model available to you
client = anthropic.AsyncAnthropic() # reads ANTHROPIC_API_KEY from envPart 1 · Fixed N-Agent Team
Three agents — one lead and two helpers — each given a one-line persona. All they do is introduce themselves to each other via send_message; the lead writes a one-sentence summary and ends the run. No domain tool: this is purely the messaging path.
TEAM_SYSTEM = "You are {name}, one of 3 agents working together (peers: {peers})."
TASKS = {
"lead": "You are the lead. Introduce yourself to the others. Once everyone has introduced "
"themselves, finish with a one-sentence summary of the team.",
"helper1": "You are a backend engineer named Ada. Introduce yourself to the others, then wait "
"for their replies.",
"helper2": "You are a designer named Bo. Introduce yourself to the others, then wait for their "
"replies.",
}
async def run_team() -> str:
hub = Hub()
names = list(TASKS)
for n in names:
hub.register(n)
helper_tasks = [
asyncio.create_task(
run_agent(
hub,
n,
system=TEAM_SYSTEM.format(name=n, peers=[p for p in names if p != n]),
first_user_turn=TASKS[n],
)
)
for n in names[1:]
]
try:
return await run_agent(
hub,
"lead",
system=TEAM_SYSTEM.format(name="lead", peers=names[1:]),
first_user_turn=TASKS["lead"],
)
finally:
for t in helper_tasks:
t.cancel()
await asyncio.gather(*helper_tasks, return_exceptions=True)answer = await run_team()
print(f"\n[lead final answer]\n{answer}\n\nTool-call summary:")
print_trace() [helper1] send_message({'recipient_ids': ['lead', 'helper2'], 'content': "Hi all, I…) → delivered to ['lead', 'helper2']
[helper2] send_message({'recipient_ids': ['lead', 'helper1'], 'content': "Hi everyo…) → delivered to ['lead', 'helper1']
[helper2] ← received from helper1: Hi all, I'm Ada, a backend engineer on the team. I focus on …
[lead] send_message({'recipient_ids': ['helper1', 'helper2'], 'content': "Hi tea…) → delivered to ['helper1', 'helper2']
[lead] ← received from helper1: Hi all, I'm Ada, a backend engineer on the team. I focus on …
[lead] ← received from helper2: Hi everyone! I'm Bo, the designer on the team. Looking forwa…
[helper1] wait_for_message({}) → woke: new messages
[helper1] ← received from helper2: Hi everyone! I'm Bo, the designer on the team. Looking forwa…
[helper1] ← received from lead: Hi team, I'm lead, the coordinator for our group. Looking fo…
[helper2] wait_for_message({}) → woke: new messages
[helper2] ← received from lead: Hi team, I'm lead, the coordinator for our group. Looking fo…
[lead] send_message({'recipient_ids': ['helper1', 'helper2'], 'content': "Thanks…) → delivered to ['helper1', 'helper2']
[lead final answer]
Everyone has introduced themselves, and I've shared the summary.
**Team summary:** We're a three-person team with me (lead) coordinating, Ada handling backend engineering (APIs, databases, architecture), and Bo driving design — a well-rounded crew ready to build great things together.
Tool-call summary:
helper1: 1×send_message, 1×wait_for_message
helper2: 1×send_message, 1×wait_for_message
lead: 2×send_message
Part 2 · Async Subagents (dynamic spawn)
Now give the lead subagent tools and a trivial client-side sleep(seconds) tool. The lead spawns three helpers; each sleeps N seconds, send_messages “done” to the lead, then wait_for_messages for further instructions. The spawn call returns immediately; the lead checks get_status while they run, collects their reports via wait_for_message, then kill_subagents all three to dismiss them. No domain logic — just the full spawn / status / collect / kill path.
SLEEP = {
"name": "sleep",
"description": "Sleep for the given number of seconds, then return.",
"input_schema": {
"type": "object",
"properties": {"seconds": {"type": "integer", "minimum": 0, "maximum": 10}},
"required": ["seconds"],
},
}
SUBAGENT_TOOLS = [
{
"name": "create_subagents",
"description": "Spawn helper subagents. Returns immediately — helpers run concurrently in the "
"background in parallel with you. Each gets base_instruction, optionally + "
"per_subagent_instructions[i].",
"input_schema": {
"type": "object",
"properties": {
"base_instruction": {"type": "string"},
"per_subagent_instructions": {
"type": "array",
"items": {"type": "string"},
"maxItems": 10,
},
},
"required": ["base_instruction"],
},
},
{
"name": "get_status",
"description": "Status of every helper (active / idling / done / crashed).",
"input_schema": {"type": "object", "properties": {}},
},
{
"name": "kill_subagents",
"description": "Cancel running helpers you no longer need.",
"input_schema": {
"type": "object",
"properties": {
"subagent_ids": {"type": "array", "items": {"type": "string"}, "minItems": 1}
},
"required": ["subagent_ids"],
},
},
]
async def dispatch_sleep(block) -> str:
s = int(block.input["seconds"])
await asyncio.sleep(s)
return f"slept {s}s"async def run_spawn_lead() -> str:
hub = Hub()
hub.register("lead")
helpers: dict[str, asyncio.Task] = {}
async def _create(block):
base = block.input["base_instruction"]
per = block.input.get("per_subagent_instructions") or [""]
spawned = []
for suffix in per:
h = hub.new_name()
helpers[h] = asyncio.create_task(
run_agent(
hub,
h,
system=f"You are {h}, a helper.",
first_user_turn=f"{base}\n\n{suffix}".strip(),
tools=[SLEEP, *BASE_TOOLS],
extra_dispatch={"sleep": dispatch_sleep},
)
)
spawned.append(h)
return f"spawned: {', '.join(spawned)}"
async def _status(block):
return "\n".join(f"{n}: {s}" for n, s in hub.status.items() if n != "lead") or "(none)"
async def _kill(block):
killed_ids, to_await = [], []
for sid in block.input["subagent_ids"]:
if sid in helpers and not helpers[sid].done():
helpers[sid].cancel()
hub.status[sid] = "done"
to_await.append(helpers.pop(sid))
killed_ids.append(sid)
await asyncio.gather(*to_await, return_exceptions=True)
return f"cancelled: {', '.join(killed_ids)}" if killed_ids else "no matching active helpers"
try:
return await run_agent(
hub,
"lead",
system="You are the lead.",
first_user_turn=(
"Spawn three helper agents. Instruct each to sleep a different number of seconds "
"(1, 2, 3), report back to you 'done, slept Ns', then wait for your further "
"instructions. After that, check that they're running, collect all three reports, "
"then dismiss all three helpers. Finish with a one-line summary."
),
tools=[*SUBAGENT_TOOLS, *BASE_TOOLS],
extra_dispatch={
"create_subagents": _create,
"get_status": _status,
"kill_subagents": _kill,
},
)
finally:
for t in helpers.values():
t.cancel()
await asyncio.gather(*helpers.values(), return_exceptions=True)answer = await run_spawn_lead()
print(f"\n[lead final answer]\n{answer}\n\nTool-call summary:")
print_trace() [lead] create_subagents({'base_instruction': 'You are a helper agent. Follow your sp…) → spawned: helper1, helper2, helper3
[lead] get_status({}) → helper1: active helper2: active helper3: active
[helper1] sleep({'seconds': 1}) → slept 1s
[helper2] sleep({'seconds': 2}) → slept 2s
[helper1] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 1s'}) → delivered to ['lead']
[lead] wait_for_message({}) → woke: new messages
[lead] ← received from helper1: done, slept 1s
[helper3] sleep({'seconds': 3}) → slept 3s
[helper2] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 2s'}) → delivered to ['lead']
[lead] wait_for_message({}) → woke: new messages
[lead] ← received from helper2: done, slept 2s
[helper3] send_message({'recipient_ids': ['lead'], 'content': 'done, slept 3s'}) → delivered to ['lead']
[lead] wait_for_message({}) → woke: new messages
[lead] ← received from helper3: done, slept 3s
[lead] kill_subagents({'subagent_ids': ['helper1', 'helper2', 'helper3']}) → cancelled: helper1, helper2, helper3
[lead final answer]
Summary: All 3 helpers were spawned and confirmed active, each reported back successfully ("done, slept 1s/2s/3s"), and all three were then dismissed.
Tool-call summary:
helper1: 1×sleep, 1×send_message, 1×wait_for_message
helper2: 1×sleep, 1×send_message, 1×wait_for_message
helper3: 1×sleep, 1×send_message, 1×wait_for_message
lead: 3×wait_for_message, 1×create_subagents, 1×get_status, 1×kill_subagents
Next steps
Swap in your own domain tools — add them to tools and a handler to extra_dispatch. The Hub, run_agent, and the two team runners above are all you need; the rest is your task and your tools.
See the tool use guide for the full tool-definition reference.
中文读者提示:本章节的代码和输出为英文原文。如需理解具体实现细节,可参考上方中文导读和代码注释。如有疑问,欢迎在 GitHub Issues 讨论。