ProjekinAja. Agentic AI Stage 4 · Building Agents Lesson 4.8
● Stage 4 · Lesson 4.8

Multi-Agent in Code — Orchestrator & Workers

One agent works. Sometimes a small team works better. Here's the orchestrator-and-workers pattern from Stage 2, implemented simply — and honestly — in Python.

⏱ ~16 min read 👥 From one agent to a team 🐍 Real, minimal code

🎯 By the end you'll understand

When a multi-agent team genuinely beats a single strong agent (and when it doesn't), the simplest version of the orchestrator-and-workers pattern (2.7) in code — an orchestrator that decomposes → spawns workers → synthesizes — why "an agent calling an agent" is just a function call, how to add a critic that reviews the draft, and the real cost, latency, and coordination tax you pay for the extra power.

KEY INSIGHTThe one idea to take away

A multi-agent system isn't a new kind of magic. It's one agent (4.7) called several times with focused briefs — and one more call to stitch the results together.

In Lesson 4.7 you built a single working agent: an LLM, some tools, and a loop. That one agent can do an enormous amount. But for big, sprawling goals it can drown — too much in its context at once, too many unrelated sub-problems, no clean way to divide and conquer. The fix is a team: a few focused agents coordinated by one boss.

The beautiful part is how little new there is to learn. A "worker" is just your agent from 4.7 pointed at a narrow task. An "orchestrator" is a plain function that decides what the workers should do and then combines their answers. No framework required — about forty lines of Python.

🔑 Hold onto this

Multi-agent = decompose → workers → synthesize. The orchestrator asks the model to split a goal into sub-tasks (planning, 2.5), runs a worker on each one, then makes one final model call to fuse the partial results into a coherent answer. That's the whole pattern.

CORE CONCEPTWhen a team beats a soloist

You met the why of multi-agent systems back in Lesson 2.7. Now that you can build agents for real, here's the practical version. A team helps in exactly three situations:

🎯

Focused contexts

Each worker sees only what its sub-task needs, not the whole messy goal. A smaller, cleaner context (2.3) means sharper reasoning and fewer distractions — the model isn't juggling ten things at once.

🧑‍🔬

Specialists

You can give each worker a different brief, different tools, even a different model. A "researcher" worker, a "code-writer" worker, a "critic" worker — each tuned for one job rather than one generalist stretched thin.

⚡

Parallelizable sub-tasks

If three sub-tasks don't depend on each other, they could run at the same time. (We'll keep our code sequential for clarity, but the structure makes concurrency easy to bolt on later.)

⚠️ Reach for one strong agent first

This is the part people skip. A single capable agent with good tools handles the vast majority of tasks — and it's cheaper, faster, and far easier to debug. Multi-agent is a tool you reach for when one agent provably isn't enough, not a default. Build the soloist (4.7), measure it (4.9), and only add a team if it can't keep up. Don't over-build.

FRAMEWORKThe pattern, in shapes

Before any code, hold the shape in your head. One orchestrator at the top, a fan of workers in the middle, a synthesis step at the bottom:

🧭 Orchestrator decompose the goal 🤖 Worker 1 sub-task A 🤖 Worker 2 sub-task B 🤖 Worker 3 sub-task C 🧵 Synthesize fuse results → final answer

Read it top to bottom: a goal comes in, the orchestrator splits it into sub-tasks, each sub-task gets handed to a worker (a focused agent run), the results bubble back up, and a final synthesis step weaves them into one answer. The same four beats every time — decompose, dispatch, collect, synthesize.

CORE CONCEPTThe worker, in code

Start with the worker, because it's the easy half — it's almost exactly your agent from 4.7. A worker takes a focused sub-task as a string and returns a result as a string. Nothing more.

To keep this lesson about the pattern rather than re-printing the whole tool loop, we'll wrap the agent you already wrote behind a tiny helper called run_agent(brief) — it runs the model-plus-tools loop from 4.7 and hands back the final text. The worker is then a one-liner that gives that agent a tight, single-purpose brief:

worker.pypython
import anthropic

client = anthropic.Anthropic()              # key comes from the environment (4.4)
MODEL = "claude-sonnet-5"                  # id may change over time


