Lab: A Research Pipeline With Parallel Subagents, a Timeout That Keeps Its Partial Results, and a Report With Its Trail
One coordinator turn, three Task calls, one round. The trips and shops subagents bring back sourced findings, the safety subagent times out on crash reports and keeps one partial finding, and the report shows 18% and 11% side by side instead of an average of 14.5%.
What you will learn
- Have the coordinator issue all three subagent calls in one response and answer them in one user turn
- Match each tool_result to its call by id and mark the failed one with is_error
- Return a structured timeout error that keeps the partial results and names the attempted query
- Build a report that sorts claims into contested, established and single source, with a coverage gap line
Before you start
- Error propagation across subagents
- Provenance: claims, sources and conflicts
- Claude tool use with the Anthropic Python SDK
This lab puts two ideas together in one small pipeline. The question is: Did the protected bike lanes change local trips? A coordinator sends three subagents to find out. They run side by side, every finding keeps its source, one search times out, and two sources disagree.
The two ideas have their own articles: error propagation across subagents (what a failing subagent should report) and provenance: claims, sources and conflicts (how a claim keeps its source). This one is about wiring them into a real coordinator turn.
The project uses the real Anthropic Python SDK pointed at a stand-in model built on httpx.MockTransport, so it runs with no API key. Its replies start with "test model reply", and the sources are made-up sample data.
A report nobody can check
Here's a draft report built the careless way:
- "Most riders feel safe." Whose survey? No source is attached.
- Crash data: blank. That search timed out, and nobody was told. The report just goes quiet.
- "Weekday trips rose 14.5%." The sources said 18% and 11%. Someone averaged them, and the trail is gone.
Think of a newsroom. The editor sends three reporters at the same time, not one after another. When they come back, every fact on the page has a name beside it. One reporter's phone died, so the page says not reached: the safety desk. Two reporters brought back different counts, so the page prints both. That's the report we're building.
Spawn together, bring results back together
The coordinator has three subagents: two search the web, one reads documents. Each one sees only its own prompt, so the prompt has to carry the question. This is the same hub-and-spoke shape as in multi-agent hub and spoke, here with the Anthropic SDK and a tool call per spoke. The pattern of several subagent calls in one response is covered on its own in parallel subagents: Task calls in one response.
A note on names. The project's code calls the subagent tool Task, as older versions and the exam guide do; current Claude docs call this tool Agent. In the Agent SDK, the coordinator's allowed tools must include it, or it can't spawn anyone.
The Task tool and what each prompt carries
From research/stand_in.py, the tool definition the coordinator sends:
TOOLS = [{"name": "Task", "description": "Hand one piece of research to a subagent.",
"input_schema": {"type": "object",
"properties": {"description": {"type": "string"},
"prompt": {"type": "string"},
"subagent_type": {"type": "string"}},
"required": ["description", "prompt", "subagent_type"]}}]
QUESTION = "Did the protected bike lanes change local trips?"
PLAN = [("trips", "web_search", "Find weekday trip counts"),
("safety", "web_search", "Find rider safety evidence"),
("shops", "doc_analysis", "Read the shop sales documents")]
On the first call the stand-in answers with one text block and three tool_use blocks, the way Claude would. Each prompt names the topic, repeats the question and lists the fields to return:
for i, (topic, agent, what) in enumerate(PLAN, 1):
prompt = (f"{topic}: {what}. Question: {QUESTION} "
"Return claim, value, evidence, source, url and published for each finding.")
blocks.append({"type": "tool_use", "id": f"toolu_test_{i}", "name": "Task",
"input": {"description": what, "prompt": prompt, "subagent_type": agent}})
Nothing is inherited. If the question isn't in the prompt, the subagent doesn't know it. For why that isolation is useful, see context isolation through subagents.
sources.json: content apart from metadata
The subagents search this sample data. One finding has two blocks:
{
"content": {
"key": "weekday_trips",
"claim": "Weekday bike trips after the lanes opened",
"value": "up 18%",
"evidence": "Counters on Main St logged 18 percent more weekday trips."
},
"meta": {
"source": "City Cycling Report",
"url": "https://example.org/city-cycling",
"published": "12 Mar"
}
}
content says what the finding says: the claim, the value and a short excerpt as evidence. meta says where it came from: source, url and publication date. Keeping them apart means a step that rewrites the content never touches the source. In the safety topic, the second query, "crash reports near the lanes", is marked "timeout": true, so it never answers.
pipeline.py: the coordinator turn
"""The coordinator: three Task calls in one response, run side by side, one report with sources."""
import json
from concurrent.futures import ThreadPoolExecutor
from research.stand_in import make_client, TOOLS, QUESTION
from research.subagents import run_subagent
from research.provenance import build_report, render
client = make_client()
messages = [{"role": "user", "content": QUESTION}]
response = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
tools=TOOLS, messages=messages)
calls = [b for b in response.content if b.type == "tool_use"]
print(f"1 response -> {len(calls)} Task calls: 1 round, not {len(calls)}")
def research(call):
return run_subagent(call.input["prompt"])
with ThreadPoolExecutor() as pool:
results = list(pool.map(research, calls))
blocks, findings, gaps = [], [], []
for call, result in zip(calls, results):
blocks.append({"type": "tool_result", "tool_use_id": call.id,
"content": json.dumps(result),
"is_error": result["isError"]})
if result["isError"]:
findings += result["partialResults"]
gaps.append(result)
print(f" {call.id} {result['topic']}: ERROR "
f"{result['failureType']}, "
f"{len(result['partialResults'])} partial")
else:
findings += result["findings"]
print(f" {call.id} {result['topic']}: "
f"{len(result['findings'])} findings")
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": blocks})
final = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
tools=TOOLS, messages=messages)
print(final.content[0].text)
print(render(build_report(findings, gaps)))
What this file adds:
- One create call, many blocks. All the
tool_useblocks are collected from that single response. Three of them. - Side by side. A
ThreadPoolExecutorruns the three subagents at once. Each gets onlycall.input["prompt"]. - One result per call, matched by id. Every
tool_resultcarries thetool_use_idof its call, andis_errormarks the one that failed. - One user turn back. The assistant turn and a single user turn holding all three results go into
messages. Three results, one round. - Partial results aren't thrown away. A failed result adds its
partialResultsto the findings and goes intogaps.
subagents.py: a timeout that explains itself
def attempt(topic):
found = []
for row in DATA[topic]["queries"]:
try:
found += search(row)
except SearchTimeout as err:
return {"isError": True, "errorCategory": "transient",
"isRetryable": True, "failureType": "timeout",
"attemptedQuery": err.query, "partialResults": found}
return {"isError": False, "topic": topic, "findings": found}
def run_subagent(prompt, tries=2):
topic = prompt.split(":")[0]
for n in range(1, tries + 1):
result = attempt(topic)
if not result["isError"]:
return result
result["topic"] = topic
result["attempts"] = tries
return result
Follow the safety subagent. It has two queries. The first, "rider safety ratings", returns one finding. The second, "crash reports near the lanes", times out. attempt doesn't raise; it returns a structured error: category transient, isRetryable true, failureType timeout, the attemptedQuery that died, and the one finding it already had in partialResults.
run_subagent tries the whole run twice, right where the problem happened. The timeout comes back again, so the error goes up with attempts set to 2. The coordinator doesn't fail; it carries on with what it has and records the gap. The fields errorCategory and isRetryable are the same idea as in tool input schemas and error responses.
provenance.py: the trail
def classify(items):
if len({f["content"]["value"] for f in items}) > 1:
return "contested"
return "established" if len(items) > 1 else "single source"
def build_report(findings, gaps):
groups = defaultdict(list)
for f in findings:
groups[f["content"]["key"]].append(f)
report = {"contested": [], "established": [],
"single source": [], "gaps": gaps}
for items in groups.values():
sources = [(f["content"]["value"], f["meta"]["source"],
f["meta"]["published"]) for f in items]
report[classify(items)].append(
{"claim": items[0]["content"]["claim"], "sources": sources})
return report
def render(report):
out = []
for kind in ("contested", "established", "single source"):
for entry in report[kind]:
out.append(f"{kind.upper()}: {entry['claim']}")
for value, source, when in entry["sources"]:
out.append(f" {value:14} <- {source}, {when}")
for gap in report["gaps"]:
out.append(f"COVERAGE GAP: {gap['topic']} timed out on "
f"\"{gap['attemptedQuery']}\", tried {gap['attempts']}, "
"partial results kept")
return "\n".join(out)
Compared with the standalone provenance example, the lab adds a third bucket. Values that differ are contested. Two or more sources with the same value are established. One source alone is single source: not wrong, just not confirmed. Every value stays attached to its source and date, and every gap gets its own line.
Run it
Running python pipeline.py (after pip install anthropic):
1 response -> 3 Task calls: 1 round, not 3
toolu_test_1 trips: 2 findings
toolu_test_2 safety: ERROR timeout, 1 partial
toolu_test_3 shops: 2 findings
test model reply: 3 reports are back, 1 failed. I will report the gap.
CONTESTED: Weekday bike trips after the lanes opened
up 18% <- City Cycling Report, 12 Mar
up 11% <- Transit Office Memo, 2 Apr
ESTABLISHED: Shop sales on lane streets
stayed steady <- Shop Study, 9 Jan
stayed steady <- Chamber Survey, 30 Jan
SINGLE SOURCE: Riders rate the separated lanes as safe
most riders <- Rider Survey, 20 Feb
COVERAGE GAP: safety timed out on "crash reports near the lanes", tried 2, partial results kept
- Line 1: one response held three Task calls. One round.
- toolu_test_2: safety came back as an error, timeout, with one partial finding.
- "test model reply": the stand-in's second answer, after it counted the
is_errorresults in the user turn. - The report: 18% and 11% both kept with their sources and dates, shop sales confirmed by two sources, rider safety from one survey, and the gap on its own line.
Well established, contested, or still open
Notice that the single-source claim sits next to the gap. Rider safety rests on one survey, and the search that might have backed it up or contradicted it (crash reports) never finished. A reader sees both facts together and can weigh the claim accordingly.
Break it: a tidy report that hides the trail
- Bug one: average and drop the sources. 18% and 11% become 14.5%, a number no source reported, and nobody can trace it.
- Bug two: hide the failed search. Safety timed out, so it's skipped, and the report reads as if nothing was missing.
The fix is the code above: both values with their sources, a gap line for the failed search, and contested and established kept apart. A smooth answer feels finished, but nobody can check it.
Recap
| Piece | Where | What it guarantees |
|---|---|---|
| Three Task calls in one response | pipeline.py | Subagents run side by side, one round |
| One user turn of tool_result blocks | pipeline.py | Each result matched by tool_use_id, failure marked is_error |
| Question inside each prompt | stand_in.py | Subagents get the context they can't inherit |
| Structured timeout | subagents.py | Failure type, attempted query and partial results reach the coordinator |
| content / meta per finding | sources.json | Claim, evidence, source and date travel together |
| contested / established / single source + gaps | provenance.py | The report shows how sure it is and what's missing |
For the exam, this lab mirrors the exercise on orchestrating subagents: when a question shows a timeout or two clashing sources, choose the design that keeps the gap, both values and their sources.
Try it yourself
Remove "timeout": true from the crash reports query in sources.json and give it one finding shaped like the others, with the key rider_safety, the value "most riders" and its own source in meta. Run the pipeline again: the coverage gap line should disappear, and rider safety should move from single source to established.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
