0Pricing
Claude Architect · 课时

协调器的职责

分解、委派、汇总、路由并处理错误。

协调器的职责 是 CoddyKit 上的免费 Claude Architect 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Claude Architect 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Claude Architect 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

The Coordinator's Job

In a multi-agent system, Claude orchestration follows a hub-and-spoke shape: one coordinator at the hub, several subagents on the spokes. The coordinator never does the deep work itself — it manages the work.

A coordinator has exactly five responsibilities you must master for the exam:

  • Decompose — split a task into subtasks
  • Delegate — hand each subtask to a subagent
  • Aggregate — merge subagent results
  • Route — send work to the right specialist
  • Handle errors — recover or escalate failures

This lesson walks through each, with the patterns and anti-patterns that separate a passing answer from a plausible distractor.

Subagents Start With a Blank Slate

The single most tested coordinator fact: subagents do NOT inherit the coordinator's conversation history. Each subagent is a fresh Claude context.

The model keeps no state between turns or across agents. Whatever a subagent needs to do its job — the user's goal, prior findings, constraints, IDs — must be passed explicitly inside that subagent's prompt.

Forgetting this is a classic failure: the coordinator 'knows' the customer ID or the research question, assumes the subagent does too, and the subagent fabricates or stalls. Context isolation is a feature (it keeps focus tight), but it puts the burden of context-passing squarely on the coordinator.

Passing Context Explicitly

Because nothing is inherited, the coordinator builds each subagent prompt as a self-contained briefing. Notice how the goal, the constraints, and the specific slice of work are all spelled out — the subagent could run on a machine that never saw the conversation.

This is also why an AgentDefinition carries a system_prompt and least-privilege allowed_tools: each subagent is scoped to its role and given only what it needs.

from claude_agent_sdk import AgentDefinition

researcher = AgentDefinition(
    name="researcher",
    description="Researches one sub-question and returns cited findings.",
    system_prompt=(
        "You research a SINGLE sub-question. "
        "You have no prior context except this prompt. "
        "Return findings with claim->source (URL, quote, date)."
    ),
    allowed_tools=["WebSearch", "WebFetch"],  # least privilege
)

# The coordinator injects ALL needed context per call:
subagent_prompt = (
    f"Overall goal: {user_goal}\n"
    f"Your sub-question: {sub_question}\n"
    f"Constraints: only sources newer than 2023."
)

Decompose: Fixed vs Adaptive

Decomposition is choosing how to break the work apart. Two strategies, and the exam wants you to match strategy to situation:

  • Fixed pipeline / prompt chaining — for a known, sequential set of steps (e.g. extract -> validate -> format). The structure is decided in advance.
  • Adaptive decomposition — for open-ended investigations where you can't know the subtasks until you start (e.g. a research question that branches as you learn).

A second decomposition pattern worth knowing: multi-pass code review. Do a per-file local pass first, then a separate cross-file integration pass. A single-pass multi-file review dilutes the model's attention and misses both local bugs and integration issues.

Delegate: One Response, Parallel Work

The coordinator delegates by issuing Task calls. The key performance fact: multiple Task calls in a single response run in parallel.

For independent subtasks — three research questions, three files to scan — emit all the Task calls together rather than one per turn. You get concurrency for free.

Two prerequisites the exam tests: the coordinator's allowedTools must include "Task", and each subagent must receive its full context explicitly (Scene 2).

# Coordinator delegating THREE independent sub-questions at once.
# Emitting them in a single response runs them in parallel.

tasks = [
    {"subagent": "researcher", "prompt": brief(goal, q)}
    for q in [
        "What are the market size figures?",
        "Who are the top 3 competitors?",
        "What regulatory constraints apply?",
    ]
]

# allowedTools on the coordinator MUST include "Task"
coordinator_allowed_tools = ["Task", "Read", "Write"]

# Each prompt is fully self-contained — no inherited history.

Route: Descriptions Pick the Specialist

Routing means sending each subtask to the right subagent. Claude chooses based primarily on the agent and tool descriptions — not the names.

A good description states purpose, what it returns, input formats with examples, and applicability boundaries. Overlapping or ambiguous descriptions cause misrouting: if two subagents sound like they both handle 'data', the coordinator may pick wrong.

Scope each subagent narrowly. Keep 4-5 tools per agent as the sweet spot; 18+ tools degrades selection reliability. Least-privilege tooling isn't only about security — it sharpens routing.

billing_agent = AgentDefinition(
    name="billing",
    # Sharp, non-overlapping description -> correct routing
    description=(
        "Handles refunds and invoice questions ONLY. "
        "Input: order_id (str) + verified customer_id. "
        "Returns: refund status or invoice PDF link. "
        "Does NOT handle shipping or account changes."
    ),
    system_prompt="...",
    allowed_tools=["lookup_order", "process_refund"],  # 2 tools, scoped
)

Aggregate: Merge With Provenance