def run_agent(brief):                       # your agent loop from 4.7, simplified
    """Run the model on one focused brief, return its final text."""
    response = client.messages.create(
        model=MODEL, max_tokens=1024,
        messages=[{"role": "user", "content": brief}],
        # in the real version you'd pass tools=... and loop on tool calls (4.5–4.7)
    )
    return next((b.text for b in response.content if b.type == "text"), "")


def run_worker(subtask):                     # a worker = a focused agent run
    """Give one agent a narrow, single-purpose brief and collect its answer."""
    brief = (
        "You are a focused specialist. Do ONLY this sub-task and "
        "return a concise, self-contained result:\n\n" + subtask
    )
    return run_agent(brief)             # one focused context, one answer

That's the whole worker. The key word is focused: the brief deliberately narrows the agent to one job and tells it to return something self-contained. A worker doesn't know about the other workers or the big picture — and that ignorance is a feature. A clean, small context is what makes its reasoning sharp.

📖 Worker

A worker is an agent run (LLM + tools + loop, from 4.7) handed a single, narrow sub-task. It receives a focused brief, works in its own small context, and returns one result. In code it's just a function you call.

CORE CONCEPTThe orchestrator, in code

Now the boss. The orchestrator does three things, in order: decompose the goal into sub-tasks, loop a worker over each one, then synthesize a final answer. We'll write each step, then assemble them.

Step 1 — Decompose. Ask the model to break the goal into a short list of sub-tasks. We request one task per line so the result is trivial to parse — no fancy framework, just splitting on newlines (this is the planning idea from 2.5, made concrete):

orchestrate.py — part 1python
def decompose(goal):
    """Ask the model to split a goal into a few focused sub-tasks."""
    prompt = (
        "Break this goal into 3 focused, independent sub-tasks.\n"
        "Return ONE sub-task per line, no numbering, no extra text.\n\n"
        "GOAL: " + goal
    )
    text = run_agent(prompt)
    tasks = [line.strip() for line in text.splitlines() if line.strip()]
    return tasks                          # e.g. ["Research X", "Research Y", "Outline Z"]

Step 2 — Synthesize. The opposite move: take the goal plus all the workers' results and make one final model call to fuse them into a single coherent answer. This is where the partial pieces become a whole (synthesis):

orchestrate.py — part 2python
def synthesize(goal, results):
    """Fuse the workers' partial results into one final answer."""
    joined = "\n\n".join(
        "--- Result {}: {}".format(i + 1, r) for i, r in enumerate(results)
    )
    prompt = (
        "Combine these partial results into one clear, coherent answer "
        "to the original goal. Remove overlap; keep it tight.\n\n"
        "GOAL: " + goal + "\n\n" + joined
    )
    return run_agent(prompt)             # one final call = the synthesis

Step 3 — Assemble. Now the orchestrator itself. It's almost embarrassingly short — decompose, loop the worker over each sub-task collecting results, synthesize. Read it as English; that's exactly what it does:

orchestrate.py — part 3python
def orchestrate(goal):
    """Decompose a goal, run a worker per sub-task, then synthesize."""
    subtasks = decompose(goal)            # 1. split the goal (2.5)

    results = []
    for task in subtasks:                 # 2. one worker per sub-task
        result = run_worker(task)         #    (sequential here; could run in parallel)
        results.append(result)            # 3. collect the partial result

    return synthesize(goal, results)    # 4. fuse into the final answer


# run it
final = orchestrate("Write a short research report on urban beekeeping.")
print(final)

That's a complete multi-agent system. Four numbered beats inside one function: decompose → run workers → collect → synthesize. Everything else — more workers, smarter prompts, parallel execution — is a variation on these lines.

▸ The shape to memorize

orchestrate = decompose + (worker per sub-task) + synthesize. The orchestrator never does the work itself; it delegates to workers and combines the results. Hold this shape and every multi-agent framework you meet later will look familiar.

KEY INSIGHTAn agent calling an agent — it's just a function call

Here's the conceptual unlock. Back in Lesson 2.2 you learned a tool is just a function the model can ask to run. In 2.7 you heard that orchestrators can treat whole agents as tools. Now look at the code and see how literally true that is:

From the orchestrator's point of view, run_worker(task) is indistinguishable from any other function call. It passes in a string, it gets back a string. It doesn't care that inside that function an entire agent — model, tools, loop — sprang to life, did its work, and shut down. A worker is a tool whose implementation happens to be another agent.

