08A.11 Reflection, Parallel Fan-Out and Agent-as-a-Tool

Agents & multimodalLesson 11 of 157,189 words6 parts
Module 08A · 0 of 15 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15

Three patterns that agent builders reach for early and get wrong in the same ways: asking the model to check its own work (reflection), running several branches at once and combining them (parallel fan-out and aggregate), and wrapping a whole agent so another agent can call it like a function (agent-as-a-tool). 08A.10 taught a bounded critique loop, 08A.9 taught fan-out with single model calls, and 08D.3 sketched an agent as a tool. This lesson does not repeat them. Each part states what those lessons already gave you and then adds the engineering that decides whether the pattern survives production: a reflection gate that cannot loop and never returns a worse answer, a fan-out with timeouts, a quorum and honest partial results, and an agent-as-a-tool with a budget slice, a depth limit and a context-isolation check. All code is plain Python with a scripted fake model, run for real below.

What you'll learn

  • What is already in 08A.9, 08A.10 and 08D.3 for these three patterns, and exactly what is new here
  • Reflection as a gate on the final answer inside the raw loop, and score-aware reflection that keeps the best draft and stops on target, plateau, regression or oscillation
  • How to tell whether reflection actually helped (fixes versus breaks, with cost)
  • Parallel fan-out: bounded concurrency, per-branch timeouts, a quorum that cancels stragglers, a shared token pool, partial results, and aggregators that refuse to hide gaps
  • Agent-as-a-tool: carving a child budget from the parent's, limiting depth, returning structured results, rolling up spend, and proving the parent's context stays small
  • How the OpenAI Agents SDK and Claude Agent SDK expose agents as tools, after you have built the plain version
  • How to evaluate each pattern with tiny deterministic checks and where to go in Modules 10A and 10B

What you don't need

  • API keys. Every runnable sample uses a scripted fake model with no network. The provider snippets in 2.4 and 4.4 are illustrative and need keys, but nothing else does.
  • Docker or any service. Everything is in-memory Python, asyncio and the standard library.
  • A framework. The raw version comes first on purpose; frameworks appear only in 4.5, after the plain version.

Setup

Python 3.11 or newer (the code uses asyncio.timeout), standard library only. As of 1 December 2026 there is nothing to install for the offline samples; the illustrative provider snippets would need openai and/or anthropic (package names only: uv add openai anthropic or pip install openai anthropic). Save each code block under the file name in its first comment, in one folder, and run it with python3 <file>. The outputs below were produced with Python 3.14. Token counts in the samples are pretend numbers carried by the scripted model.


What you must be able to do after this lesson#

  • Add a reflection gate to the final answer of a tool loop with its own retry cap, so it can never loop forever
  • Keep the best-scoring draft in score-aware reflection and stop on target, plateau, regression or oscillation
  • Measure whether reflection helped by counting tasks it fixed, tasks it broke and the extra cost
  • Build a parallel fan-out with bounded concurrency, per-branch timeouts, a quorum and a shared token pool
  • Aggregate branch results without hiding failures, and refuse to decide on too few votes
  • Wrap an agent as a tool with a child budget carved from the parent's, a depth limit and structured results
  • Check that a child's spend rolls up into the parent and that the parent's context does not grow with the child

Why this matters for an AI engineer#

These three patterns are the first thing people add after a basic loop works, because each promises something real: better quality, lower latency, cleaner structure. Each also hides a way to spend more money for less reliability. A reflection loop that rewrites a correct answer into a wrong one, a fan-out that silently drops the branch that failed, and a "specialist agent" that burns the whole budget out of sight are all common production incidents. The difference between a demo and a shippable version is small, concrete code, and that is what this lesson shows.

You'll hear... You'll understand it after...
"Add a self-critique step, it improves quality." 2.5 Does reflection help?
"The second draft was worse than the first." 2.3 Score-aware reflection
"Run the searches in parallel." Part 3: Parallel fan-out
"One branch failed and nobody noticed." 3.4 Run it
"Make the researcher a tool of the manager agent." Part 4: Agent-as-a-tool
"The sub-agent ran up the bill." 4.3 The code
"Is a manager with sub-agents better than one agent?" Part 5: Choosing

Part 1: What exists already, and the shared loop#

1.1 What the earlier lessons gave you, and what is new#

Pattern Already taught New in this lesson
Reflection and self-critique 08A.10, 4.1: a bounded critique loop with a JSON critic, a reflections list fed back each round, and max_rounds. 4.2: verification against the world. 4.3: when it helps and hurts Reflection as a final-answer gate inside the raw loop; score-aware reflection that returns the best draft and stops on target, plateau, regression or oscillation; measuring whether reflection helped (fixes versus breaks, cost multiple)
Parallel fan-out and aggregate 08A.9, 3.3: sectioning and voting over single model calls, a semaphore, ParallelJobError. 3.6: map-reduce. 08D.3, 2.8: the research-fan-out architecture Each branch is an agent loop; per-branch timeouts; a quorum that cancels stragglers; a shared token pool; partial results that say what is missing; aggregators that refuse to hide gaps
Agent-as-a-tool 08D.3, 2.4: the idea and a code sketch. 08A.10, 5.3: orchestrator-workers A runnable version with a budget carved from the parent's, a depth limit, structured results, spend roll-up, a context-isolation check, and the framework mappings. For the orchestration and multi-agent view, see 08D.1

1.2 The shared mini loop#

All three patterns need a loop to run inside. To keep the lesson self-contained, here is a deliberately small one in the spirit of 08A.2: call the model, run the tools it asks for (concurrently when it asks for several), append results, stop on an answer or a limit. It adds three things the patterns need: an optional Pool that several loops can draw from (the shared budget), an optional final_check (the reflection gate in Part 2), and a clean LoopResult.

python
# mini.py
"""A deliberately small raw tool loop plus a scripted fake model, shared by this lesson's samples.

It is the 08A.2 idea at its smallest: call the model, run the tools it asks for, append results, stop on
an answer or a limit. Everything here is standard library and runs with no key and no network."""
from __future__ import annotations

import asyncio
from dataclasses import dataclass, field
from typing import Awaitable, Callable


@dataclass
class Turn:
    text: str = ""
    calls: list[tuple[str, dict]] = field(default_factory=list)      # [(tool_name, args), ...]
    tokens: int = 100                                                # pretend usage for this model call


def call(tool: str, /, tokens: int = 100, **args) -> Turn:
    return Turn(calls=[(tool, args)], tokens=tokens)


def calls(*pairs: tuple[str, dict], tokens: int = 100) -> Turn:
    return Turn(calls=list(pairs), tokens=tokens)


def say(text: str, tokens: int = 100) -> Turn:
    return Turn(text=text, tokens=tokens)


class ScriptedModel:
    """Replays canned turns, records every message list it was shown, and can simulate latency."""

    def __init__(self, turns: list[Turn], delay: float = 0.0) -> None:
        self.turns, self.delay, self.seen = list(turns), delay, []

    async def __call__(self, messages: list[dict]) -> Turn:
        self.seen.append(len(messages))
        if self.delay:
            await asyncio.sleep(self.delay)
        return self.turns.pop(0) if self.turns else say("[script exhausted]")


class Pool:
    """A token pool that several loops can draw from. This is how budgets are shared and carved up."""

    def __init__(self, limit: int) -> None:
        self.limit, self.used = limit, 0

    @property
    def left(self) -> int:
        return self.limit - self.used

    def spend(self, n: int) -> None:
        self.used += n

    def carve(self, cap: int, fraction: float = 0.5) -> "Pool":
        """A child pool: at most `cap`, and at most `fraction` of what the parent has left."""
        return Pool(min(cap, int(self.left * fraction)))


@dataclass
class LoopResult:
    status: str                  # completed | stopped | failed
    reason: str
    answer: str
    steps: int
    tokens: int
    messages: list[dict]


Tool = Callable[..., Awaitable[str]]


