结构化交接协议
交接时提供 ID、摘要、操作和建议。
结构化交接协议 是 CoddyKit 上的免费 Claude Architect 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Claude Architect 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Claude Architect 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Handoffs Need Structure
In a hub-and-spoke multi-agent system, the coordinator constantly hands work to subagents and receives results back. The CRITICAL fact: subagents do NOT inherit the coordinator's conversation history — the model keeps no state, so the FULL request history travels in messages every turn.
That means every handoff must carry its own context explicitly. An unstructured "go fix the auth bug" loses the case ID, what was already tried, and what decision the coordinator needs back. A structured handoff protocol fixes this: each transfer carries an identifier, a summary, the actions taken, and a recommendation.
The Four-Part Handoff
A reliable handoff payload has four fields, each solving a specific failure mode:
- ID — a stable correlation key (case_id, custom_id) so results can be matched to requests, even across parallel calls.
- Summary — the verbatim transactional facts the receiver needs (verified customer ID, order number, amounts).
- Actions — what was already attempted, with results, so work isn't repeated.
- Recommendation — the proposed next step or decision the receiver must confirm or override.
This maps directly onto how coordinators decompose, delegate, aggregate, and route.
Pass Context Explicitly
Because the subagent starts with a blank history, you cannot rely on "it already knows." Build the handoff into the subagent's prompt itself. Notice how the ID, summary, and prior actions are spelled out — nothing is assumed.
subagent_prompt = f"""
HANDOFF
id: {case_id}
summary: Verified customer C-4821 (id confirmed via get_customer).
Order O-9930, refund requested: $420.
actions_taken:
- get_customer -> identity verified
- lookup_order(O-9930) -> status DELIVERED, eligible
recommendation: Approve refund of $420; confirm against policy before process_refund.
Proceed with the recommendation or override it with justification.
"""
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system="You are the refund-processing subagent.",
messages=[{"role": "user", "content": subagent_prompt}],
tools=refund_tools,
)Enforce Shape With Structured Output
A free-text handoff is easy to malform. To guarantee all four fields are present, make the handoff a tool with a JSON Schema and use tool_choice to force structured output. tool_use + JSON Schema eliminates syntax errors and enforces required fields.
Key rule from the fact sheet: mark a field required ONLY if it is always present. id, summary, actions, and recommendation are always present in a valid handoff — so they are legitimately required. An optional field like escalation_reason must NOT be required, or the model will fabricate it.
handoff_tool = {
"name": "emit_handoff",
"description": "Emit a structured handoff to the coordinator.",
"input_schema": {
"type": "object",
"properties": {
"id": {"type": "string"},
"summary": {"type": "string"},
"actions": {"type": "array", "items": {"type": "string"}},
"recommendation": {"type": "string"},
"escalation_reason": {"type": "string"}
},
"required": ["id", "summary", "actions", "recommendation"]
}
}Force the Handoff With tool_choice
How you set tool_choice decides whether you actually get a structured handoff:
"auto"— the model may reply with prose instead of a handoff. Risky for protocols."any"— the model MUST call some tool, guaranteeing structured output.{"type":"tool","name":"emit_handoff"}— forces exactly this tool. Use this when the subagent's job is to return one well-formed handoff.
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system="Summarize your work as a single handoff.",
messages=history,
tools=[handoff_tool],
tool_choice={"type": "tool", "name": "emit_handoff"},
)
handoff = response.content[0].input # {id, summary, actions, recommendation}Correlate With a Stable ID
The ID is what lets a coordinator aggregate results that arrive out of order. When you issue multiple Task calls in one response, they run in parallel — replies don't come back in the order you sent them. Without a correlation key you cannot map a result to its request.
This is the same principle as the Batch API's custom_id, which correlates requests so you can re-submit only the failures. In a synchronous multi-agent flow, your handoff id plays that role.
results_by_id = {}
for handoff in subagent_handoffs:
results_by_id[handoff["id"]] = handoff
# Aggregate deterministically by ID, not by arrival order
for case_id in dispatched_ids:
h = results_by_id.get(case_id)
if h is None:
log.warning("missing handoff for %s", case_id)Keep Facts Verbatim in the Summary
The summary is where handoffs quietly break. Progressive summarization makes numbers, percentages, and dates vague — exactly the fields a receiver needs to act ($420 becomes "a few hundred dollars"). And models attend to the start and end of context more than the middle (lost-in-the-middle).
The fix: pull transactional facts into a separate case-facts block kept verbatim, outside any prose summary. The handoff's summary field should carry these exact facts, never a lossy paraphrase.
case_facts = {
"customer_id": "C-4821",
"order_id": "O-9930",
"refund_amount_usd": 420.00,
"delivered_on": "2026-06-02",
}
# Inject verbatim; do NOT let these pass through summarization
summary = (
"Verified C-4821; order O-9930 delivered 2026-06-02; "
"refund requested $420.00."
)Actions: Distinguish Failure From Empty
The actions field must record not just what ran, but what each call returned — and it must distinguish an access FAILURE (maybe retryable) from a valid EMPTY result (no matches, do not retry). Use structured errors, not generic ones.
A structured error carries isError, errorCategory (transient / validation / business / permission), isRetryable, the attempted query, and partial results. Generic "Operation failed" blocks recovery; structured context lets the receiver route intelligently.
actions = [
{"tool": "get_customer", "result": "verified C-4821"},
{"tool": "lookup_order", "query": "O-9930",
"isError": True, "errorCategory": "transient",
"isRetryable": True,
"message": "order service timeout",
"partial_results": []},
]Recommendation, Not Final Action
The fourth field is a recommendation the receiver can confirm or override — not a unilateral action. This keeps decision authority where it belongs and supports clean escalation.
Good escalation triggers belong in the recommendation: an explicit human request (escalate immediately), a policy gap, no progress after attempts, or a threshold violation. BAD triggers must never drive it: sentiment analysis, a model self-rated confidence score, or an untrained classifier. A recommendation reading "customer sounds frustrated, escalate" is the anti-pattern.
recommendation = (
"Refund $420 is within policy and order is eligible. "
"RECOMMEND approve. NOTE: refunds over $500 require a "
"hook-enforced check; this is under threshold."
)
# escalation_reason set ONLY on a real trigger, e.g.:
# "Customer explicitly asked for a manager."Guard Critical Steps With Hooks
A handoff's recommendation is probabilistic — prompt guidance is right roughly 90% of the time. When acting on a handoff has financial, legal, or safety consequences, the guarantee must be deterministic, enforced by a hook, not by the recommendation text.
An outgoing-call hook can block a policy-violating action (e.g. refund > $500) regardless of what the subagent recommended. A programmatic precondition — block process_refund until get_customer returned a verified ID — gives a guarantee prompts cannot. Hooks = 100% deterministic; prompts ≈ 90% probabilistic.
# settings.json — deterministic enforcement on the action,
# independent of the handoff recommendation
{
"hooks": {
"PreToolUse": [{
"matcher": "process_refund",
"command": "./hooks/block_refund_over_500.sh"
}]
}
}Resume vs Fresh Summary
Sometimes a handoff continues earlier work. --resume <name> continues a named session and fork_session branches from a shared point. But beware: resumed tool results can be STALE if the codebase or data changed underneath them.
When the underlying state has moved, a fresh session seeded with a structured handoff (ID + verbatim facts + actions + recommendation) is often more reliable than resuming a session full of outdated tool output. The structured handoff is what makes a clean restart cheap.
# Continue named work...
claude --resume refund-C4821
# ...but if state changed, start fresh and inject the handoff:
claude -p "$(cat handoff_C4821.json)" \
--system-prompt "Act on this structured handoff."Quick Check: Designing the Handoff
A coordinator dispatches three refund cases to subagents with parallel Task calls. You are designing the handoff each subagent returns so results can be aggregated and acted on safely. Which design is correct?
Recap: Structured Handoff Protocols
Key takeaways:
- Subagents inherit no history — every handoff carries its own context explicitly.
- Four fields: ID (correlate parallel results), summary (verbatim facts), actions (with structured errors), recommendation (confirm/override).
- Force the shape with a handoff tool + JSON Schema and
tool_choice; require only always-present fields. - Keep numbers and dates verbatim in a case-facts block — summarization makes them vague.
- In actions, distinguish access failure from a valid empty result via
errorCategoryandisRetryable. - Gate consequential actions with deterministic hooks, never with the recommendation alone.
- If resumed tool output may be stale, restart fresh with the structured handoff.
用 AI 导师学习 Python — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 26
- 课程
- 104
常见问题解答
「结构化交接协议」课时是免费的吗?
是的 — 「结构化交接协议」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Claude Architect 课程的其余内容,请升级到 CoddyKit PRO。 Claude Architect 课程共包含 4 节课。
「结构化交接协议」这节课中我会学到什么?
交接时提供 ID、摘要、操作和建议。 你通过在浏览器中直接运行的动手代码来练习 Claude Architect,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Claude Architect 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Claude Architect 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「结构化交接协议」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Claude Architect 课中编写并运行代码吗?
能。每节 Claude Architect 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。