💡 Why this matters

Once you see "agent as a function," multi-agent stops being mysterious. You're not building some exotic hive mind — you're writing ordinary Python where some of your functions happen to call a model inside. You could even let the orchestrator's agent call run_worker as a real tool (4.5), deciding for itself when to spin one up. Same idea, one layer fancier.

This is also why the whole thing composes so cleanly. A worker could itself be an orchestrator that spawns its own sub-workers. Functions calling functions — turtles, all the way down — but each layer is the same simple shape you already understand.

PRACTICALAdding a critic — the reviewer variant

One especially useful worker doesn't produce anything new — it reviews. This is reflection (2.6) and the review-before-trust habit (3.6) turned into a teammate. You draft an answer, then hand it to a critic worker that hunts for weaknesses, and you revise once based on its notes:

critic.pypython
def critique(goal, draft):
    """A critic worker: find weaknesses in the draft. Produces notes, not prose."""
    brief = (
        "You are a sharp critic. List the 3 biggest weaknesses in this "
        "draft answer to the goal. Be specific and brief.\n\n"
        "GOAL: " + goal + "\n\nDRAFT:\n" + draft
    )
    return run_worker(brief)


def orchestrate_with_critic(goal):
    draft = orchestrate(goal)            # the team produces a first draft
    notes = critique(goal, draft)        # a critic reviews it (2.6 / 3.6)
    revise = (
        "Revise the draft to fix these critique notes. "
        "Return only the improved answer.\n\n"
        "DRAFT:\n" + draft + "\n\nNOTES:\n" + notes
    )
    return run_agent(revise)             # one revision pass, then stop

Notice the discipline: we critique once and revise once. A critic loop can improve a draft, but left unbounded it spends money chasing diminishing returns — and can even talk itself into making things worse. Like every loop in this course, give it a hard stop (4.7).

📖 Critic (reviewer)

A critic is a worker whose job is to evaluate another agent's output — find errors, gaps, weak arguments — rather than produce the answer itself. It turns reflection (2.6) into a separate, focused step with a fresh context, which often catches what the original author missed.

SEE ITOrchestrator in code

Let's run orchestrate("write a short research report on urban beekeeping") and watch it execute. Press ▶ Run: the orchestrator decomposes the goal into three sub-tasks, each worker lights up and returns a partial result, an optional critic reviews the draft, then the synthesis step fuses everything into the final report. Each beat is tied to the function that produced it.

🧭 Interactive · orchestrate("write a short research report on urban beekeeping")

Deterministic walk-through. Watch each function fire in order: decompose → run_worker ×3 → critique → synthesize.

Press Run to step through the orchestrator.
🧭

decompose(goal)

Orchestrator asks the model to split the goal into 3 sub-tasks.

🤖

run_worker(subtask 1)

Worker 1 · focused agent run.

🤖

run_worker(subtask 2)

Worker 2 · focused agent run.

🤖

run_worker(subtask 3)

Worker 3 · focused agent run.

🔎

critique(goal, draft)

Critic worker reviews the combined draft (optional).

🧵

synthesize(goal, results)

One final model call fuses the results into the report.

📄 Final answer (returned by orchestrate)

— waiting to run —

See how the orchestrator never writes a word of the report itself — it only decomposes, dispatches, and synthesizes. The workers do the producing; the critic does the checking; the final call does the weaving. That division of labor is the pattern.

WEAKNESSThe honest trade-offs

A team is more powerful, but power is never free. Before you reach for multi-agent, weigh what it actually costs against a single-agent baseline (4.7). From 2.7, now concrete:

Single agent 🤖Orchestrator + workers 👥
Model callsa handfuldecompose + N workers + synthesize — many more
Costlowmultiplies with every worker and step
Latencyfastslower (sequential calls add up)
Failure pointsone loop to debugdecompose, each worker, synthesis — more places to break
Coordinationnone neededreal — passing context, parsing, handling a worker that fails
When it winsmost tasksbig goals with separable, specialist sub-tasks

Every box in the right column is a tax. A bad decomposition poisons every worker downstream. One flaky worker can derail the synthesis. And the bill grows with each call — a five-worker-plus-critic run can cost an order of magnitude more than one good agent doing the same job. Always compare to the single-agent baseline before paying that tax.