async def run_loop(model: ScriptedModel, tools: dict[str, Tool], task: str, *, system: str = "",
                   max_steps: int = 6, pool: Pool | None = None,
                   final_check: Callable[[str], list[str]] | None = None,
                   max_gate_retries: int = 1) -> LoopResult:
    messages: list[dict] = ([{"role": "system", "content": system}] if system else []) + \
                           [{"role": "user", "content": task}]
    tokens, gate_retries, last_text = 0, 0, ""
    for step in range(1, max_steps + 1):
        if pool is not None and pool.left <= 0:
            return LoopResult("stopped", "token budget", last_text or "(no answer yet)", step - 1, tokens, messages)
        turn = await model(messages)
        tokens += turn.tokens
        if pool is not None:
            pool.spend(turn.tokens)
        if not turn.calls:                                           # the model wants to finish
            last_text = turn.text
            issues = final_check(turn.text) if final_check else []
            if issues and gate_retries < max_gate_retries:           # the reflection gate (Part 1)
                gate_retries += 1
                messages.append({"role": "assistant", "content": turn.text})
                messages.append({"role": "user", "content": "Before you finish, fix: " + "; ".join(issues)})
                continue
            reason = "model answered" if not issues else "answered with unresolved issues: " + "; ".join(issues)
            return LoopResult("completed", reason, turn.text, step, tokens, messages)
        messages.append({"role": "assistant", "content": "", "calls": turn.calls})

        async def one(name: str, args: dict) -> str:
            if name not in tools:
                return f"error: unknown tool {name!r}"
            try:
                return await tools[name](**args)
            except Exception as exc:                                 # errors are data (08A.2)
                return f"error: {type(exc).__name__}: {exc}"

        results = await asyncio.gather(*(one(n, a) for n, a in turn.calls))
        for (name, _), out in zip(turn.calls, results):
            messages.append({"role": "tool", "name": name, "content": out})
    return LoopResult("stopped", "max steps", last_text or "(no answer yet)", max_steps, tokens, messages)

Part 2: Reflection and self-critique#

This Part extends 08A.10, Part 4 (the bounded critique loop, verification against the world and when reflection helps) and the evaluator-optimizer in 08A.9, 3.5 (a score, a plateau stop and a best-draft fallback over single model calls). It adds a gate inside the raw tool loop, score-aware stops, and a way to measure the gain.

2.1 What reflection is, in two sentences#

Reflection means checking a draft against criteria and revising it before it leaves the system. 08A.10, 4.1 covers the standard bounded critique loop and its research roots (Self-Refine and Reflexion), so this lesson does not repeat them. It adds the three things that make reflection safe to ship.

2.2 Reflection as a gate on the final answer#

The simplest place to put reflection is not a separate pipeline but the moment the loop tries to finish. When the model answers with no tool calls, run a check. If it finds problems, add them to the conversation ("Before you finish, fix: ...") and let the loop continue. The retry counts against the same step and token limits, so it cannot loop forever, and the gate has its own retry cap.

run_loop in mini.py already has the hook (final_check and max_gate_retries). The checks run in your code, which is the strongest form of critic (08A.10, 4.2): cheap, deterministic and unable to flatter the draft.

python
# reflect_gate.py
"""Reflection as a gate on the final answer, inside the raw loop (no separate critique pipeline)."""
import asyncio
import re

from mini import ScriptedModel, call, run_loop, say


async def lookup_order(order_id: str) -> str:
    return f"order {order_id}: delivered 2026-11-20, total 84.50, damaged on arrival"


def final_check(answer: str) -> list[str]:
    """Deterministic checks run in YOUR code, before the answer leaves the loop."""
    issues = []
    if not re.search(r"\bA17\b", answer):
        issues.append("name the order id A17")
    if "30 days" not in answer:
        issues.append("state the 30-day refund window")
    if len(answer.split()) > 40:
        issues.append("keep it under 40 words")
    return issues


async def main() -> None:
    tools = {"lookup_order": lookup_order}
    # Run 1: the first answer misses two requirements; the gate sends it back once; the revision passes.
    m1 = ScriptedModel([call("lookup_order", order_id="A17"),
                        say("Sorry about the damage, we will refund you."),
                        say("Order A17 is refunded; our policy allows returns within 30 days.")])
    r1 = await run_loop(m1, tools, "Reply to the customer.", final_check=final_check)
    print("run 1:", r1.status, "|", r1.reason, "| steps:", r1.steps)
    print("       answer:", r1.answer)
    print("       model was shown", m1.seen, "messages on each call")

    # Run 2: the model ignores the feedback. The gate has a retry cap, so it cannot loop forever,
    # and the unresolved issues are reported instead of hidden.
    m2 = ScriptedModel([say("We will refund you."), say("Refund coming soon.")])
    r2 = await run_loop(m2, tools, "Reply to the customer.", final_check=final_check)
    print("run 2:", r2.status, "|", r2.reason)


asyncio.run(main())
Output · real, run with Python 3.14 on 1 December 20264 lines
run 1: completed | model answered | steps: 3
       answer: Order A17 is refunded; our policy allows returns within 30 days.
       model was shown [1, 3, 5] messages on each call
run 2: completed | answered with unresolved issues: name the order id A17; state the 30-day refund window

Run 1: the first answer missed the order id and the policy window, so the gate sent it back once; the third model call saw 5 messages (the earlier three plus the draft and the fix request), and the revision passed. Run 2: the model ignored the feedback twice. The gate stopped at its retry cap and the run was completed with the unresolved issues listed in the reason, not hidden. That is the contract: a gate can improve an answer or flag it, never trap the run.

2.3 Score-aware reflection: best-of, not last-of#

The gate above asks "pass or fail?". Many checks give a score (the share of rubric items met), and a score unlocks four decisions the pass/fail version cannot make. A revision can make things worse, so return the best draft seen, not the last one. And the loop needs more stop reasons than "max rounds":

Stop reason Meaning Why it matters
target reached Score is at or above the target The normal success
plateau Score gained less than min_gain More rounds are paying for nothing
regression A revision scored lower than the best so far The revision broke something; keep the best
oscillation A draft identical to an earlier one reappeared The loop is going in circles
max rounds The cap was hit The backstop

The critic here is rubric(), a deterministic scorer with four yes-or-no checks. The generator is scripted so each case is exactly reproducible.

python
# reflect_score.py
"""Score-aware reflection: keep the BEST draft, and stop on target, plateau, regression or oscillation."""
from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Callable


def rubric(draft: str) -> tuple[float, list[str]]:
    """A deterministic critic: four yes/no checks, score = share passed."""
    checks = {
        "name the order id A17": bool(re.search(r"\bA17\b", draft)),
        "state the 30-day window": "30 days" in draft,
        "give the refund amount": "84.50" in draft,
        "stay under 30 words": len(draft.split()) <= 30,
    }
    issues = [msg for msg, ok in checks.items() if not ok]
    return 1 - len(issues) / len(checks), issues


@dataclass
class Round:
    n: int
    draft: str
    score: float
    issues: list[str]


@dataclass
class Reflection:
    best: Round
    stop_reason: str
    rounds: list[Round]


def reflect(generate: Callable[[list[str]], str], critic: Callable[[str], tuple[float, list[str]]], *,
            max_rounds: int = 4, target: float = 1.0, min_gain: float = 0.05) -> Reflection:
    rounds: list[Round] = []
    feedback: list[str] = []
    best: Round | None = None
    reason = "max rounds"
    for n in range(1, max_rounds + 1):
        draft = generate(feedback)
        score, issues = critic(draft)
        this = Round(n, draft, score, issues)
        rounds.append(this)
        if any(r.draft == draft for r in rounds[:-1]):                    # same draft again: going in circles
            reason = "oscillation (a draft repeated)"
            break
        if best is not None and score < best.score:                       # the revision made it worse
            reason = f"regression ({score:.2f} < best {best.score:.2f}); keeping round {best.n}"
            break
        gain = score - (best.score if best else 0.0)
        if best is None or score > best.score:
            best = this
        if score >= target:
            reason = "target reached"
            break
        if n > 1 and gain < min_gain:
            reason = f"plateau (gain {gain:.2f} < {min_gain})"
            break
        feedback = issues                                                 # what the next round must fix
    assert best is not None
    return Reflection(best, reason, rounds)


