Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 3

Lab: Parallel Sub-Agents with Isolated Context

Build a supervisor that runs three sub-agents in parallel, at most two at a time, each with only its own task in its context, and joins their checked outputs into an audit report.

Contentsand lesson path

On this page

  1. Why Split an Audit Across Isolated Workers
  2. Three Stages: Split, Run, Join
  3. Verify Your Understanding
  4. Apply it
  5. Review prompt

Lessons of Multi-Agent Orchestration

  1. When More Agents Help and When They Hurt Concept · 15 min
  2. Supervisors, Handoffs and Agents as Tools Worked example · 25 min
  3. Lab: Parallel Sub-Agents with Isolated Context Lab · 25 min
  4. How Multi-Agent Systems Fail Concept · 15 min
  5. Single Versus Multi-Agent on One Task Set Lab · 25 min
  6. Check: Choose a Topology Knowledge check · 8 questions

What you will learn

  • Delegate sub-tasks to sub-agents with isolated contexts and structured return values, running independent ones in parallel.

Prerequisites: Agent Loops & ReAct

01. Why Split an Audit Across Isolated Workers

A single agent asked to run a full security and compliance audit of a large codebase runs into a context problem. If you load API route definitions, static analysis rules and regulatory retention requirements into a single prompt, the context grows large and mixes unrelated material, and details from one domain are easier to miss while the model works on another.

Software architects meet a similar problem with services: they split work into parts that talk through typed contracts, so that one part cannot disturb another. Sub-agents apply the same idea to prompts. In a security audit, mixed context can mean a missed finding: an agent auditing API routes might overlook an unauthenticated admin endpoint because its transcript is full of an unrelated SQL error it was debugging earlier. Dividing the workload into parallel sub-agents gives each one a context that holds only its own task. The workers in this lab are coroutines in one Python process, so their memory is not separated; what is isolated is the prompt each one sends, its own message list.

This pattern is called parallel fan-out with isolated context. "Fan-out" means one supervisor starts several workers at the same time; "isolated context" means each worker gets only the instructions and tools for its own part. Instead of one agent that must know everything, a small supervisor starts three workers, at most two at a time in this lab. None of the workers knows about the others, which keeps each prompt small and stops one task from interfering with another.

In this lab you build a supervisor in Python asyncio that starts three isolated sub-agents, waits for all of them, checks each reply, and combines the findings into one audit report.

02. Three Stages: Split, Run, Join

The supervisor works in three stages.

Stage 1, split the task. The supervisor takes the overall goal and writes one small task per worker: a task prompt and the tools that worker may use. It leaves out everything else: earlier conversation turns, its own notes and the instructions for other domains. So each worker starts with a short prompt that holds only its own job. Split off only sub-tasks that do not need each other's output: a sub-task that needs another's result has to wait for it, so start the independent ones together and run the dependent one after. In production you would also attach trace IDs to each task, so you can follow every worker in your tracing tool; this lab leaves tracing out to stay short.

Stage 2, run the workers at the same time. With an asynchronous runtime such as Python asyncio.gather, the supervisor starts the worker calls together instead of one after another. The API worker looks for leaked credentials in endpoints, the code worker scans the authentication code for risky regular expressions, and the compliance worker checks how long tables keep customer data. Because the workers do not wait for each other, the total time can approach the time of the slowest worker when all of them can run at once. With a concurrency cap, as in this lab, it takes longer than that, but still less than running every worker in turn.

Starting many workers at once can exceed the provider's rate limit, so supervisors usually cap how many run at the same time with an asyncio.Semaphore. A cap of, say, five workers still runs them in parallel but makes HTTP 429 Too Many Requests errors during bursts less likely.

Stage 3, join, check and combine. The supervisor waits until every worker has finished or failed. As each worker completes, its return payload is validated against a schema (the lab uses a small standard-library validator; Pydantic models do the same job). If a worker fails, times out or returns malformed JSON, the supervisor retries only that worker, once, and records anything still failing as a partial failure instead of losing the results that succeeded. The supervisor puts each checked result in a dict keyed by domain (results[domain]) and prints the report from that dict. The workers' own message lists never reach it.

Lab setup. You need Python 3.12 or later; standard library only, no API key. Tested with Python 3.12.13. Create a folder subagents-lab and save the four files below. The model is a seeded fake that answers like an API and misbehaves on purpose, so you can see every failure path: the compliance worker's first call hangs, and the code worker's first reply is cut off mid-JSON.

Python · subagents-lab/fake_model.py
"""A seeded stand-in for a model API. Some calls misbehave on purpose:
the compliance worker's first call hangs, the code worker's first reply is cut off."""
import asyncio
import json
import math