💡 On running workers concurrently

Because independent sub-tasks don't depend on each other, you could run the workers in parallel (with threads or async) to cut latency. We kept the loop sequential here for clarity, and that's the right call while you're learning — get it correct first, fast second. Concurrency adds its own coordination headaches, so reach for it only when latency is a real, measured problem.

WEAKNESSCommon mistakes to avoid

✗ Reaching for multi-agent first

The most common over-build in the field. A single strong agent (4.7) with good tools solves most problems more cheaply and reliably. Multi-agent is what you add after a soloist provably can't keep up — not your starting point. Complexity you don't need is just bugs you haven't met yet.

✗ No single-agent baseline to compare against

If you never built and measured (4.9) the one-agent version, you can't actually know the team is better — you're just assuming it. Always have a baseline. Plenty of multi-agent systems perform worse than the soloist they replaced, at several times the cost.

✗ Ignoring the extra cost and latency

Each worker is a full set of model calls, and they add up fast in both dollars and seconds. A team that calls the model fifteen times to answer a question one agent handled in three is a worse system, not a fancier one. Count the calls before you ship.

KEY INSIGHTWhere this connects in your course

  • Planning & decomposition (2.5) — the orchestrator's decompose step is exactly the planning idea, now a real model call that splits a goal into sub-tasks.
  • Reflection (2.6) — the critic worker turns self-review into a separate, focused step with a fresh context.
  • Multi-agent systems (2.7) — this is that conceptual pattern made concrete: orchestrator, workers, "agent as a tool," and its honest trade-offs.
  • Review before you trust (3.6) — the critic automates the review habit you practiced by hand.
  • A real working agent (4.7) — every worker is that agent, given a narrow brief. You built the soloist; here you coordinate a few of them.
  • Evals (4.9) — next: how to measure whether the team actually beats the baseline, instead of just assuming it does.

You now have the whole ladder: one agent, then a coordinated team. The skill isn't building the biggest team — it's knowing the smallest system that gets the job done, and reaching for more structure only when you've proven you need it.

GLOSSARYKey terms introduced

Orchestrator
The coordinating function that decomposes a goal into sub-tasks, dispatches a worker to each, collects the results, and synthesizes a final answer. It delegates rather than doing the work itself.
Worker
An agent run (LLM + tools + loop, from 4.7) given one narrow sub-task and a focused brief; returns a single self-contained result. In code, just a function call.
Decomposition
Splitting a big goal into smaller, focused sub-tasks — here, a model call that returns one task per line (the planning idea from 2.5).
Synthesis
The final step that fuses the workers' partial results into one coherent answer, via a single model call.
Critic
A worker that reviews another agent's output for weaknesses instead of producing the answer — reflection (2.6) as a separate step.
Agent-as-tool
Treating a whole agent as if it were a single function the orchestrator calls: pass a brief in, get a result out, ignore the machinery inside (2.2).
Coordination
The work of managing a team — passing context between agents, parsing results, handling a worker that fails — the real overhead a single agent never has.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1What are the three things an orchestrator does, in order?›

Decompose the goal into sub-tasks (2.5), run a worker on each sub-task and collect the results, then synthesize a final answer with one more model call. Decompose → workers → synthesize. The orchestrator never does the work itself; it delegates and combines.

2In what sense is "an agent calling an agent" just a function call?›

From the caller's view, run_worker(task) takes a string and returns a string — identical to any function. It doesn't matter that inside that function a whole agent (model + tools + loop) ran. A worker is a tool whose implementation happens to be another agent (2.2 / 2.7).

3What does a critic worker add, and why critique only once?›

A critic reviews the draft for weaknesses (reflection, 2.6; review, 3.6) so you can revise once. You bound it because an unbounded critic loop burns money on diminishing returns and can even make the answer worse — every loop needs a hard stop.

4Before building a multi-agent system, what should you always do first — and why?›

Build and measure a single strong agent baseline (4.7, 4.9). Multi-agent costs more in money, latency, failure points, and coordination — so unless the soloist provably can't keep up, the team is just expensive complexity. Most tasks don't need it. Don't over-build.

You can coordinate a team now. Next: prove it actually works →