Skip to slide
Chapter 11 · Subagents and Multi-Agent Orchestration
80 / 142

CHAPTER 11 · Subagents and Multi-Agent Orchestration · 8 / 10

Code MVP: a subagent spawner

"""
chapter 11: subagents and orchestration.
spawn_subagent runs a FRESH agent loop with its own context window and
returns only a summary to the parent. An orchestrator chains a planner,
an implementer, and a skeptical verifier.
"""
from dataclasses import dataclass

@dataclass
class SubagentSpec:
    name: str
    instructions: str          # the subagent's system prompt (its contract)
    model: str = "inherit"     # 'inherit' or a cheaper/faster model (tiered execution)

def run_isolated_loop(spec: SubagentSpec, task: str, model_fn, tools) -> str:
    """A subagent: its own history, separate from the parent's. Returns a
    summary string. (Real version reuses Chapter 2's agent_loop verbatim.)"""
    history = [
        {"role": "system", "content": spec.instructions},
        {"role": "user", "content": task},          # self-contained: no parent history
    ]
    # ... the same loop as Chapter 2 runs here, using model_fn and tools ...
    summary = model_fn(history, spec.model)          # produces ONLY a final summary
    return summary

def spawn_subagent(spec, task, model_fn, tools, background=False):
    if background:
        # Real harness: launch on a thread/process and return a handle.
        # Toy version stays synchronous for clarity.
        pass
    return run_isolated_loop(spec, task, model_fn, tools)

# --- The orchestrator pattern: planner -> implementer -> verifier ---
PLANNER = SubagentSpec("planner",
    "Analyze the request and output a numbered technical plan. Plan only.")
IMPLEMENTER = SubagentSpec("implementer",
    "Implement the plan. Make the edits and run the build.")
VERIFIER = SubagentSpec("verifier",
    "You are a SKEPTICAL validator. Confirm the work actually runs and tests "
    "pass. Report what passed vs what is incomplete. Do not trust claims.")

def orchestrate(request, model_fn, tools):
    plan = spawn_subagent(PLANNER, request, model_fn, tools)
    result = spawn_subagent(IMPLEMENTER, f"Plan:\n{plan}\n\nImplement it.", model_fn, tools)
    verdict = spawn_subagent(VERIFIER, f"Claim:\n{result}\n\nVerify it.", model_fn, tools)
    return {"plan": plan, "result": result, "verdict": verdict}

if __name__ == "__main__":
    # Fake model: each subagent returns a canned summary so the flow is visible.
    def fake_model(history, model):
        role = history[0]["content"][:20]
        if "Analyze" in history[0]["content"]:
            return "1. Add validateEmail()  2. Add tests  3. Run pytest"
        if "Implement" in history[0]["content"]:
            return "Added validateEmail() and 3 tests. Claimed: all pass."
        return "VERIFIED: function exists, 3/3 tests pass. No edge cases missed."
    from pprint import pprint
    pprint(orchestrate("add email validation", fake_model, tools={}))

Run it and you see three isolated subagents hand structured output down the chain: a plan, an implementation claim, and an independent verdict. The parent only ever sees those three summaries, not the dozens of tool calls each subagent might have made internally. That is context isolation plus the orchestrator and verifier patterns in one small flow.

← → arrow keys work too