def scripted(drafts: list[str]) -> Callable[[list[str]], str]:
    it = iter(drafts)
    return lambda feedback: next(it)


CASES = {
    "converges": [
        "Sorry about that, a refund is on its way.",
        "Order A17 refund is on its way, sorry about that.",
        "Order A17: 84.50 refunded; we allow returns within 30 days.",
    ],
    "plateau": [
        "Order A17 will be refunded soon.",
        "Your order A17 is going to be refunded very soon.",
    ],
    "regression": [
        "Order A17 refunded, 84.50 returned.",
        "Dear valued customer, thank you for your patience while we process the refund for you today.",
    ],
    "oscillation": [
        "Order A17 refunded, sorry for the damage.",
        "Order A17 refunded within 30 days, sorry for the damage.",
        "Order A17 refunded, sorry for the damage.",
    ],
}

if __name__ == "__main__":
    for name, drafts in CASES.items():
        result = reflect(scripted(drafts), rubric)
        print(f"== {name}: stop = {result.stop_reason}")
        for r in result.rounds:
            mark = "  <- returned" if r is result.best else ""
            print(f"   round {r.n}: score {r.score:.2f}  issues={r.issues}{mark}")
Output · real, run with Python 3.14 on 1 December 202614 lines
== converges: stop = target reached
   round 1: score 0.25  issues=['name the order id A17', 'state the 30-day window', 'give the refund amount']
   round 2: score 0.50  issues=['state the 30-day window', 'give the refund amount']
   round 3: score 1.00  issues=[]  <- returned
== plateau: stop = plateau (gain 0.00 < 0.05)
   round 1: score 0.50  issues=['state the 30-day window', 'give the refund amount']  <- returned
   round 2: score 0.50  issues=['state the 30-day window', 'give the refund amount']
== regression: stop = regression (0.25 < best 0.75); keeping round 1
   round 1: score 0.75  issues=['state the 30-day window']  <- returned
   round 2: score 0.25  issues=['name the order id A17', 'state the 30-day window', 'give the refund amount']
== oscillation: stop = oscillation (a draft repeated)
   round 1: score 0.50  issues=['state the 30-day window', 'give the refund amount']
   round 2: score 0.75  issues=['give the refund amount']  <- returned
   round 3: score 0.50  issues=['state the 30-day window', 'give the refund amount']

Read the four cases:

  • converges: 0.25, then 0.50, then 1.00 (the target). The returned draft is round 3.
  • plateau: two drafts at 0.50. The second added nothing, so the loop stopped instead of spending a third round.
  • regression: round 2 rewrote a decent draft (0.75) into a polite, empty one (0.25). The loop kept round 1. A loop that returns the last draft would have shipped the worse one.
  • oscillation: the generator flipped between two drafts, and the repeat was caught. Round 2 (0.75) is returned.

2.4 Where the critic's evidence comes from#

A critic that sees only the draft will tend to approve it. The rules for a critic that earns its cost:

  1. Deterministic checks first. Format, required fields, numbers recomputed, claims looked up. These are free and cannot be charmed.
  2. A model critic only for what code cannot check (tone, completeness against a rubric), with a checklist in the prompt so it judges against criteria instead of vibes. Treat it as an LLM judge and validate it (10A.4 and 10A.5 cover that).
  3. Give the critic different evidence from the generator. Same model plus same context gives correlated blind spots (08D.3, 2.9). The strongest critics get tools or data the generator did not, such as the order record, so they can check rather than re-read.
  4. A cheaper or different model is fine for the critic on routine checks, because it judges rather than creates.

Here are the two raw provider calls for a critic. They need keys, so they are illustrative; the parsing is the same on both. (The file also holds the tool formats and parallel flags used in later parts.)

python
# provider_snippets.py
"""ILLUSTRATIVE provider code for this lesson (needs OPENAI_API_KEY / ANTHROPIC_API_KEY to run).
Three things: a critic call on a cheaper model, the two wire formats of an agent exposed as a tool,
and the flags that control model-emitted parallel tool calls."""
import json

CRITIC = ("You are a strict reviewer. Reply with ONLY a JSON object: "
          '{"score": 0.0-1.0, "issues": ["..."]}. Judge only against the checklist you are given.')


def critique_openai(client, draft: str, checklist: str) -> dict:
    resp = client.responses.create(
        model="gpt-6-luna", instructions=CRITIC, store=False, max_output_tokens=500,
        input=f"Checklist:\n{checklist}\n\nDraft:\n{draft}")
    return json.loads(resp.output_text)                    # a real loop also handles bad JSON and incomplete


def critique_anthropic(client, draft: str, checklist: str) -> dict:
    resp = client.messages.create(
        model="claude-haiku-5-5", max_tokens=500, system=CRITIC,
        messages=[{"role": "user", "content": f"Checklist:\n{checklist}\n\nDraft:\n{draft}"}])
    return json.loads("".join(b.text for b in resp.content if b.type == "text"))


DELEGATE_PARAMS = {
    "type": "object",
    "properties": {"task": {"type": "string", "description":
        "A complete, self-contained brief: the question, the sources to use, the format of the answer. "
        "The specialist has not seen this conversation."}},
    "required": ["task"], "additionalProperties": False,
}
DESCRIPTION = ("Delegate ONE self-contained research question to a specialist that searches the docs. "
               "Returns JSON with status, a short summary and whether the result is partial. "
               "Use it for questions that need several searches; do not use it for a single lookup.")

OPENAI_AGENT_TOOL = {"type": "function", "name": "researcher", "description": DESCRIPTION,
                     "parameters": DELEGATE_PARAMS, "strict": True}          # Responses API function tool
ANTHROPIC_AGENT_TOOL = {"name": "researcher", "description": DESCRIPTION,
                        "input_schema": DELEGATE_PARAMS}                     # Messages API tool

# Model-emitted parallel calls (several tool calls in ONE turn) are a per-request setting:
OPENAI_PARALLEL_OFF = {"parallel_tool_calls": False}                         # a parameter of responses.create
ANTHROPIC_PARALLEL_OFF = {"tool_choice": {"type": "auto", "disable_parallel_tool_use": True}}

if __name__ == "__main__":
    print(json.dumps({"openai": OPENAI_AGENT_TOOL["name"], "anthropic": ANTHROPIC_AGENT_TOOL["name"]}))

2.5 Does reflection help?#

You cannot tell by reading outputs. Compare the same tasks with and without reflection and count three things: tasks reflection fixed, tasks it broke, and what it cost. The script uses scripted per-task results as stand-ins for graded runs; the method is the point.

python
# reflect_ablation.py
"""Did reflection help? Compare the SAME tasks with and without it, and count fixes and breaks.
The per-task results below are scripted stand-ins for graded runs; the method is the point."""

# (task, passed without reflection, passed with reflection, extra tokens the reflection spent)
RESULTS = [
    ("t1", False, True, 900), ("t2", False, True, 850), ("t3", True, True, 700), ("t4", True, False, 950),
    ("t5", False, False, 1000), ("t6", True, True, 650), ("t7", False, True, 800), ("t8", True, True, 600),
]
base_tokens_per_task = 1200

fixed = sum(1 for _, a, b, _ in RESULTS if not a and b)
broken = sum(1 for _, a, b, _ in RESULTS if a and not b)
rate_without = sum(a for _, a, _, _ in RESULTS) / len(RESULTS)
rate_with = sum(b for _, _, b, _ in RESULTS) / len(RESULTS)
cost_multiple = 1 + sum(x for *_, x in RESULTS) / (base_tokens_per_task * len(RESULTS))

print(f"pass rate without reflection: {rate_without:.2f}   with: {rate_with:.2f}")
print(f"fixed by reflection: {fixed}   broken by reflection: {broken}   net: {fixed - broken:+d}")
print(f"token cost multiple: x{cost_multiple:.2f}   (8 tasks is far too few to trust; see 10A.7 Part 5)")
Output · real, run with Python 3.14 on 1 December 20263 lines
pass rate without reflection: 0.50   with: 0.75
fixed by reflection: 3   broken by reflection: 1   net: +2
token cost multiple: x1.67   (8 tasks is far too few to trust; see 10A.7 Part 5)

