Single Versus Multi-Agent on One Task Set
Build a small benchmark harness that runs a single agent and a supervisor with three workers on the same 20 tasks, five times each, and reports success rate with a confidence interval, latency and total tokens, all measured by the harness.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A task set with ground truth
- Step 2: A seeded fake model
- Step 3: Two topologies behind one meter
- Step 4: Repeat, measure and summarise
- Step 5: Change one assumption at a time
- Step 6: Limits are part of the design
- Check your understanding
- Apply it
- Review prompt
Lessons of Multi-Agent Orchestration
- When More Agents Help and When They Hurt Concept · 15 min
- Supervisors, Handoffs and Agents as Tools Worked example · 25 min
- Lab: Parallel Sub-Agents with Isolated Context Lab · 25 min
- How Multi-Agent Systems Fail Concept · 15 min
- Single Versus Multi-Agent on One Task Set Lab · 25 min
- Check: Choose a Topology Knowledge check · 8 questions
What you will learn
- Diagnose multi-agent failure modes (lost context, conflicting actions, runaway delegation, duplicated work) and add limits and checks.
- Justify a multi-agent design against a single-agent baseline using measured quality, latency and token cost.
Prerequisites: Agent Loops & ReAct
01. Goal and setup
A multi-agent design costs more calls and adds new ways to fail, as How Multi-Agent Systems Fail showed, so adopt it only when it beats a single agent on your own tasks. One run on one task cannot show that. In this lab you build a harness that compares the two designs fairly and shows how uncertain the result is.
Both designs audit service configuration for leaked API keys, regular expressions with nested quantifiers and data kept longer than 30 days. Each task comes with the list of problems that really exist, the ground truth. Both use the same model, instructions and tools; only the topology differs. For every run the harness records:
- success: whether the final report lists exactly the ground-truth problems, with no misses and no false alarms;
- recall and precision: the share of real problems found, and the share of reported problems that are real;
- latency: wall-clock time measured with
time.perf_counter(); - tokens: input and output tokens added up over every model call, including the supervisor's own calls.
The model is a seeded fake that answers like an API, takes time and reports token usage, so the lab is free, offline and repeatable. Keep its limit in mind: how its accuracy drops as prompts grow is a setting you choose (--dilution), not something the lab discovers. The lab teaches you to build and read a benchmark; a decision about a real system needs your real agents in the same harness.
You need: Python 3.12 or later; the code uses only the standard library and no API key. Tested with Python 3.12.13. Create an empty folder mas-bench and work inside it.
mas-bench/
├── tasks.py step 1: seeded tasks with ground truth
├── fake_model.py step 2: seeded stand-in for a model API
├── topologies.py step 3: meter, single agent, supervisor and workers
├── smoke.py step 3: one run of each design
└── bench.py step 4: repeated runs and statistics02. Step 1: A task set with ground truth
Each task has three documents of 10 to 60 lines, one per domain, with up to two planted problems each. The lengths vary, so the result does not hang on one example. Every line has an id such as api-11, and the ground truth is the set of ids that hold a problem. The seed gives everyone the same 20 tasks.
"""Seeded audit tasks, each with a known set of findings (the ground truth)."""
import random
DOMAINS = ("api", "code", "retention")
def _line(rng, domain, i, bad):
if domain == "api":
cred = f"key=sk_live_{rng.randrange(10**8):08d}" if bad else "auth=bearer"
return f"GET /v1/resource{i} {cred}"
if domain == "code":
pattern = r"^(\w+)+@corp$" if bad else r"^[a-z0-9_]{3,32}$"
return f"USER_RE_{i} = re.compile(r'{pattern}')"
days = rng.choice([45, 90, 400]) if bad else rng.choice([7, 14, 30])
return f"table events_{i} retention_days={days}"
def make_tasks(n, seed):
tasks = []
for t in range(n):
rng = random.Random(f"task|{seed}|{t}")
docs, truth = {}, set()
for domain in DOMAINS:
size = rng.randint(10, 60) # tasks differ in length on purpose
bad = set(rng.sample(range(size), rng.randint(0, 2)))
lines = []
for i in range(size):
line_id = f"{domain}-{i}"
lines.append(f"{line_id}: {_line(rng, domain, i, i in bad)}")
if i in bad:
truth.add(line_id)
docs[domain] = "\n".join(lines)
tasks.append({"id": f"t{t:02d}", "docs": docs, "truth": truth})
return tasks03. Step 2: A seeded fake model
The last line of the prompt tells the fake whether to pick a tool, plan, merge worker results or write a report. Its rules are explicit:
- Tokens are estimated as one per four characters. A real API reports exact counts in its usage fields.
- Latency is a sleep that grows with prompt and reply length, plus or minus 20%. The harness times each run itself.
- Accuracy: when it writes a report, the fake misses each real problem with probability
dilution × prompt tokens / 1000, up to 0.95. It also flags a clean line 0.2% of the time and cuts 5% of its JSON replies in half, as a truncated reply would be. - Repeatability: each call has a key such as
single|t03|2|report|try0that seeds its random generator, so the same call gets the same reply even when threads finish in another order.
"""A seeded stand-in for an LLM API: the same prompt and key give the same reply."""
import json
import math
import random
import re
import time
LINE = re.compile(r"^([a-z]+-\d+): (.*)$", re.MULTILINE)
def count_tokens(text):
return math.ceil(len(text) / 4) # rough rule of thumb: ~4 characters per token
def looks_bad(text):
if "key=sk_live_" in text or r"(\w+)+" in text:
return True
days = re.search(r"retention_days=(\d+)", text)
return bool(days) and int(days.group(1)) > 30
class FakeModel:
def __init__(self, seed, dilution, bad_json=0.05, false_pos=0.002):
self.seed = seed
self.dilution = dilution # ASSUMPTION: miss rate grows with prompt length
self.bad_json = bad_json # share of report replies cut off mid-JSON
self.false_pos = false_pos # chance of flagging a clean line
def complete(self, prompt, key):
rng = random.Random(f"model|{self.seed}|{key}")
tokens_in = count_tokens(prompt)
last = prompt.rstrip().splitlines()[-1]
if last.startswith("NEXT TOOL:"):
reply = json.dumps({"tool": last[10:].split(",")[0].strip()})
elif last == "PLAN":
reply = json.dumps({"assign": ["api", "code", "retention"]})
elif last == "MERGE":
reply = self._merge(prompt, rng)
else:
reply = self._report(prompt, tokens_in, rng)
tokens_out = count_tokens(reply)
ms = 15 + tokens_in * 0.008 + tokens_out * 0.4 # slower for longer prompts
time.sleep(ms * rng.uniform(0.8, 1.2) / 1000)
return reply, {"input_tokens": tokens_in, "output_tokens": tokens_out}
def _report(self, prompt, tokens_in, rng):
p_miss = min(0.95, self.dilution * tokens_in / 1000)
found = []
for line_id, text in LINE.findall(prompt):
if looks_bad(text):
if rng.random() >= p_miss:
found.append(line_id)
elif rng.random() < self.false_pos:
found.append(line_id)
return self._maybe_cut(json.dumps({"findings": found}), rng)
def _merge(self, prompt, rng):
found = []
for line in prompt.splitlines():
if line.startswith('{"findings"'):
found += json.loads(line)["findings"]
unique = sorted(set(found))
return self._maybe_cut(json.dumps({"findings": unique}), rng)
def _maybe_cut(self, reply, rng):
return reply[: len(reply) // 2] if rng.random() < self.bad_json else reply04. Step 3: Two topologies behind one meter
Every model call goes through Meter. It counts calls, adds up the tokens from each reply's usage and enforces a call budget. ask_json checks that a report parses and retries once if it does not. These limits come from lesson 04: a budget stops runaway delegation, and a schema check catches broken hand-offs.
single_agentasks the model which tool to call next and appends each tool's output to its history. On every later call it sends that whole history again.multi_agentmakes one planning call. It then runs three workers in parallel threads, each with a fresh context that holds only its own domain, and finishes with one merge call. A worker returns only its findings, never its transcript.
"""Two architectures that share one model, one prompt style and the same tools."""
import json
import threading
from concurrent.futures import ThreadPoolExecutor
from tasks import DOMAINS
SYSTEM = (
"You audit a service. Report every line that leaks a credential, uses a\n"
"nested regex quantifier or keeps data for more than 30 days. Reply in JSON.\n"
)
class BudgetExceeded(Exception):
pass
class BadReply(Exception):
pass
class Meter:
"""Wraps the model: counts calls and tokens and enforces a call budget."""
def __init__(self, model, max_calls, overhead=0):
self.model, self.max_calls = model, max_calls
# fixed text every call carries: tool schemas, policies (~10 tokens/line)
self.preamble = ("#" * 39 + "\n") * (overhead // 10)
self.calls = self.tokens_in = self.tokens_out = self.bad_replies = 0
self.lock = threading.Lock() # workers call the model from threads
def ask(self, prompt, key):
with self.lock:
if self.calls >= self.max_calls:
raise BudgetExceeded(key)
self.calls += 1
reply, usage = self.model.complete(self.preamble + prompt, key)
with self.lock:
self.tokens_in += usage["input_tokens"]
self.tokens_out += usage["output_tokens"]
return reply
def ask_json(self, prompt, key):
for attempt in range(2): # one retry, then give up
reply = self.ask(prompt, f"{key}|try{attempt}")
try:
return json.loads(reply)["findings"]
except (json.JSONDecodeError, KeyError, TypeError):
with self.lock:
self.bad_replies += 1
raise BadReply(f"{key}: no valid JSON after one retry")
def single_agent(task, meter, key):
history, left = SYSTEM, list(DOMAINS)
while left: # the model picks the next tool; each result joins the history
ask = history + f"NEXT TOOL: {', '.join(left)}"
reply = meter.ask(ask, f"{key}|t{len(left)}")
tool = json.loads(reply)["tool"]
left.remove(tool)
history += f"CALL {tool}\n{task['docs'][tool]}\n"
return set(meter.ask_json(history + "REPORT", f"{key}|report"))
def worker(task, domain, meter, key):
prompt = SYSTEM + f"SCOPE: {domain} only\n" # fresh, isolated context
tool = json.loads(meter.ask(prompt + f"NEXT TOOL: {domain}", f"{key}|t"))["tool"]
prompt += f"CALL {tool}\n{task['docs'][tool]}\n"
return meter.ask_json(prompt + "REPORT", f"{key}|report")
def multi_agent(task, meter, key):
plan = json.loads(meter.ask(SYSTEM + "PLAN", f"{key}|plan"))["assign"]
with ThreadPoolExecutor(max_workers=len(plan)) as pool:
jobs = [pool.submit(worker, task, d, meter, f"{key}|{d}") for d in plan]
results = [job.result() for job in jobs]
summary = "".join(json.dumps({"findings": r}) + "\n" for r in results)
return set(meter.ask_json(SYSTEM + summary + "MERGE", f"{key}|merge"))First check that each design runs once and that the meter counts what you expect:
"""Run each architecture once on the first task and show what the meter saw."""
from fake_model import FakeModel
from tasks import make_tasks
from topologies import Meter, multi_agent, single_agent
tasks = make_tasks(20, seed=7)
lines = sum(doc.count("\n") + 1 for t in tasks for doc in t["docs"].values())
counts = [len(t["truth"]) for t in tasks]
print(f"{len(tasks)} tasks, {lines} lines, {sum(counts)} findings "
f"({min(counts)}-{max(counts)} per task)")
task = tasks[0]
print("truth:", sorted(task["truth"]))
model = FakeModel(seed=7, dilution=0.08)
for name, agent in (("single", single_agent), ("multi", multi_agent)):
meter = Meter(model, max_calls=12)
found = agent(task, meter, f"smoke|{name}")
print(f"{name:<6} found={sorted(found)} calls={meter.calls} "
f"in={meter.tokens_in} out={meter.tokens_out}")python3 smoke.py20 tasks, 2174 lines, 67 findings (0-6 per task)
truth: ['api-11', 'api-31']
single found=['api-11', 'api-31'] calls=4 in=3434 out=23
multi found=['api-11', 'api-31'] calls=8 in=2063 out=50Both designs find the two leaked keys in task t00. The single agent made 4 calls but used 3,434 input tokens; the multi-agent run made 8 calls and used 2,063. The single agent re-sends its whole history, so it pays for the API document again on each later call. Comparing only final prompt sizes would miss this cost.
05. Step 4: Repeat, measure and summarise
bench.py runs each design 5 times on each of the same 20 tasks, 100 runs per design, and computes:
- a Wilson score interval, a 95% confidence interval for a success rate that, unlike the simple textbook formula, never falls below 0% or rises above 100%;
- the p95 latency, the time under which 95% of runs finished, by the nearest-rank method;
- a paired comparison: on how many tasks multi-agent did better or worse, with an exact sign test of how surprising that split would be if neither design were better.
"""Benchmark both architectures on the same tasks and print what was measured."""
import argparse
import math
import statistics
import time
from fake_model import FakeModel
from tasks import make_tasks
from topologies import BadReply, BudgetExceeded, Meter, multi_agent, single_agent
def wilson(k, n, z=1.96):
"""95% Wilson score interval for a success rate of k out of n."""
p, z2 = k / n, z * z
centre = (p + z2 / (2 * n)) / (1 + z2 / n)
half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n)
return centre - half, centre + half
def p95(values):
ordered = sorted(values)
return ordered[math.ceil(0.95 * len(ordered)) - 1] # nearest-rank method
def sign_test(wins, losses):
"""Two-sided exact sign test over tasks that did not tie."""
n = wins + losses
if n == 0:
return 1.0
tail = sum(math.comb(n, i) for i in range(min(wins, losses) + 1))
return min(1.0, 2 * tail / 2**n)
def run(name, agent, tasks, model, repeats, max_calls, overhead):
rows = []
for task in tasks:
for rep in range(repeats):
meter = Meter(model, max_calls, overhead)
start = time.perf_counter()
try:
found, status = agent(task, meter, f"{name}|{task['id']}|{rep}"), "ok"
except BudgetExceeded:
found, status = set(), "budget"
except BadReply:
found, status = set(), "bad_json"
ms = 1000 * (time.perf_counter() - start)
truth = task["truth"]
rows.append({
"task": task["id"], "ok": found == truth, "status": status, "ms": ms,
"tp": len(found & truth), "fp": len(found - truth),
"fn": len(truth - found), "calls": meter.calls,
"tin": meter.tokens_in, "tout": meter.tokens_out,
"bad": meter.bad_replies,
})
return rowsdef summarise(name, rows):
n, wins = len(rows), sum(r["ok"] for r in rows)
low, high = wilson(wins, n)
tp, fp, fn = (sum(r[k] for r in rows) for k in ("tp", "fp", "fn"))
ms = [r["ms"] for r in rows]
print(f"{name:<7}{n:>5}{wins / n:>8.0%} {low:.0%}-{high:.0%}"
f"{tp / max(1, tp + fn):>8.2f}{tp / max(1, tp + fp):>7.2f}"
f"{statistics.mean(ms):>7.0f}{p95(ms):>6.0f}"
f"{statistics.mean(r['tin'] for r in rows):>8.0f}"
f"{statistics.mean(r['tout'] for r in rows):>6.0f}"
f"{statistics.mean(r['calls'] for r in rows):>6.1f}")
def per_task(rows):
rates = {}
for r in rows:
rates.setdefault(r["task"], []).append(r["ok"])
return {task: sum(oks) / len(oks) for task, oks in rates.items()}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--tasks", type=int, default=20)
ap.add_argument("--repeats", type=int, default=5)
ap.add_argument("--seed", type=int, default=7)
ap.add_argument("--dilution", type=float, default=0.08)
ap.add_argument("--overhead", type=int, default=0)
ap.add_argument("--multi-max-calls", type=int, default=12)
args = ap.parse_args()
tasks = make_tasks(args.tasks, args.seed)
model = FakeModel(args.seed, args.dilution)
single = run("single", single_agent, tasks, model, args.repeats, 6, args.overhead)
multi = run("multi", multi_agent, tasks, model, args.repeats,
args.multi_max_calls, args.overhead)
print(f"{args.tasks} tasks x {args.repeats} repeats, seed {args.seed}, "
f"dilution {args.dilution}, overhead {args.overhead}")
print("arch runs success 95% CI recall prec. ms avg p95"
" in tok out calls")
summarise("single", single)
summarise("multi", multi)
a, b = per_task(single), per_task(multi)
better = sum(b[t] > a[t] for t in a)
worse = sum(b[t] < a[t] for t in a)
print(f"per task: multi better on {better}, worse on {worse}, "
f"tied on {len(a) - better - worse}; sign test p = "
f"{sign_test(better, worse):.3f}")
for name, rows in (("single", single), ("multi", multi)):
status = [r["status"] for r in rows]
print(f"{name}: bad JSON replies {sum(r['bad'] for r in rows)}, failed runs: "
f"budget {status.count('budget')}, bad_json {status.count('bad_json')}")
if __name__ == "__main__":
main()python3 bench.py20 tasks x 5 repeats, seed 7, dilution 0.08, overhead 0
arch runs success 95% CI recall prec. ms avg p95 in tok out calls
single 100 63% 53%-72% 0.92 0.94 95 118 2769 28 4.1
multi 100 72% 63%-80% 0.96 0.93 89 108 1740 61 8.3
per task: multi better on 11, worse on 7, tied on 2; sign test p = 0.481
single: bad JSON replies 8, failed runs: budget 0, bad_json 0
multi: bad JSON replies 26, failed runs: budget 0, bad_json 0Read the table the way a reviewer would:
- Quality. Multi-agent succeeds on 72% of runs (63–80%) and the single agent on 63% (53–72%). The intervals overlap. Per task, multi-agent is better on 11 tasks and worse on 7, and the sign test gives p = 0.481. A split like this is quite likely even if the two designs were equal, so this data does not show a reliable difference in quality.
- Latency. The mean is about 90 ms against about 95 ms. The workers run in parallel, but both designs still have four model calls in a row on their slowest path, so the gain is small. Real calls take seconds, not milliseconds, so measure again with your real model.
- Tokens. Multi-agent uses fewer input tokens here (1,740 against 2,769 per run) but twice the calls and output tokens. For cost, price each call's input and output tokens at its own model's current rates.
- Independence. The Wilson interval treats the 100 runs as independent, but the 5 repeats of one task are not, so it is somewhat too narrow. The per-task comparison is the more honest view.
06. Step 5: Change one assumption at a time
Change one input at a time and watch which conclusions move. First, remove the accuracy penalty for long prompts:
python3 bench.py --dilution 020 tasks x 5 repeats, seed 7, dilution 0.0, overhead 0
arch runs success 95% CI recall prec. ms avg p95 in tok out calls
single 100 80% 71%-87% 1.00 0.94 96 117 2769 29 4.1
multi 100 80% 71%-87% 1.00 0.93 89 109 1741 62 8.3
per task: multi better on 8, worse on 7, tied on 5; sign test p = 1.000
single: bad JSON replies 8, failed runs: budget 0, bad_json 0
multi: bad JSON replies 26, failed runs: budget 0, bad_json 0Both designs now reach 80% with recall 1.00 (the failures left are false alarms), so the quality gap in step 4 came entirely from the long-prompt assumption. Whether it holds for your model is what a real benchmark must measure.
Next, add 1,000 tokens of fixed text, such as instructions and tool schemas, to every call:
python3 bench.py --overhead 100020 tasks x 5 repeats, seed 7, dilution 0.08, overhead 1000
arch runs success 95% CI recall prec. ms avg p95 in tok out calls
single 100 47% 38%-57% 0.82 0.93 127 159 6849 27 4.1
multi 100 59% 49%-68% 0.90 0.93 124 149 10000 60 8.3
per task: multi better on 10, worse on 6, tied on 4; sign test p = 0.454
single: bad JSON replies 8, failed runs: budget 0, bad_json 0
multi: bad JSON replies 26, failed runs: budget 0, bad_json 0The token picture flips: multi-agent now uses 10,000 input tokens per run against 6,849, because each of its 8 calls pays the fixed text again. Anthropic reports the same direction in its own data: multi-agent systems used about 15 times the tokens of a chat, against about 4 times for a single agent. Finally, use more tasks to narrow the uncertainty:
python3 bench.py --tasks 6060 tasks x 5 repeats, seed 7, dilution 0.08, overhead 0
arch runs success 95% CI recall prec. ms avg p95 in tok out calls
single 300 67% 62%-72% 0.92 0.95 93 109 2490 27 4.1
multi 300 73% 68%-78% 0.95 0.94 87 107 1615 59 8.2
per task: multi better on 28, worse on 18, tied on 14; sign test p = 0.184
single: bad JSON replies 17, failed runs: budget 0, bad_json 0
multi: bad JSON replies 78, failed runs: budget 0, bad_json 4The intervals are narrower, but p = 0.184 is still not convincing, and four multi-agent runs failed because a report came back broken twice. The honest summary: multi-agent looks slightly better, costs twice the calls, and the difference is not yet established.
07. Step 6: Limits are part of the design
The multi-agent design needs 8 calls when nothing goes wrong, and up to 12 when every report needs its one retry. Set the budget to exactly 8 calls and see what happens:
python3 bench.py --multi-max-calls 820 tasks x 5 repeats, seed 7, dilution 0.08, overhead 0
arch runs success 95% CI recall prec. ms avg p95 in tok out calls
single 100 63% 53%-72% 0.92 0.94 95 118 2769 28 4.1
multi 100 59% 49%-68% 0.73 0.93 84 92 1717 58 8.0
per task: multi better on 10, worse on 9, tied on 1; sign test p = 1.000
single: bad JSON replies 8, failed runs: budget 0, bad_json 0
multi: bad JSON replies 25, failed runs: budget 23, bad_json 0Now 23 runs stop at the budget, because their retry would have needed a ninth call, and success falls from 72% to 59%. Three lessons follow:
- Count a run stopped by a limit as a failure, with the tokens and time it used. Dropping it describes a system that does not exist.
- Set limits from measured call counts plus the retries you allow, not from the happy path.
- Give each failure mode from lesson 04 a counter: calls and budget stops for runaway delegation, bad JSON replies for broken hand-offs.
08. Check your understanding
09. Apply it
The practice task asks you to compare your research assistant with its single-agent version on 10 questions. Reuse this harness:
- Keep
bench.pyandMeter. ReplaceFakeModeland the two topology functions with your real agents, and route every model call throughMeter. - Read the model name from an environment variable, for example
ANTHROPIC_MODEL=claude-sonnet-5-5, and use the same model in both designs. Take token counts from the usage fields of each API response. Do not settemperature: from API version 2026-10-21, which the anthropic 2.x SDKs send, Claude no longer acceptstemperature,top_portop_kat all, even at their default values. - Write a ground truth or rubric for each question before running, and run each question at least 3 times.
- Report success with its interval, the per-task comparison, mean and p95 latency, and tokens and cost per question; then state your decision and what evidence would change it.
10. Review prompt
Answer without looking back:
- What must stay identical in both designs to credit the topology?
- Why are repeats of one task not independent, and what helps?
- Why can a multi-agent system bill fewer input tokens than a single agent on one task set, and more on another?
- Which counters reveal runaway delegation and broken hand-offs?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.