Articles / agentspythonprojects
Build a multi-agent app builder in Python: specs, handoffs and a reviewer gate
Five agents build a CLI todo app in Python. Spec with acceptance criteria, file plan, frozen tests, a reviewer that rejects v1. Runnable, real output.
A multi-agent app builder splits one job ("make me a todo app") across roles that pass work to each other. A product agent writes what the app must do, an architect decides which files exist, a coder writes them, a tester writes tests, and a reviewer decides whether the result ships. That split only works if each handoff is something a program can check. Chat transcripts passed from agent to agent can't be checked. Files with a fixed shape can.
This post builds that pipeline in about 200 lines of standard-library Python. It builds a small command-line todo app inside a temp directory. The reviewer rejects the first version, because two acceptance tests fail and the coder tried to delete one of the tests. The second version gets approved. Then one step runs on a real local model (qwen3 4B via Ollama), and that run shows where this design pays off and where it doesn't.
This is the multi-agent sequel to two earlier posts. Build an AI coding agent in Python covers the single-agent tool loop, path guards, command allowlists and the test gate, and Design an AI coding agent covers sandboxes, edit formats and cost at scale. None of that is repeated here. This post is about the seams between agents.
The pipeline and its artifacts#
Every role reads named files and writes named files. The orchestrator is plain Python. No model decides who runs next.
idea (one sentence)
|
v
[product] ----> SPEC.json acceptance criteria AC1..ACn, interface
| |
v v
[architect] --> PLAN.json files, and which ACs each file covers
| |
v v
[tester] -----> tests/ written from SPEC only, then frozen
|
v
[coder] ------> todo.py only paths listed in PLAN.json are written
| ^
v | REVIEW.json (reasons, failing ACs)
run tests (timeout)|
| |
v |
[reviewer] -- reject ------+
|
approve --> done
Three choices in that diagram do most of the work.
- The spec is a contract. Acceptance criteria have stable IDs (
AC1,AC2), and every later artifact refers to those IDs. The plan says which file covers which AC. Each test name starts with its AC ID. The reviewer reports failures per AC. When something breaks, you know which requirement broke. - The tester never sees the code. Tests come from the spec's interface (
main(argv, store) -> int), before the coder runs. If the tester read the code first, it would test what the code does instead of what the spec asks for. - Artifacts are validated at each boundary. A malformed spec stops the run before the architect starts. A plan that leaves an AC uncovered stops before any code is written. A bad handoff costs one model call, not five.
Specs as contracts#
Here is the spec the product role produced in the scripted run. The model's raw output is JSON, so the orchestrator can parse it and check it.
SPEC = {
"app": "todo CLI",
"interface": {"module": "todo.py",
"entrypoint": "main(argv: list[str], store: str) -> int; prints to stdout/stderr"},
"acceptance": [
{"id": "AC1", "given": "empty store", "when": "add 'buy milk'",
"then": "prints 'added 1', returns 0"},
{"id": "AC2", "given": "one open todo", "when": "list",
"then": "prints '1 [ ] buy milk'"},
{"id": "AC3", "given": "todo 1 exists", "when": "done 1",
"then": "returns 0 and list shows '1 [x] buy milk'"},
{"id": "AC4", "given": "no todo 99", "when": "done 99",
"then": "prints 'no todo 99' to stderr, returns 1, store unchanged"},
{"id": "AC5", "given": "any store", "when": "add ''",
"then": "prints 'text required' to stderr, returns 2, nothing stored"},
],
}
Every then names an exact string or an exit code. That is what makes it a contract: two people (or two agents) reading AC4 will write the same assertion. "Shows a helpful error" would let the coder and the tester each pick their own wording, and the tests would fail for no real reason.
The spec check is short:
def check_spec(spec):
errs = []
if not spec.get("interface", {}).get("module"):
errs.append("spec: interface.module missing")
ids = [ac.get("id", "") for ac in spec.get("acceptance", [])]
if not ids:
errs.append("spec: no acceptance criteria")
for ac in spec.get("acceptance", []):
if not re.fullmatch(r"AC\d+", ac.get("id", "")):
errs.append(f"spec: bad id {ac.get('id')!r}")
then = ac.get("then", "")
if not then:
errs.append(f"spec: {ac.get('id')} has no 'then'")
elif re.search(r"\be\.g\.|correctly|cleanly|properly|appropriate", then, re.I):
errs.append(f"spec: {ac['id']} is not testable: {then[:60]!r}")
if len(ids) != len(set(ids)):
errs.append("spec: duplicate ids")
return errs
check_plan is the same idea for PLAN.json: file paths must match [a-z_]+\.py, and every AC ID must appear in some file's covers list. The vague-word regex is crude, and it is there because of the real-model run further down. A spec can be valid JSON with perfect IDs and still be untestable.
The roles and their gates#
The model sits behind one method, complete(role, prompt, round_) -> str. In this post a ScriptedModel returns canned JSON for each (role, round) pair, so everything runs with python3 and no API key. A real client (Claude, OpenAI, Ollama) goes behind the same method; the Ollama version is about ten lines and appears in the last section.
The coder and tester are where the boundaries matter most.
def coder(model, ws, round_):
plan = ws.read_json("PLAN.json")
inputs = ws.read("SPEC.json") + ws.read("PLAN.json")
if ws.path("REVIEW.json").exists():
inputs += ws.read("REVIEW.json")
out = json.loads(model.complete("coder", "Write the files in PLAN.json.\n" + inputs, round_))
allowed = {f["path"] for f in plan["files"]}
refused = []
for rel, src in out["files"].items():
if rel in allowed:
ws.write(rel, src)
else:
refused.append(rel) # not in the plan: never touches disk
return refused
def tester(model, ws):
# The tester sees the spec's interface, never the code. Tests are written once and frozen.
spec = ws.read("SPEC.json")
out = json.loads(model.complete("tester", "Write unittest tests named test_<ACid>_*.\n" + spec))
for rel, src in out["files"].items():
parts = Path(rel).parts
if parts[0] != "tests" or ".." in parts:
raise PermissionError(f"tester may only write tests/: {rel}")
ws.write(rel, src)
The plan is the coder's write allowlist. The coder gets SPEC, PLAN and, on a retry, the last REVIEW. It never sees the test source, and it can't write to tests/, because no plan entry points there. ws.write resolves every path against the temp project root and raises PermissionError on anything outside it. Both guards fire as expected:
PermissionError: tester may only write tests/: tests/../todo.py
PermissionError: outside project: ../../etc/x
Tests run with unittest in a subprocess with a 20-second timeout, a stripped environment and -I (isolated mode). The runner maps each verbose result line back to its AC by the test name:
def run_tests(ws, timeout=20):
try:
r = subprocess.run(
[sys.executable, "-I", "-m", "unittest", "discover", "-s", "tests", "-t", ".", "-v"],
cwd=ws.root, capture_output=True, text=True, timeout=timeout,
start_new_session=True, env={"PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"},
)
except subprocess.TimeoutExpired:
return {"timed_out": True, "per_ac": {}, "exit": None}
per_ac = {}
for m in re.finditer(r"^test_(AC\d+)\w* \(.*?\) \.\.\. (ok|FAIL|ERROR)", r.stderr, re.M):
ac, status = m.groups()
per_ac.setdefault(ac, []).append(status)
errors = sorted(set(re.findall(r"^(\w+Error: .*)$", r.stderr, re.M)))
return {"timed_out": False, "exit": r.returncode, "per_ac": per_ac,
"errors": errors, "tail": r.stderr.strip().splitlines()[-1]}
Parsing verbose output is fragile. Anything a test prints to stderr can split a result line. An early run of this pipeline used open(...).read() in a test. The ResourceWarning landed in the middle of the test_AC4 ... ok line, the regex missed it, and the reviewer reported "AC4: no test" on a passing suite. The fix was in the test, but a production version should use a custom TestResult or pytest's JUnit XML instead of a regex.
The reviewer has two layers. Hard checks run in code: every AC needs at least one test, every test must pass, the suite must not time out or crash, and no file outside the plan may have been attempted. The model gets those reasons and can add more (naming, risk, a missing edge case). It can't delete any.
def reviewer(model, ws, results, refused, round_):
spec = ws.read_json("SPEC.json")
reasons = []
crashed = results["exit"] and not results["per_ac"]
if crashed:
reasons.append("test suite crashed: " + "; ".join(results["errors"]))
for ac in [] if crashed else spec["acceptance"]:
got = results["per_ac"].get(ac["id"])
if not got:
reasons.append(f"{ac['id']}: no test")
elif any(s != "ok" for s in got):
reasons.append(f"{ac['id']}: test {'/'.join(got)} ({ac['then']})")
if results["timed_out"]:
reasons.append("tests timed out")
for rel in refused:
reasons.append(f"file outside plan refused: {rel}")
# The model may add reasons (style, risk). It cannot remove the hard ones.
notes = json.loads(model.complete("reviewer", json.dumps({"reasons": reasons}), round_))
reasons += notes.get("extra_reasons", [])
verdict = "approve" if not reasons else "reject"
ws.write("REVIEW.json", json.dumps({"round": round_, "verdict": verdict,
"reasons": reasons}, indent=2))
return verdict, reasons
An LLM reviewer that can approve on its own judgment will sometimes approve red tests, especially after a long, confident coder message. Here, approval needs an empty reasons list, and the model can only add to that list.
The coder and reviewer together form what Anthropic's agent-patterns guide calls an evaluator-optimizer loop, with the difference that the evaluator here is mostly code. The orchestrator in build() runs product, architect and tester once, then loops coder, tests and reviewer for at most three rounds, stopping at the first APPROVE. It prints one line per role, which is the output below.
The run: v1 rejected, v2 approved#
The scripted coder's first version has two real bugs. done 99 does nothing and returns 0 instead of printing an error. add "" stores an empty todo. It also does what weak coding agents often do with a failing test and tries to rewrite tests/test_todo.py without the AC4 test. Round two fixes both bugs and only writes todo.py.
$ python3 run.py
project dir: appbuild-7h39swgh
product -> SPEC.json 5 criteria
architect -> PLAN.json ['todo.py']
tester -> tests/ (frozen)
coder -> round 1 refused: tests/test_todo.py
tests -> FAILED (failures=2)
reviewer -> REJECT
- AC4: test FAIL (prints 'no todo 99' to stderr, returns 1, store unchanged)
- AC5: test FAIL (prints 'text required' to stderr, returns 2, nothing stored)
- file outside plan refused: tests/test_todo.py
coder -> round 2
tests -> OK
reviewer -> APPROVE
files: ['PLAN.json', 'REVIEW.json', 'SPEC.json', 'tests/__init__.py', 'tests/test_todo.py', 'todo.py']
calls:
product round 1 prompt 283 chars
architect round 1 prompt 984 chars
tester round 1 prompt 950 chars
coder round 1 prompt 1178 chars
reviewer round 1 prompt 220 chars
coder round 2 prompt 1455 chars
reviewer round 2 prompt 15 chars
total 7 calls, 5085 prompt chars
The rejection reasons quote the spec's then text, so the round-two coder prompt (277 characters longer than round one, which is the size of REVIEW.json) says exactly what to fix. The attempted test rewrite never reached disk. The frozen tests are the same file the tester wrote before any code existed.
In an earlier version of the script, the first coder output imported a helpers.py that the plan did not list. The orchestrator refused the file, the import failed, and the reviewer reported test suite crashed: ModuleNotFoundError: No module named 'helpers' instead of five confusing "no test" lines. That case is why the reviewer checks for a crash before it checks ACs.
One step on a real model#
Swapping the product role onto a local model takes one class:
class OllamaModel:
"""Real local call. Only used for one role in the optional run."""
def __init__(self, name="qwen3:4b-instruct"):
self.name, self.calls = name, []
def complete(self, role, prompt, round_=1):
import urllib.request
self.calls.append((role, round_, len(prompt)))
body = json.dumps({"model": self.name, "stream": False, "format": "json",
"options": {"temperature": 0},
"messages": [{"role": "user", "content": prompt}]}).encode()
req = urllib.request.Request("http://localhost:11434/api/chat", body,
{"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=180) as resp:
return json.loads(resp.read())["message"]["content"]
format: "json" asks Ollama for JSON output. You can also pass a full JSON schema there; see the structured outputs docs in the sources. The first real run, before the vague-word check existed, came back with ten criteria that all passed the shape check. Two of them:
SPEC accepted: 10 criteria
AC1 -> The app prints a message indicating it is ready to receive commands (e.g., 'Enter a command: add, list, mark, or quit') and does not exit
AC7 -> The app exits cleanly and does not leave any open file handles or incomplete state
The model turned a CLI into an interactive prompt loop, gave example strings instead of exact ones, and added criteria no unit test can check. Every later role would have built on that. After adding the vague-word check and one retry that feeds the errors back, the run looked like this (Ollama 0.40.16 on a laptop, about 3 minutes 20 seconds for both attempts):
$ python3 run.py --ollama-product
product attempt 1 rejected:
spec: AC1 is not testable: 'The app prints a message indicating it is ready to receive c'
spec: AC2 is not testable: 'The app adds the task to the list and saves it to the JSON f'
spec: AC3 is not testable: "The app prints all tasks in a formatted list (e.g., '1. [tas"
spec: AC5 is not testable: "The app prints an error message (e.g., 'Unknown command: xyz"
product attempt 2 rejected:
spec: AC3 is not testable: "The app prints all tasks in a formatted list, exactly as: '1"
spec: AC4 is not testable: 'The app marks the task at index 1 as done and saves the upda'
spec: AC7 is not testable: 'The app closes all file handles and exits cleanly without an'
SPEC rejected by contract check:
...
The retry fixed some criteria and not others, and the pipeline stopped before the architect ran. A 4B model can't write a tight spec from a one-line idea with this prompt. Failing at the spec boundary cost two model calls. Without the check, the same mistake would have shown up as a coder and tester disagreeing about prompt strings three roles later. The regex is still a blunt tool, and it will flag some fine criteria. A better gate asks a second model "can you write one assertion for this criterion, yes or no", or hands the spec to a human for a 30-second read, which for a real project is cheap.
Where multi-agent costs more than it gains#
Anthropic reported that in their data, agents use about 4 times the tokens of a chat, and multi-agent systems about 15 times. They also wrote that most coding tasks have fewer parts that can run in parallel than research does. This pipeline is sequential, so it pays for the extra calls without getting any parallel speedup. Here is how that trade breaks down.
| Concern | One agent with tools | This five-role pipeline |
|---|---|---|
| Model calls for a clean run | One loop, often 5 to 15 turns | 5 calls minimum, plus 2 per review round |
| Context | One growing transcript | Each role reads only its input files (283 to 1,455 chars here) |
| Test independence | Same model writes code and tests | Tests written before the code, from the spec only |
| Debugging a failure | Read one long trace | Open the artifact at the failing boundary |
| Ambiguous idea | The agent asks you mid-loop | A vague spec spreads to every downstream role unless a gate stops it |
| Latency | Lowest | Sequential sum of every role |
The multi-agent version earns its cost when you need the separation. That covers tests that must not be written by the code's author, a reviewer that must not be argued out of a red build, and an audit trail of which requirement each file serves. It loses on small tasks. A single agent with the guards from the coding agent post would fix this todo app in one loop with fewer tokens. Cognition's essay on multi-agent systems makes the related point that agents working from partial context make conflicting decisions. Here each role gets a partial view on purpose, and the price is that the spec has to be complete. Someone has to write the contract, and that costs time.
Practical rules from building this:
- Start with one agent. Add a role only when you can name the artifact it produces and the check that validates it.
- Give each role a write allowlist, not a reminder in its prompt.
- Freeze tests before code exists, and give the coder no write path to them.
- Let the reviewer's model add reasons and never remove them.
- Cap review rounds. If round three still fails, the spec is probably wrong, and that is a human's call.
For the other ways to wire agents (supervisor, fan-out, critic loops, blackboard) and the cost of each, see Multi-agent architecture patterns. For a LangGraph version with parallel branches and a human approval step, see Multi-agent workflow automation in Python.
Testing the pipeline itself#
The scripted model makes the orchestrator testable without any model. Useful cases, each a few lines with a different SCRIPT dict:
- A spec with a duplicate ID or a vague
thenstops before the architect runs. - A plan that leaves AC5 uncovered stops before the tester runs.
- A coder that writes a file outside the plan gets refused, and the reviewer reports it.
- A coder whose code loops forever hits the 20-second timeout and gets rejected with "tests timed out".
- A reviewer model that returns
{"extra_reasons": []}on red tests still produces REJECT.
Once those pass, swap one role at a time onto a real model and keep a small set of app ideas with hand-written specs as the eval. Count how often each role's artifact passes its gate on the first try. That number tells you which role needs a better prompt or a bigger model, and the agent evals path covers how to grow it into a proper suite.
Sources#
- Anthropic, How we built our multi-agent research system: the 4x and 15x token figures, and the note on coding tasks being less parallel.
- Anthropic, Building effective agents: orchestrator-workers and evaluator-optimizer workflows.
- Cognition, Don't build multi-agents.
- Ollama, Chat API, Structured outputs and the qwen3 model page.
- Python docs: unittest, subprocess (timeouts,
start_new_session), tempfile, pathlib (resolve,is_relative_to).