Pass rate rose from 0.50 to 0.75: three tasks fixed, one broken, net plus two, for roughly 1.67 times the token cost. The "broken" column is the one teams forget to count. Eight tasks is far too few to trust the numbers (10A.7, Part 5 says how many you need and why intervals matter).

2.6 Reflection pitfalls#

Pitfall Symptom Fix
The critic always says "revise" Rewrites forever; cost climbs A target score, min_gain, a round cap and plateau detection
The revision breaks something right The final answer is worse than draft 1 Return the best draft; keep "preserve what was right" in the revise prompt
Same blind spot The critic approves what the generator got wrong Different evidence (tools, data) or deterministic checks
Vague criteria The critic nitpicks style endlessly A checklist with testable items
Unlogged critiques Cannot tell if reflection helps Log every round, score and issue; run the ablation
Reflection hides a missing capability Quality plateaus below the target Fix the retrieval or the tool, not the critic

Part 3: Parallel fan-out and aggregate#

This Part extends 08A.9, 3.3 (sectioning and voting over single model calls) and 08D.3, 2.8 (the research fan-out architecture). It is self-contained: it defines the pattern, then adds the controls needed when each branch is a whole agent loop.

3.1 The shape#

Fan-out and aggregate splits independent work into branches, runs them at the same time, and combines the results. It buys latency: the run takes about as long as the slowest branch, not the sum. It costs money: the tokens are the sum of the branches plus the aggregator. 08A.9, 3.3 teaches sectioning (different subtasks) and voting (the same task several times) over single model calls, with a semaphore and ParallelJobError, and 08D.3, 2.8 shows it as a multi-agent architecture. The question this part answers is the next one: what do you do when branches are whole agent loops and some of them fail, stall, or run out of budget?

flowchart TD
    T["Task"] --> S["Split into independent branches"]
    S --> B1["Branch 1: agent loop"]
    S --> B2["Branch 2: agent loop"]
    S --> B3["Branch 3: agent loop"]
    B1 --> A["Aggregate"]
    B2 --> A
    B3 --> A
    A --> R["Result + what is missing"]

