Orchestration: agents that call agents
“The subagent lies. Not out of malice — out of optimism.”
Objective
Understand when it is worth arranging agents in a hierarchy, implement a subagent with isolated context, and build the verification-by-handle mechanism that keeps the parent from trusting the child’s report.
8.1 Why use a hierarchy
A single agent with many tools starts to get confused. The solution is hierarchy: a coordinator agent that delegates parts of the work to subagents, each with isolated context and specific tools.
The gain is real. A subagent with its own context does not carry the parent’s history, which keeps cost low and focus high. A subagent with restricted tools cannot do what it should not.
The risk is also real, and it is specific: the subagent lies. Not out of malice — out of optimism. It reports success when it did what it thought was success. If the parent trusts the report, the whole system rests on a false foundation.
8.2 Isolated context
The simplest implementation is a separate process with a JSON brief. The subagent does not see the parent’s history; it sees only what was passed to it.
Listing 8.1. Subagent as an isolated process with a JSON brief.
CHILD = '''
import hashlib, json, sys
from pathlib import Path
brief = json.loads(sys.argv[1])
out = Path(brief["out"])
lines = [f"item {i}: ok" for i in range(1, brief["n"] + 1)]
out.write_text("\\n".join(lines), encoding="utf-8")
digest = hashlib.sha256(out.read_bytes()).hexdigest()
print(json.dumps({"path": str(out), "sha256": digest,
"lines": len(lines)}))
'''
def run_subagent(brief: dict) -> dict:
p = subprocess.run([sys.executable, "-c", CHILD, json.dumps(brief)],
capture_output=True, text=True, timeout=60)
if p.returncode != 0:
raise RuntimeError(f"subagent failed: {p.stderr[-500:]}")
return json.loads(p.stdout.strip().splitlines()[-1])
The brief must be self-contained. A subagent does not inherit the parent’s context — that is the point. If the brief says “generate the report” and does not specify the format, the subagent will invent a format.
8.3 The verifiable handle
The solution to the optimistic report is to require a handle that the parent can verify independently.
Listing 8.2. Independent verification of the subagent’s result.
def verify(handle: dict) -> bool:
"""The parent does NOT trust the report: it recomputes the file hash."""
path = Path(handle["path"])
if not path.exists():
return False
actual = hashlib.sha256(path.read_bytes()).hexdigest()
n_lines = len(path.read_text(encoding="utf-8").splitlines())
return actual == handle["sha256"] and n_lines == handle["lines"]
The subagent returns a path, a hash and a count. The parent recomputes them. Running it:
Listing 8.3. Output: verification and negative proof.
handle returned by the subagent: {'path': '.../report.txt',
'sha256': '48221a38...', 'lines': 5}
parent's independent verification: PASSED
forged handle: rejected (correct)
The last line is the one that proves verification works: a handle with a made-up hash is rejected. Without this negative proof, you have a check that may not be checking anything.
Checks stronger than a hash. A hash guarantees integrity, not correctness: a wrong but consistent file passes. For tasks whose result can actually be verified, prefer checking the property that matters — number of valid lines, correct sum, schema respected — or run a validator. The hash is the minimum; the semantic assertion is the ideal.
8.4 Parallelism
Independent subagents can run at the same time. The gain is in latency, not cost: the tokens are the same, but less time passes on the clock.
Listing 8.4. Parallel subagents with verification.
from concurrent.futures import ThreadPoolExecutor
briefs = [{"out": f"part_{i}.txt", "n": 5} for i in range(4)]
with ThreadPoolExecutor(max_workers=4) as pool:
handles = list(pool.map(run_subagent, briefs))
failures = [h for h in handles if not verify(h)]
print(f"{len(handles) - len(failures)}/{len(handles)} verified")
Verification is still mandatory: parallelism increases the chance of a subagent failing silently, because you are watching less closely.
8.5 When not to orchestrate
Orchestration has a cost: more calls, more latency, more places for errors to hide. The rule of thumb:
-
One agent, when the task is a sequence of steps with common tools.
-
Subagents, when there are independent parts that can run in parallel, or when the context volume of one part would pollute the rest.
-
Deep orchestration, almost never. Three levels of agents is the point at which you lose the ability to debug.
Common pitfall
Creating a subagent for each tool “for the sake of organization”. Every subagent carries context, orchestration and verification overhead. It pays off when the subagent handles a substantial and independent part of the work — not when it merely wraps a call.