FINDINGS = {
    "api": {"endpoints_scanned": 42, "leaked_credentials": ["GET /v1/export"]},
    "code": {"files_scanned": 18, "risky_patterns": ["auth_parser.py:88"]},
    "compliance": {"tables_checked": 9, "over_retention": ["events_2019"]},
}
SLOW = {"api": 0.05, "code": 0.08, "compliance": 0.06}  # seconds per call


async def complete(messages, domain, attempt):
    tokens_in = sum(math.ceil(len(m["content"]) / 4) for m in messages)
    if domain == "compliance" and attempt == 0:
        await asyncio.sleep(5)  # a hung request: only a timeout ends it
    await asyncio.sleep(SLOW[domain])
    reply = json.dumps({"domain": domain, **FINDINGS[domain]})
    if domain == "code" and attempt == 0:
        reply = reply[: len(reply) // 2]  # truncated JSON
    return reply, {"input_tokens": tokens_in, "output_tokens": len(reply) // 4}

Step 1: isolated workers. Each worker creates its own message list containing only the system prompt and its own task, calls the model, and returns the reply. Its transcript never reaches the supervisor.

Python · subagents-lab/workers.py
"""Each worker builds its own message list: its context holds only its own task."""
import fake_model

SYSTEM = "You audit one domain of a service. Reply with JSON findings only."
TASKS = {"api": "Audit the 42 API endpoints for leaked credentials.",
         "code": "Scan the auth code for risky regular expressions.",
         "compliance": "Check every table against the 30-day retention rule."}


async def run_worker(domain, attempt):
    messages = [{"role": "system", "content": SYSTEM},  # fresh, isolated context
                {"role": "user", "content": TASKS[domain]}]
    reply, usage = await fake_model.complete(messages, domain, attempt)
    return reply, usage  # the transcript stays here; only the reply goes back

Step 2: structured return values. The supervisor accepts only the fields it expects, with the right types, and drops anything else a worker adds.

Python · subagents-lab/schemas.py
"""Structured return values: the supervisor accepts nothing else."""
import json

REQUIRED = {"api": {"endpoints_scanned": int, "leaked_credentials": list},
            "code": {"files_scanned": int, "risky_patterns": list},
            "compliance": {"tables_checked": int, "over_retention": list}}


class BadResult(ValueError):
    pass


def validate(domain, reply):
    try:
        data = json.loads(reply)
    except json.JSONDecodeError:
        raise BadResult("reply is not valid JSON") from None
    for field, kind in REQUIRED[domain].items():
        if not isinstance(data.get(field), kind):
            raise BadResult(f"{field} must be {kind.__name__}")
    return {field: data[field] for field in REQUIRED[domain]}  # drop extras

Step 3: the supervisor. A semaphore caps concurrent model calls at two, as you would to stay under a provider rate limit. Each call has a timeout. gather(..., return_exceptions=True) collects failures as values instead of letting the first one cancel the rest. Failed workers get one retry; a bug in your own code (any other exception) is re-raised rather than hidden.

Python · subagents-lab/supervisor.py
"""Fan out three isolated workers, validate, retry once, report partial failures."""
import asyncio
import sys
import time

from schemas import BadResult, validate
from workers import TASKS, run_worker

TIMEOUT_S, MAX_CONCURRENT = 0.3, 2


async def attempt(domain, n, gate):
    async with gate:  # at most MAX_CONCURRENT model calls at once
        reply, usage = await asyncio.wait_for(run_worker(domain, n), TIMEOUT_S)
    return validate(domain, reply), usage


async def supervise(domains, attempts=2):
    gate = asyncio.Semaphore(MAX_CONCURRENT)
    results, failures, tokens = {}, {}, 0
    for n in range(attempts):  # by default one retry for failed workers
        todo = [d for d in domains if d not in results]
        outcomes = await asyncio.gather(*(attempt(d, n, gate) for d in todo),
                                        return_exceptions=True)
        for domain, out in zip(todo, outcomes):
            if isinstance(out, (asyncio.TimeoutError, BadResult)):
                why = str(out) or f"no reply within {TIMEOUT_S * 1000:.0f} ms"
                failures[domain] = f"{type(out).__name__}: {why}"
                print(f"  {domain:<10} attempt {n + 1} failed: {failures[domain]}")
            elif isinstance(out, BaseException):
                raise out  # a bug in our own code: do not hide it
            else:
                results[domain], usage = out
                tokens += usage["input_tokens"] + usage["output_tokens"]
                failures.pop(domain, None)
                print(f"  {domain:<10} attempt {n + 1} ok")
    return results, failures, tokens


async def plain_gather(domains):  # a bare gather, as many first versions use
    return await asyncio.gather(*(attempt(d, 0, asyncio.Semaphore(3))
                                  for d in domains))


if __name__ == "__main__":
    start = time.perf_counter()
    if "--plain" in sys.argv:
        try:
            asyncio.run(plain_gather(list(TASKS)))
        except Exception as exc:
            print(f"plain gather raised {type(exc).__name__}; no results kept")
    else:
        attempts = 1 if "--no-retry" in sys.argv else 2
        results, failures, tokens = asyncio.run(supervise(list(TASKS), attempts))
        print(f"report: {len(results)}/{len(TASKS)} domains, "
              f"unresolved={sorted(failures)}, worker tokens={tokens}")
        for domain, findings in results.items():
            print(f"  {domain}: {findings}")
    elapsed = time.perf_counter() - start  # about 0.4 s here; varies by machine
    print(f"finished in under 1 s: {elapsed < 1}")
Terminal
python3 supervisor.py
Expected output
  api        attempt 1 ok
  code       attempt 1 failed: BadResult: reply is not valid JSON
  compliance attempt 1 failed: TimeoutError: no reply within 300 ms
  code       attempt 2 ok
  compliance attempt 2 ok
report: 3/3 domains, unresolved=[], worker tokens=151
  api: {'endpoints_scanned': 42, 'leaked_credentials': ['GET /v1/export']}
  code: {'files_scanned': 18, 'risky_patterns': ['auth_parser.py:88']}
  compliance: {'tables_checked': 9, 'over_retention': ['events_2019']}
finished in under 1 s: True

Both failures were recovered by retrying only the failed workers; the API worker's result was kept from the first round. On our machine the whole run took about 0.4 seconds, most of it the 300 ms timeout on the hung call, although the fake model hangs for 5 seconds. Wall time differs between machines, so the script prints only whether the run stayed under one second.

Step 4: partial failure. Run without retries to see what the report looks like when workers stay broken.

Terminal
python3 supervisor.py --no-retry
Expected output
  api        attempt 1 ok
  code       attempt 1 failed: BadResult: reply is not valid JSON
  compliance attempt 1 failed: TimeoutError: no reply within 300 ms
report: 1/3 domains, unresolved=['code', 'compliance'], worker tokens=51
  api: {'endpoints_scanned': 42, 'leaked_credentials': ['GET /v1/export']}
finished in under 1 s: True

Step 5: why return_exceptions=True matters. The --plain mode runs the same workers with a bare asyncio.gather, as many first versions do.

Terminal
python3 supervisor.py --plain
Expected output
plain gather raised BadResult; no results kept
finished in under 1 s: True

A bare gather raises the first exception it sees, so the API worker's finished result is thrown away with the rest. Failure isolation is not automatic; it comes from return_exceptions=True, per-worker timeouts and retries, and a report that names what is missing.

This lab measures correctness and recovery, not whether the multi-agent design is worth it. Comparing it with a single agent on the same tasks, with repeated runs, is the subject of Single Versus Multi-Agent on One Task Set. Guarding peer handoffs against ping-pong loops is shown in Supervisors, Handoffs and Agents as Tools.

03. Verify Your Understanding

Practice check · 3 questions

Parallel Sub-Agent Execution Knowledge Check

Three questions on gather failures, the retry round and what is isolated.

Q1. Three workers run under a bare `asyncio.gather`, and one raises. What happens to the results of the two that succeeded?
Q2. In the default run, the API worker succeeds in round 1, and the code and compliance workers fail. How many workers call the model in round 2, and why?
Q3. The lab's workers are coroutines in one Python process. What exactly is isolated between them?
Practice only: not graded, not saved, not evidence.

04. Apply it

Use the same supervisor shape in the research assistant for this skill:

  • Give each of the three sub-questions its own message list and a return schema, such as findings, sources, confidence and gaps.
  • Run independent sub-questions with gather(..., return_exceptions=True), a per-call timeout and a semaphore sized to your provider's rate limit.
  • Retry only the workers that failed, and list unresolved sub-questions in the final report instead of hiding them.
  • Record the tokens each worker used, so the comparison with your single agent in the last lab of this skill has real numbers.

05. Review prompt

Without looking back, explain what is isolated when sub-agents run as coroutines in one process, and why. Then describe what happens to finished results when one worker raises under a bare gather, and name the three things in the supervisor that turn a hung or broken worker into a partial result.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check