Use fan-out when the subtasks are independent (no branch needs another's output), when breadth matters ("compare all five vendors"), or when latency matters and the branches are slow. Do not use it for steps that depend on each other (that is a chain), or when the extra cost is not worth the speed.

3.2 Six decisions that make it production-safe#

Decision Question This lesson's answer
Concurrency bound How many at once? A semaphore, sized to rate limits (03.9)
Per-branch timeout What if one hangs? asyncio.timeout per branch; the branch becomes a timeout outcome, not a hang
Quorum Must we wait for every branch? Stop at k usable results and cancel the stragglers
Shared budget Who pays? One token Pool all branches draw from; branches that start after it is empty are skipped
Partial results What if one fails? Each branch returns an Outcome with a status (ok, partial, error, timeout, cancelled, skipped); nothing is silently dropped
Aggregation How to combine honestly? Aggregators that list what is missing and refuse to decide on too few votes

08D.3, 3.6 discusses partial failure for multi-agent systems in general; this is the same idea made executable.

3.3 The code#

fan_out returns outcomes in input order, not finish order, so the result is deterministic. Branches are tiny agent loops built from mini.py. A branch that stops early (budget, steps) raises Partial, so its findings are kept and marked partial rather than lost.

python
# fanout.py
"""Fan out to N branches (each one a small agent loop), then aggregate. Standard library only.

New compared with a plain gather: per-branch timeouts, a quorum that cancels stragglers, a shared token
pool, partial results that say what is missing, and aggregators that refuse to hide the gaps."""
from __future__ import annotations

import asyncio
import time
from collections import Counter
from dataclasses import dataclass
from typing import Awaitable, Callable

from mini import Pool, ScriptedModel, call, run_loop, say


@dataclass
class Outcome:
    name: str
    status: str                     # ok | partial | error | timeout | cancelled | skipped
    value: str | None = None
    detail: str = ""
    tokens: int = 0


BranchFn = Callable[[], Awaitable[tuple[str, int]]]          # returns (text, tokens used)


class Partial(Exception):
    """A branch that stopped early (budget, steps) but has something worth keeping."""

    def __init__(self, text: str, tokens: int, why: str) -> None:
        super().__init__(why)
        self.text, self.tokens, self.why = text, tokens, why


async def fan_out(branches: dict[str, BranchFn], *, max_concurrency: int = 3, branch_timeout: float = 1.0,
                  quorum: int | None = None, pool: Pool | None = None) -> list[Outcome]:
    sem = asyncio.Semaphore(max_concurrency)
    outcomes: dict[str, Outcome] = {}

    async def run_one(name: str, fn: BranchFn) -> None:
        async with sem:
            if pool is not None and pool.left <= 0:                  # shared budget already spent
                outcomes[name] = Outcome(name, "skipped", detail="token pool exhausted before start")
                return
            try:
                async with asyncio.timeout(branch_timeout):
                    text, tokens = await fn()
                outcomes[name] = Outcome(name, "ok", text, tokens=tokens)
            except Partial as p:
                outcomes[name] = Outcome(name, "partial", p.text, detail=p.why, tokens=p.tokens)
            except TimeoutError:
                outcomes[name] = Outcome(name, "timeout", detail=f"no answer in {branch_timeout}s")
            except asyncio.CancelledError:
                outcomes[name] = Outcome(name, "cancelled", detail="quorum reached; straggler cancelled")
                raise
            except Exception as exc:
                outcomes[name] = Outcome(name, "error", detail=f"{type(exc).__name__}: {exc}")

    tasks = {name: asyncio.create_task(run_one(name, fn)) for name, fn in branches.items()}
    pending = set(tasks.values())
    while pending:
        done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
        ok = sum(1 for o in outcomes.values() if o.status == "ok")
        if quorum is not None and ok >= quorum and pending:
            for t in pending:
                t.cancel()
            await asyncio.gather(*pending, return_exceptions=True)
            break
    return [outcomes[n] for n in branches]                           # input order, not finish order


def missing(outcomes: list[Outcome]) -> list[str]:
    return [f"{o.name} ({o.status}: {o.detail})" for o in outcomes if o.status != "ok"]



def aggregate_concat(outcomes: list[Outcome]) -> str:
    parts = [f"[{o.name}]{' (partial)' if o.status == 'partial' else ''} {o.value}"
             for o in outcomes if o.status in ("ok", "partial")]
    gaps = missing(outcomes)
    return "\n".join(parts) + (f"\nINCOMPLETE. Missing: {'; '.join(gaps)}" if gaps else "")


def aggregate_vote(outcomes: list[Outcome], min_votes: int = 2) -> str:
    votes = [o.value for o in outcomes if o.status == "ok"]
    if len(votes) < min_votes:
        return f"NO DECISION: only {len(votes)} usable vote(s), need {min_votes}"
    (winner, n), = Counter(votes).most_common(1)
    return f"{winner} ({n} of {len(votes)} usable votes; {len(outcomes) - len(votes)} branch(es) missing)"


def aggregator_prompt(task: str, outcomes: list[Outcome]) -> str:
    """What the aggregating model is shown. It is told exactly what is missing."""
    body = "\n".join(f"- {o.name}{' (partial)' if o.status == 'partial' else ''}: {o.value}"
                     for o in outcomes if o.status in ("ok", "partial"))
    gaps = missing(outcomes)
    note = ("\nMissing branches: " + "; ".join(gaps) + "\nDo not present the answer as complete. Say what is missing."
            if gaps else "")
    return f"Task: {task}\nBranch results:\n{body}{note}"


# ---------- branches: each is a tiny agent loop with its own scripted model ----------------------
async def docs_tool(query: str) -> str:
    await asyncio.sleep(0.05)
    return f"doc about {query}"


def agent_branch(topic: str, delay: float = 0.0, fail: bool = False, tokens: int = 100,
                 pool: Pool | None = None) -> BranchFn:
    async def branch() -> tuple[str, int]:
        if fail:
            raise RuntimeError("search backend returned 503")
        model = ScriptedModel([call("search", tokens=tokens, query=topic), say(f"findings on {topic}", tokens=tokens)],
                              delay=delay)
        res = await run_loop(model, {"search": docs_tool}, f"research {topic}", pool=pool)   # the loop charges the pool
        if res.status != "completed":
            raise Partial(res.answer, res.tokens, res.reason)
        return res.answer, res.tokens
    return branch


async def main() -> None:
    topics = ["pricing", "security", "roadmap"]

    print("== 1 all branches succeed (each branch is a 2-step agent, 0.15s per model call)")
    t0 = time.perf_counter()
    out = await fan_out({t: agent_branch(t, delay=0.15) for t in topics})
    elapsed = time.perf_counter() - t0
    sequential = 3 * (0.15 + 0.05 + 0.15)
    print(aggregate_concat(out))
    print("   faster than running them one after another:", elapsed < sequential * 0.6)

    print("== 2 one branch errors, one is too slow: a PARTIAL result that says so")
    out = await fan_out({"pricing": agent_branch("pricing"), "security": agent_branch("security", fail=True),
                         "roadmap": agent_branch("roadmap", delay=2.0)}, branch_timeout=0.4)
    print(aggregate_concat(out))
    print("   --- what the aggregating model would be shown:")
    print("   " + aggregator_prompt("Summarise the product", out).replace("\n", "\n   "))

    print("== 3 quorum: stop at 2 usable results and cancel the straggler")
    t0 = time.perf_counter()
    out = await fan_out({"pricing": agent_branch("pricing"), "security": agent_branch("security"),
                         "roadmap": agent_branch("roadmap", delay=3.0)}, branch_timeout=5.0, quorum=2)
    print("   statuses:", {o.name: o.status for o in out})
    print("   returned long before the straggler could finish:", time.perf_counter() - t0 < 1.0)

    print("== 4 shared token pool of 250, one branch at a time, 100 tokens per model call (200 per branch)")
    pool = Pool(250)
    out = await fan_out({t: agent_branch(t, pool=pool) for t in topics}, max_concurrency=1, pool=pool)
    print("   statuses:", {o.name: o.status for o in out}, "| pool used:", pool.used, "of", pool.limit)
    print(aggregate_concat(out))

    print("== 5 voting: the same question asked three times")
    async def vote_branch(answer: str | None) -> tuple[str, int]:
        if answer is None:
            raise RuntimeError("model error")
        return answer, 100
    votes = {"v1": lambda: vote_branch("positive"), "v2": lambda: vote_branch("positive"),
             "v3": lambda: vote_branch("negative")}
    print("   ", aggregate_vote(await fan_out(votes)))
    votes = {"v1": lambda: vote_branch("positive"), "v2": lambda: vote_branch(None), "v3": lambda: vote_branch(None)}
    print("   ", aggregate_vote(await fan_out(votes)))


if __name__ == "__main__":
    asyncio.run(main())

3.4 Run it#

Five scenarios, each exercising one decision. Timing checks print only a true/false (not the milliseconds) so the output is the same on every machine.

Output · real, run with Python 3.14 on 1 December 202625 lines
== 1 all branches succeed (each branch is a 2-step agent, 0.15s per model call)
[pricing] findings on pricing
[security] findings on security
[roadmap] findings on roadmap
   faster than running them one after another: True
== 2 one branch errors, one is too slow: a PARTIAL result that says so
[pricing] findings on pricing
INCOMPLETE. Missing: security (error: RuntimeError: search backend returned 503); roadmap (timeout: no answer in 0.4s)
   --- what the aggregating model would be shown:
   Task: Summarise the product
   Branch results:
   - pricing: findings on pricing
   Missing branches: security (error: RuntimeError: search backend returned 503); roadmap (timeout: no answer in 0.4s)
   Do not present the answer as complete. Say what is missing.
== 3 quorum: stop at 2 usable results and cancel the straggler
   statuses: {'pricing': 'ok', 'security': 'ok', 'roadmap': 'cancelled'}
   returned long before the straggler could finish: True
== 4 shared token pool of 250, one branch at a time, 100 tokens per model call (200 per branch)
   statuses: {'pricing': 'ok', 'security': 'partial', 'roadmap': 'skipped'} | pool used: 300 of 250
[pricing] findings on pricing
[security] (partial) (no answer yet)
INCOMPLETE. Missing: security (partial: token budget); roadmap (skipped: token pool exhausted before start)
== 5 voting: the same question asked three times
    positive (2 of 3 usable votes; 0 branch(es) missing)
    NO DECISION: only 1 usable vote(s), need 2

How to read it:

  1. All succeed. Three two-step agent branches ran together and finished far faster than running one after another would have taken.
  2. One error, one timeout. The aggregate holds only pricing and says INCOMPLETE with both reasons. The model-based aggregator is shown a prompt that lists the missing branches and says "do not present the answer as complete". A silent merge would have produced a confident summary of one third of the data.
  3. Quorum. With a quorum of 2, the first two branches finished and the slow roadmap branch was cancelled (status cancelled). The run returned long before the straggler could finish.
  4. Shared pool. A pool of 250 tokens, one branch at a time, 100 tokens per model call. pricing finished (200 tokens). security started with 50 left, made one call (pool now at 300), and stopped on its next check as partial. roadmap found the pool empty and was skipped. The pool shows 300 of 250 used: one call overshot, exactly the effect described in 08A.3, 3.4.
  5. Voting. Two "positive" and one "negative" give a 2-of-3 majority. When two branches fail, one vote remains and the aggregator returns NO DECISION rather than pretending one vote is a majority.

3.5 Aggregation strategies, and how aggregation fails#

Strategy When How it fails
Concatenate with labels Sections or independent findings Reader assumes completeness; add the missing list (as in code)
Majority vote Short, comparable answers (labels, numbers) Ties; correlated errors (all branches wrong the same way); too few votes
Reduce with a model Open-ended findings that must be merged Drops minority findings, merges contradictions, invents a smooth story
Judge and select Several candidate drafts, one to ship The judge's bias; the same blind spot as the generators

Aggregation is a new place to be wrong that the branches did not have. Evaluate branch quality and end-to-end quality separately (08A.9, 3.3 makes the same point): a merge can lose information that every branch got right.

3.6 Two kinds of parallel: model-emitted and orchestrated#

Do not confuse these.

  • Model-emitted parallel tool calls: the model returns several tool calls in one turn, and your loop runs them together (08A.2, 4.1). The model decides. It is controlled per request: parallel_tool_calls (OpenAI Responses) or disable_parallel_tool_use inside tool_choice (Anthropic); see the constants in provider_snippets.py.
  • Orchestrated fan-out: your code splits the task and runs branches, each with its own loop. You decide. It is what this part builds.

Both multiply cost and both run into rate limits. A 429 storm from an unbounded fan-out is the classic failure; bound concurrency with a semaphore (03.9), share one budget, and note that org-level rate limits across teams are 11B.7's subject.


Part 4: Agent-as-a-tool#

This Part extends 08D.3, 2.4, which introduces the idea with a short sketch. It is self-contained: it defines the pattern, then builds the runnable version with the controls the sketch leaves out.

4.1 What it is#

An agent-as-a-tool registers a complete agent in another agent's tool list. The parent sees one tool call; underneath, a full loop runs, with its own instructions, tools and context. The parent gets back a result, and the child's intermediate steps never enter the parent's history. The parent stays in charge of the conversation. That is the difference from a handoff, where control moves to the other agent; the OpenAI Agents SDK documentation draws the same line: with agents as tools, a central agent orchestrates specialists "instead of handing off control", and receives each specialist's output back as a tool result.

It is the lightest form of multi-agent design: no new protocol, no shared state, just a function that happens to run a loop. 08D.3, 2.4 introduces it and 08D.1 gives the wider decision of when several agents earn their cost.

4.2 What 08D.3 sketched, and what is missing#

08D.3, 2.4 shows an agent_as_tool wrapper that runs a child and returns a summary. A wrapper that only does that has four production gaps, and this lesson closes each.

Gap What goes wrong The fix in the code below
No budget for the child A child can spend the parent's whole budget out of sight parent_pool.carve(cap, fraction): a slice, never the whole wallet
No depth limit A child that can call itself recurses MAX_DEPTH: below it the agent-tool is simply not offered
Unstructured result The parent cannot tell success from partial from error A JSON result with status, partial, summary, steps, tokens
Hidden spend and context Cost and growth are invisible Child spend rolls up into the parent's pool; an invariant checks that the parent's history does not grow with the child

4.3 The code and what it prints#

as_tool(spec, parent_pool, depth) returns an async tool function. It carves a child pool, withholds the agent-tool at the depth limit, runs the child loop with a timeout, rolls the child's spend into the parent, and returns structured JSON. The model-facing part is the description on AgentSpec: the parent reads it to decide when to delegate (4.4).

python
# agent_tool.py
"""An agent as a tool: the parent sees ONE tool call; underneath, a whole child loop runs.

What makes it safe to ship: the child gets a carved-out slice of the parent's budget, a depth limit stops
runaway recursion, errors and partial work come back as structured data, and the parent's context only
grows by the summary, never by the child's transcript."""
from __future__ import annotations

import asyncio
import json
from dataclasses import dataclass, field
from typing import Callable

from mini import Pool, ScriptedModel, Tool, call, calls, run_loop, say

MAX_DEPTH = 2                      # parent = depth 0, its sub-agents = depth 1, theirs = depth 2


@dataclass
class AgentSpec:
    name: str
    description: str                                   # the parent model reads this to decide when to delegate
    make_model: Callable[[], ScriptedModel]            # in production: a client + system prompt for this role
    tools: dict[str, Tool] = field(default_factory=dict)
    sub_agents: list["AgentSpec"] = field(default_factory=list)
    child_token_cap: int = 600                         # never give a child more than this
    max_steps: int = 5


STATS = {"child_runs": 0, "child_messages": 0, "withheld": 0, "deepest": 0}        # so the demo can show context isolation


def as_tool(spec: AgentSpec, parent_pool: Pool, depth: int) -> Tool:
    """Wrap `spec` as an async tool function. `depth` is how deep the CALLER is."""

    async def delegate(task: str) -> str:
        pool = parent_pool.carve(spec.child_token_cap, fraction=0.5)      # a slice, not the whole wallet
        tools = dict(spec.tools)
        STATS["deepest"] = max(STATS["deepest"], depth + 1)
        if depth + 1 < MAX_DEPTH:                                         # only below the depth limit may it delegate
            tools.update({s.name: as_tool(s, pool, depth + 1) for s in spec.sub_agents})
        elif spec.sub_agents:
            STATS["withheld"] += 1                                        # the agent-tool is simply not offered
        try:
            res = await asyncio.wait_for(
                run_loop(spec.make_model(), tools, task, pool=pool, max_steps=spec.max_steps), timeout=2.0)
        except asyncio.TimeoutError:
            return json.dumps({"agent": spec.name, "status": "error", "partial": False,
                               "summary": "child timed out", "tokens": pool.used})
        parent_pool.spend(pool.used)                                      # child spend rolls up to the parent
        STATS["child_runs"] += 1
        STATS["child_messages"] += len(res.messages)
        return json.dumps({"agent": spec.name, "status": res.status, "partial": res.status != "completed",
                           "summary": res.answer[:300], "steps": res.steps, "tokens": res.tokens})

    return delegate


async def search_docs(query: str) -> str:
    await asyncio.sleep(0.02)
    return f"doc about {query}"


def researcher_model() -> ScriptedModel:
    return ScriptedModel([call("search_docs", query="refund policy"), call("search_docs", query="shipping"),
                          say("Refunds within 30 days; shipping takes 3 to 5 days.")])


def greedy_model() -> ScriptedModel:
    """A badly behaved child: it tries to call itself again and again, then never answers."""
    return ScriptedModel([call("researcher", task="go deeper")] * 2 + [call("search_docs", query="x")] * 6)


RESEARCHER = AgentSpec("researcher", "Looks things up in the docs and returns a short, cited summary.",
                       researcher_model, tools={"search_docs": search_docs})
RESEARCHER.sub_agents = [RESEARCHER]                    # allowed on paper; the depth limit stops it


async def main() -> None:
    print("== 1 the parent delegates twice in ONE turn; both children run concurrently")
    parent_pool = Pool(5_000)
    tools = {"researcher": as_tool(RESEARCHER, parent_pool, depth=0)}
    parent = ScriptedModel([calls(("researcher", {"task": "refund rules"}), ("researcher", {"task": "shipping rules"})),
                            say("Summary: refunds in 30 days, shipping 3 to 5 days.")])
    res = await run_loop(parent, tools, "What do customers need to know?", pool=parent_pool)
    print("   parent:", res.status, "|", res.answer)
    for m in res.messages:
        if m["role"] == "tool":
            print("   parent saw:", m["content"])
    print(f"   parent history: {len(res.messages)} messages; children ran {STATS['child_runs']} loops "
          f"with {STATS['child_messages']} messages the parent never saw")
    print(f"   parent pool: {parent_pool.used} used (parent's own calls + both children rolled up)")

    print("== 2 a child that misbehaves: recursion is cut at the depth limit, budget is cut at its slice")
    STATS.update(child_runs=0, child_messages=0, withheld=0, deepest=0)
    greedy = AgentSpec("researcher", "greedy", greedy_model, tools={"search_docs": search_docs}, child_token_cap=300)
    greedy.sub_agents = [greedy]
    parent_pool = Pool(5_000)
    parent = ScriptedModel([call("researcher", task="research everything"), say("I got a partial result.")])
    res = await run_loop(parent, {"researcher": as_tool(greedy, parent_pool, depth=0)}, "Go.", pool=parent_pool)
    out = json.loads([m for m in res.messages if m["role"] == "tool"][0]["content"])
    print("   child returned:", out)
    print("   children ran:", STATS["child_runs"], "| deepest level reached:", STATS["deepest"],
          "| times the agent-tool was withheld at the depth limit:", STATS["withheld"])
    print("   parent pool used:", parent_pool.used, "of", parent_pool.limit)

    print("== 3 a child that crashes: the parent gets an error result, not an exception")
    async def broken(task: str) -> str:
        raise RuntimeError("child blew up")
    parent = ScriptedModel([call("researcher", task="x"), say("The specialist failed; I will tell the user.")])
    res = await run_loop(parent, {"researcher": broken}, "Go.")
    print("   tool message:", [m["content"] for m in res.messages if m["role"] == "tool"][0])
    print("   final answer:", res.answer)


if __name__ == "__main__":
    asyncio.run(main())
Output · real, run with Python 3.14 on 1 December 202613 lines
== 1 the parent delegates twice in ONE turn; both children run concurrently
   parent: completed | Summary: refunds in 30 days, shipping 3 to 5 days.
   parent saw: {"agent": "researcher", "status": "completed", "partial": false, "summary": "Refunds within 30 days; shipping takes 3 to 5 days.", "steps": 3, "tokens": 300}
   parent saw: {"agent": "researcher", "status": "completed", "partial": false, "summary": "Refunds within 30 days; shipping takes 3 to 5 days.", "steps": 3, "tokens": 300}
   parent history: 4 messages; children ran 2 loops with 10 messages the parent never saw
   parent pool: 800 used (parent's own calls + both children rolled up)
== 2 a child that misbehaves: recursion is cut at the depth limit, budget is cut at its slice
   child returned: {'agent': 'researcher', 'status': 'stopped', 'partial': True, 'summary': '(no answer yet)', 'steps': 2, 'tokens': 200}
   children ran: 3 | deepest level reached: 2 | times the agent-tool was withheld at the depth limit: 2
   parent pool used: 500 of 5000
== 3 a child that crashes: the parent gets an error result, not an exception
   tool message: error: RuntimeError: child blew up
   final answer: The specialist failed; I will tell the user.

Reading the three scenarios:

  1. Concurrent delegation. The parent asked for two researcher runs in one turn, and run_loop ran them together. The parent saw only two small JSON results. Its history is 4 messages, while the children ran 2 loops with 10 messages the parent never saw. The parent's pool shows 800 tokens used: its own two calls (200) plus both children (300 each) rolled up. Spend is visible even though context is isolated.
  2. A misbehaving child. The child tried to delegate to itself and then loop on searches. The depth limit cut recursion: the deepest level reached was 2, and the agent-tool was withheld twice. The child's budget slice stopped it. It returned status: stopped, partial: true, and the parent kept a result it could reason about instead of an exception. Note the summary, (no answer yet): it is honest but not helpful. A better partial result carries the child's findings, which is the contract in 08A.3, 6.2.
  3. A crashing child. The exception became an error result the parent model read, and the parent still produced a final answer. This is "errors are data" from 08A.2 applied to a whole agent.

4.4 Writing the tool the parent will read#

The parent chooses whether to delegate by reading the tool's name, description and parameters, so those are prompts. A bad one produces vague delegation ("research stuff") and a child that guesses. A good one says what the specialist is for, when not to use it, what to put in task, and what comes back. The wire formats for both providers are in the snippet above (OPENAI_AGENT_TOOL, ANTHROPIC_AGENT_TOOL); the lasting points are in the parameter description: the specialist has not seen this conversation, so the task must be a complete, self-contained brief. The fix for most "the subagent did the wrong thing" bugs is a better brief.

4.5 How frameworks expose it#

After the plain version, the frameworks are easy to read. Checked against each project's documentation on 1 December 2026:

OpenAI Agents SDK Claude Agent SDK
How you declare it agent.as_tool(tool_name=..., tool_description=...), with options such as custom_output_extractor, is_enabled, needs_approval, parameters, session and on_stream (docs) agents={"name": AgentDefinition(description=..., prompt=..., tools=[...], model=...)} in the options; Claude invokes them through the Agent tool (docs)
What the child receives The tool's input A fresh context: only its own system prompt and the Agent tool's prompt string (a fork copies the conversation instead)
What the parent receives The sub-agent's output as a tool result, optionally post-processed The subagent's final message; intermediate tool calls and results stay inside
Limits Per-run max_turns on the runner (08A.3, Part 7) maxTurns per agent (output marked partial at the limit); env CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH (default 3), CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS (default 20); max_budget_usd includes subagent spend

Map them back to the plain version: custom_output_extractor is your result-shaping step; tools=[...] on an AgentDefinition is least privilege for the child; the depth, concurrency and spend settings are the carve, the depth limit and the roll-up you wrote by hand. Note one subtlety in the Claude docs: by default the Agent tool can run subagents in the background and return later, which is a different control-flow shape from the blocking call built here (08A.13).

4.6 Failure modes#

Failure Symptom Defence
Vague brief The child answers a different question Self-contained task, a tool description that says what to include
A multi-minute agent treated like a cheap function Latency and cost spikes Budget slice, timeout, and a description that says it is expensive
Hidden spend The bill is larger than the parent's trace Roll up child usage; count it in the parent's budget
Recursion Agents spawn agents Depth limit; withhold the agent-tool at the limit
Permission leak The child has tools the parent should not Least privilege per child (tools= allowlists)
Injection through output A hostile page steers the parent through the child's summary Treat child output as untrusted (08A.5)
Needs a dialogue The specialist must ask clarifying questions mid-task A tool call is one round trip; use a handoff or a different design (08D.1)

Part 5: Choosing and combining the three#

You have... Reach for... Because
A draft whose quality can be checked by code or a rubric Reflection (gate first, then score-aware) Cheap, bounded, and you can measure whether it helped
Independent subtasks, and latency or breadth matters Fan-out with a quorum and a pool Latency is the slowest branch, but cost is the sum, so cap it
A self-contained specialist skill with its own tools or permissions Agent-as-a-tool The parent's context stays small and permissions are separated
Steps that depend on each other A chain or a plan (08A.9, 08C.1) Parallelism needs independence
A task one agent can do with the right tools One agent Every extra agent adds cost, latency and ways to fail (08D.1)

They compose. A fan-out branch can be an agent-as-a-tool call; the aggregator can apply a reflection gate before returning; a reflection critic can itself be an agent with different tools. Each composition multiplies cost, so compose only when a measurement says the extra quality is real, and share one budget across all of it.


Part 6: Evaluate it#

6.1 Where to read first#

Concept lessons first:

Then the tooling (required unless marked optional):

6.2 What to measure for each pattern#

Pattern Measure Pass rule (example)
Reflection Pass rate with and without it on the same tasks; tasks fixed and broken; cost multiple Net fixes above zero with an interval that excludes zero, at a cost multiple you accept; no regression in the returned draft
Reflection critic Agreement with human labels Calibrated like any judge (10A.5)
Fan-out Latency versus the sequential baseline; partial-result handling (a failed branch is flagged); aggregation fidelity (do key facts from each branch survive the merge); cost versus single branch A failed branch always produces an INCOMPLETE flag; the merge keeps at least the agreed share of key facts; cost within budget
Agent-as-a-tool Quality and cost versus a single-agent baseline (10A.12 Part 6); orchestration overhead; the brief's quality; context-isolation and spend roll-up invariants The two-agent design beats the baseline on success or cost per successful task; parent history length independent of child work; parent spend equals own plus children

6.3 A concrete tiny eval: invariants for all three#

Inputs: the scripted patterns from this lesson. Metric: pass or fail per invariant. Pass rule: every invariant passes, on every run, in CI. These are deterministic checks of your pattern code. They do not replace measuring a real model, which uses the ablation in 2.5 on a real task set.

python
# invariants.py
"""Cheap, deterministic checks for the three patterns. Each is a pass/fail rule you could run in CI."""
import asyncio
import json

from agent_tool import RESEARCHER, STATS, as_tool
from fanout import agent_branch, aggregate_concat, fan_out
from mini import Pool, ScriptedModel, call, run_loop, say
from reflect_score import CASES, reflect, rubric, scripted


def check(name: str, ok: bool) -> None:
    print(("PASS  " if ok else "FAIL  ") + name)


async def main() -> None:
    # Fan-out: when a branch fails, the aggregate must say the result is incomplete.
    out = await fan_out({"a": agent_branch("a"), "b": agent_branch("b", fail=True)})
    check("fan-out flags a missing branch as INCOMPLETE", "INCOMPLETE" in aggregate_concat(out))
    out = await fan_out({"a": agent_branch("a"), "b": agent_branch("b")})
    check("fan-out with no failures is not flagged", "INCOMPLETE" not in aggregate_concat(out))

    # Agent-as-a-tool: the parent's history must not grow with the child's work, and spend must roll up.
    lengths = []
    for child_steps in (1, 3, 5):
        STATS.update(child_runs=0, child_messages=0, withheld=0, deepest=0)
        pool = Pool(5_000)
        child_turns = [call("search_docs", query="q")] * (child_steps - 1) + [say("done")]
        RESEARCHER.make_model = lambda t=child_turns: ScriptedModel(list(t))
        parent = ScriptedModel([call("researcher", task="x"), say("ok")])
        res = await run_loop(parent, {"researcher": as_tool(RESEARCHER, pool, 0)}, "go", pool=pool)
        tool_msg = json.loads([m for m in res.messages if m["role"] == "tool"][0]["content"])
        lengths.append(len(res.messages))
        check(f"parent pool = parent calls (200) + child tokens ({tool_msg['tokens']}) -> {pool.used}",
              pool.used == 200 + tool_msg["tokens"])

    check(f"parent history length is the same whatever the child does (lengths for 1, 3, 5 child steps: {lengths})",
          len(set(lengths)) == 1)

    # Reflection: the returned draft must never score lower than any earlier draft.
    for name, drafts in CASES.items():
        r = reflect(scripted(drafts), rubric)
        check(f"reflection '{name}' returns the best draft seen", all(r.best.score >= x.score for x in r.rounds))


asyncio.run(main())
Output · real, run with Python 3.14 on 1 December 202610 lines
PASS  fan-out flags a missing branch as INCOMPLETE
PASS  fan-out with no failures is not flagged
PASS  parent pool = parent calls (200) + child tokens (100) -> 300
PASS  parent pool = parent calls (200) + child tokens (300) -> 500
PASS  parent pool = parent calls (200) + child tokens (500) -> 700
PASS  parent history length is the same whatever the child does (lengths for 1, 3, 5 child steps: [3, 3, 3])
PASS  reflection 'converges' returns the best draft seen
PASS  reflection 'plateau' returns the best draft seen
PASS  reflection 'regression' returns the best draft seen
PASS  reflection 'oscillation' returns the best draft seen

Each line is a rule you could keep forever. A failed branch is flagged as incomplete. The parent's history length is the same whether the child took 1, 3 or 5 steps (3 messages each time). The parent's spend equals its own calls plus exactly what the child reported (300, 500 and 700 for children costing 100, 300 and 500 tokens). And reflection never returns a draft scoring below an earlier one. The next step is to run the same checks against a real model and a real task set, with a single-agent baseline for comparison, using the Module 10 lessons above.


Common misconceptions#

  • "Reflection always improves quality." It sometimes fixes and sometimes breaks. Measure fixes against breaks and keep the best draft.
  • "The critic is a second opinion." Not if it sees only the draft and shares the generator's blind spots. Give it different evidence or use deterministic checks.
  • "Parallel means faster and cheaper." Faster in latency; the cost is the sum of the branches, plus an aggregator. Parallel is rarely cheaper.
  • "If one branch fails, the others still give the answer." They give part of an answer. The aggregate must say what is missing, or you ship a confident answer built on a third of the data.
  • "A majority of the branches that finished is a majority." Two usable votes out of five is not a vote. Set a minimum.
  • "A sub-agent is just a function call." It is a loop with its own budget, latency and failure modes. Treat it as an expensive, fallible function.
  • "The child's context is hidden, so its cost is too." Context isolation is not cost isolation. Roll up spend.
  • "An agent-as-a-tool and a handoff are the same." With a tool, the parent keeps control and gets a result back. With a handoff, control moves.

Key takeaways#

  • 08A.10, 08A.9 and 08D.3 gave you the basic patterns; the production gaps are gates, scores, partial results, budgets and isolation.
  • Reflection can be a gate on the final answer with a retry cap. Score it, return the best draft, and stop on target, plateau, regression or oscillation.
  • Prefer deterministic critics, then a model critic against a checklist, and give any critic evidence the generator lacked.
  • Measure reflection by what it fixed, what it broke and what it cost.
  • Fan-out needs a concurrency bound, per-branch timeouts, an optional quorum that cancels stragglers, a shared token pool, and outcomes with statuses instead of silent drops.
  • Aggregators must name what is missing and refuse to decide on too few votes.
  • Agent-as-a-tool needs a budget slice, a depth limit, a structured result, spend roll-up and an isolation check; the child's output is untrusted input.
  • The brief and the tool description are prompts: the specialist has not seen the conversation.
  • Frameworks (OpenAI Agents SDK as_tool, Claude Agent SDK subagents) package the same ideas; learn the plain version first so you can read their options.
  • Each pattern multiplies cost. Compose only when a measurement shows the gain.

Terms introduced in this lesson#

Term Meaning
Reflection Checking a draft against criteria and revising it before it leaves the system
Self-critique Reflection where the model (or a second call) judges the draft
Reflection gate A check run when the loop tries to finish; failures are sent back as feedback, up to a retry cap
Score-aware reflection Reflection that scores each draft and returns the best one
Best-of tracking Keeping the highest-scoring draft rather than the last one
Plateau A reflection stop reason: the score stopped improving by at least min_gain
Regression A revision that scores lower than the best draft so far
Oscillation A draft repeating an earlier draft, so the loop is going in circles
Fixed and broken counts In a reflection ablation, tasks reflection turned from fail to pass, and from pass to fail
Fan-out Splitting independent work into branches that run at the same time
Aggregate Combining branch results into one result
Quorum The number of usable branch results at which the rest are cancelled
Straggler A branch still running after a quorum is reached
Token pool A shared budget that several loops draw from
Branch outcome A branch's result with a status: ok, partial, error, timeout, cancelled or skipped
Partial result A result from a branch or run that stopped early but kept what it found
Majority vote Choosing the answer most branches agree on, with a minimum number of usable votes
Model-emitted parallel tool calls Several tool calls the model returns in one turn
Agent-as-a-tool A whole agent registered as a tool in another agent's tool list
Handoff Transferring control of the conversation to another agent, as opposed to calling it as a tool
Budget carve Giving a child agent a slice of the parent's remaining budget
Depth limit A cap on how many levels of agents may call agents
Spend roll-up Adding a child agent's usage to its parent's total
Context isolation The child's intermediate steps never entering the parent's history
Delegation brief The task the parent writes for a child; it must be self-contained

Exercises#

  1. A weighted rubric. Change rubric() so the refund amount counts double, and re-run all four cases. Which stop reasons change? Hint: weights change the scores, so a draft that was 0.75 may become 0.60 or 0.80; plateau and regression are decided by score gaps and the min_gain threshold, so recompute each case by hand first and then check against the output.
  2. Break the gate. Make final_check flag a second issue that the model can never fix (for example "include the customer's birthday"). What does the run return, and how would you decide which unfixable issues should block the answer and which should only be flagged? Hint: with the retry cap the run completes with answered with unresolved issues; classify issues as blocking or advisory and only retry on blocking ones.
  3. Quorum with a floor. Change fan_out so a quorum of 2 only counts results whose status is ok, and add a min_ok that makes the whole call fail loudly when too few branches succeed. Hint: the loop already counts ok outcomes before cancelling; add a check after the loop that raises or returns a flag if the count is below min_ok, and test it with the error-and-timeout scenario.
  4. A fair latency test. Replace the "faster than sequential" boolean with a measurement that compares fan-out time to the sum of the branch times, over five repetitions, and reports the median ratio. Hint: use time.perf_counter around each run, compute sum(branch_delays) as the sequential estimate, and report a ratio; use a median because a single run is noisy.
  5. Depth and fraction. In agent_tool.py, change MAX_DEPTH to 1, then 3, and the carve fraction to 0.9. Predict, then check, how many children run and what the parent's pool shows. Hint: with MAX_DEPTH=1 the child's agent-tool is withheld immediately; a larger fraction lets a child take most of the parent's remaining budget, which is the failure the carve exists to prevent.
  6. A real critic. Using critique_openai or critique_anthropic with a key, replace rubric() for the tone check only, keep the deterministic checks for the rest, and run the ablation from 2.5 on ten real drafts. Report fixed, broken and cost. Hint: combine scores as (deterministic share) times (model tone score) or as an average, and label the output illustrative; do not paste your key. Compare against the two-model critic setup in 08A.10.

Check yourself#

  1. What does reflection as a final-answer gate add over a separate critique loop, and what stops it from looping forever?
  2. Why should score-aware reflection return the best draft rather than the last one?
  3. Name the five reflection stop reasons.
  4. Why is a critic that sees only the draft a weak critic, and what makes a critic stronger?
  5. In a reflection ablation, what are "fixed" and "broken", and why must you count both?
  6. Fan-out improves latency but not cost. Why?
  7. What is a quorum, and what must you do with the branches that are still running when it is reached?
  8. Why must an aggregate say what is missing?
  9. List four things a production agent-as-a-tool needs that a bare wrapper lacks.
  10. What is the difference between an agent-as-a-tool and a handoff?

Further resources#


← 08A.10 — Agent Patterns: ReAct, Plan-and-Execute, Routing and Orchestrator-Workers | Module 08A overview | 08A.12 — Human-in-the-Loop and Approval Gates as a Pattern →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close