Once subagents return, the coordinator aggregates their outputs into one coherent answer. This is more than concatenation.

  • Keep provenance: every claim maps to its source (URL, doc name, quote, publication date).
  • Annotate conflicts rather than silently picking one number — and remember dates often resolve apparent contradictions.
  • Render by content type: tables for financials, prose for news, lists for technical findings.

Aggregation is also where you preserve partial results: if one subagent failed, the coordinator still merges what succeeded and clearly marks the gap.

Handle Errors: Recover Locally, Escalate Up

The fifth responsibility is the one that breaks fragile systems. The rule:

  • Recover transient faults locally inside the subagent (e.g. a timeout — retry there).
  • Escalate non-recoverable failures upward with partial results, so the coordinator can route around them.

Two anti-patterns to avoid: silently suppressing an error (the coordinator never learns), and aborting the whole workflow because one subagent failed. One failed spoke should not collapse the hub.

Crucially, distinguish an access FAILURE (maybe retryable) from a valid EMPTY result (no matches — not an error at all).

Structured Errors Enable Routing

The coordinator can only route around a failure if the failure tells it enough. A generic "Operation failed" blocks recovery. A structured error enables intelligent routing.

Structured error context includes the failure type / category, whether it is retryable, the attempted query, any partial results, and alternatives. With that, the coordinator decides: retry, try another tool, merge partials, or escalate.

# A subagent returning a STRUCTURED error the coordinator can act on:
error_result = {
    "isError": True,
    "errorCategory": "transient",   # transient | validation | business | permission
    "isRetryable": True,
    "message": "Search API timed out after 30s",
    "attempted_query": "market size fintech 2024",
    "partial_results": [{"source": "...", "claim": "..."}],
}

# Coordinator logic:
if error_result["isError"] and error_result["isRetryable"]:
    retry(error_result["attempted_query"])
else:
    escalate_with(error_result["partial_results"])

The Loop Stops on stop_reason

The coordinator runs an agentic loop: send the request, inspect stop_reason, and if it is tool_use, run the tools (including Task delegations), append results to history, and repeat until end_turn.

Terminate on the stop_reason — never by parsing the model's text for words like 'done' or 'finished'. Decisions about when work is complete are model-driven. An iteration cap is a safety net, not the primary stop mechanism.

Reserve hard-coded control for guarantees you must enforce; let the model decide the flow otherwise.

while True:
    resp = client.messages.create(
        model="claude-opus-4-1",
        max_tokens=2048,
        messages=history,   # FULL history every turn — model keeps no state
        tools=tools,
    )
    if resp.stop_reason == "tool_use":
        results = run_tools(resp)           # may include parallel Task calls
        history.append(assistant(resp))
        history.append(tool_results(results))
        continue
    if resp.stop_reason == "end_turn":
        break                               # stop on stop_reason, not on text
    # iteration cap = safety net only, checked separately

When the Coordinator Must Escalate

Some failures aren't the coordinator's to solve — they belong to a human. Good escalation triggers:

  • An explicit human request — escalate immediately.
  • Policy gaps the agent has no rule for.
  • No progress after reasonable attempts.
  • Threshold violations (e.g. a refund above a limit).

Bad triggers the exam will offer as distractors: sentiment analysis, the model's own self-rated confidence (1-10), or untrained classifiers. And when a business rule has financial, legal, or safety consequences, enforce it with a deterministic hook, not prompt guidance — hooks are 100% deterministic, prompts only ~90% probabilistic.

Quick Check: Delegating a Subtask

A research coordinator delegates a sub-question to a researcher subagent. The coordinator already discussed the user's goal and gathered earlier findings in its own conversation. What MUST the coordinator do for the subagent to succeed?

Recap: The Coordinator in Five Moves

You can now reason about a coordinator like an architect:

  • Decompose — fixed pipelines for known sequences, adaptive for open-ended work; multi-pass (local then cross-file) for code review.
  • Delegate — emit multiple Task calls in one response to run in parallel; include 'Task' in allowedTools.
  • Route — sharp, non-overlapping descriptions pick the right specialist; 4-5 tools per agent.
  • Aggregate — merge with provenance, annotate conflicts, preserve partial results.
  • Handle errors — recover transient faults locally; escalate non-recoverable failures with structured context and partial results; never silently suppress or abort the whole workflow.

Above all: subagents inherit no history — pass context explicitly, and stop on stop_reason, never on parsed text. Enforce financial/legal/safety rules with deterministic hooks. Master these and the orchestration scenarios are yours.

常见问题解答

「协调器的职责」课时是免费的吗?

是的 — 「协调器的职责」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Claude Architect 课程的其余内容,请升级到 CoddyKit PRO。 Claude Architect 课程共包含 4 节课。

「协调器的职责」这节课中我会学到什么?

分解、委派、汇总、路由并处理错误。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Claude Architect 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Claude Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「协调器的职责」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Claude Architect 课中编写并运行代码吗?

能。每节 Claude Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 中心辐射式协调器拓扑
  2. 协调器的职责
  3. 子代理不会继承历史记录
  4. 并行生成子代理
← 返回 Claude Architect