ProjekinAja. Agentic AI Stage 5 · Multi-Agent Automation Lesson 5.4
● Stage 5 · Lesson 5.4

Build It in Code — A Multi-Agent Automation End to End

Everything from this stage, assembled into one runnable program: a manager that delegates to specialist workers, a critic that reviews, and a shared state that ties it all together.

⏱ ~20 min read 🏗️ The Stage 5 capstone 🐍 One full pipeline

🎯 By the end you'll understand

How the ideas from this stage — when to use a team, orchestrator-worker + critic architectures, and roles, communication & shared state — combine into one coherent Python program: a research → write → review → revise → publish content pipeline, with focused role prompts, a shared-state dict, and a bounded revision loop. You'll read it top to bottom and know exactly how to run it.

KEY INSIGHTThe one idea to take away

A multi-agent automation is not a framework. It's a handful of focused prompts, one reusable model-call helper, a plain dict everyone reads and writes, and an orchestrator function with a stop condition — a single file you can fully understand.

For three lessons you've held the ideas in your head: when a team beats a soloist (5.1), the orchestrator-worker and critic shapes (5.2), and how agents coordinate through roles and a shared state (5.3). This lesson does the last thing: snaps them together into pipeline.py — a program that actually produces a finished article from a topic.

It builds straight on Stage 4. The single-agent loop from Lesson 4.7 becomes a reusable run_agent helper; the orchestrator-and-workers code from Lesson 4.8 grows a real shared state and a critic-driven revision loop. Same parts, assembled into a working automation.

🔑 Hold onto this

Every part of this program maps to a Stage 5 idea. The role prompts are roles (5.3). The orchestrate function is the orchestrator delegating to workers + a critic (5.2). The state dict is shared state — the workspace everyone reads and writes (5.3). The bounded revision loop is the critic loop with a hard stop (5.2). Nothing new — just everything, at once.

PRACTICALThe project: a content pipeline

Abstract "multi-agent systems" don't stick. A concrete job does. So we'll build something a real team does every day: take a topic in, and produce a finished, reviewed article out. The work flows through five stages, each owned by a role:

🔎 Research → notes ✍️ Write → draft 🔍 Review → issues? 🛠️ Revise ≤ 2 rounds 📤 Publish → final

Three things make this a genuine multi-agent automation rather than one long prompt:

🎭

Specialist roles

A researcher, a writer, and a critic — each a focused system prompt (5.3). One model, three hats, each worn in its own clean context.

🧭

An orchestrator

One orchestrate(goal) function that runs the roles in order and decides what happens next — including whether to revise (5.2).

📋

A shared state

A plain dict — {topic, notes, draft, review, final} — that every role reads from and writes to. The workspace that ties the team together (5.3).

▸ The whole automation in one sentence

An orchestrator runs specialist roles (researcher → writer → critic → reviser) over a shared-state dict, with a bounded revision loop as its stop condition. That's the Stage 5 picture, finally assembled and running.

FRAMEWORKThe program, mapped

Before the code, hold the map. The file has four sections, in this order, and each one is something you already learned:

SectionWhat it isFrom lesson
① Setupimports, the client, the model id, the step/revision budgets4.7
② run_agent helperone reusable function that calls the model (and loops on tools if given any)4.7 · 4.8
③ Rolesthree focused system prompts: researcher, writer, critic5.3
④ orchestrateruns the roles over the shared state, with a bounded revision loop5.2 · 5.3

We'll write them in exactly that order — that's how the file reads top to bottom, and each section depends only on the ones above it. Setup, then the one helper every role uses, then the roles, then the orchestrator that drives them.

💡 Read it as one program, in pieces

The four code blocks below are one file — pipeline.py — split at natural seams so we can talk about each part. Concatenate them in order and you have the complete, runnable program. The comments tag each piece back to its lesson.

CORE CONCEPT① Setup

The top of the file does the usual three things: import what we need, create the client (which reads the API key from the environment — never hardcode it), and declare a couple of constants. The constants up top are budgets: how many model turns a tool-using agent may take, and how many revision rounds the pipeline will tolerate before it ships anyway.

pipeline.py · ① setuppython
import os
import anthropic                              # the SDK (pip install anthropic) — 4.4

client = anthropic.Anthropic()               # reads ANTHROPIC_API_KEY from the env — never hardcode
MODEL = "claude-sonnet-5"                  # the brain (1.3) — model ids drift over time
MAX_STEPS = 6                                # step budget if a role uses tools — stop condition (2.9)
MAX_REVISIONS = 2                            # the REVISION BUDGET — caps the critic loop (5.2)

Two budgets, two stop conditions. MAX_STEPS bounds any single agent's internal tool loop (the same step budget from 4.7). MAX_REVISIONS bounds the outer loop — how many times the critic can send the draft back. Both sit at the top as named constants so the limits are impossible to miss, and impossible to forget.

CORE CONCEPT② The run_agent helper

Every role in this pipeline is just a model call with a different system prompt. So we write the call once, as a reusable helper, and let all three roles share it. run_agent(system, user, tools=None) takes a role's system prompt and a user message, and returns the model's final text.

The key correctness point: there are two paths. If you pass no tools, it's a single call. If you do pass tools, it runs the full agent loop from 4.7 — call the model, dispatch any tool the model requests, append the result with a matching tool_use_id, and go again until the model stops asking for tools. Either way it returns clean text.

pipeline.py · ② the run_agent helperpython
def final_text(response):
    """Pull the text out of a response — robustly. Never response.content[0].text."""
    return next((b.text for b in response.content if b.type == "text"), "")


def run_agent(system, user, tools=None, dispatch=None):
    """Run one role. No tools -> one call. With tools -> the agent loop (4.7)."""
    messages = [{"role": "user", "content": user}]

        if not tools:                                  # --- simple path: one model call ---
            response = client.messages.create(
                model=MODEL, max_tokens=1500,
                system=system, messages=messages,
            )
            return final_text(response)

    # --- tool path: the agent loop, bounded by MAX_STEPS (4.7 / 2.9) ---
    dispatch = dispatch or {}
    response = None
    for _ in range(MAX_STEPS):
        response = client.messages.create(
            model=MODEL, max_tokens=1500,
            system=system, tools=tools, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":        # model went quiet -> done
            break

        results = []                                   # dispatch every tool the model asked for
        for block in response.content:
            if block.type == "tool_use":
                fn = dispatch.get(block.name)
                out = fn(block.input) if fn else f"Unknown tool: {block.name}"
                results.append({"type": "tool_result",
                    "tool_use_id": block.id, "content": str(out)})
        messages.append({"role": "user", "content": results})  # observe -> loop

    return final_text(response)

Three details earn their keep. First, final_text walks the content blocks and grabs the first text block — it never assumes response.content[0] is text, because the first block might be a tool_use block, and .text would crash. Second, on the tool path each tool_result carries the matching tool_use_id and is appended as a user turn — that's how the SDK pairs a result back to the request. Third, the loop is bounded by MAX_STEPS, so even a tool-using role can't spin forever.

📖 The reusable agent call

run_agent(system, user) is the single seam every role talks through. Give it a role's system prompt and a message, get back text. Because all three roles share it, the pipeline stays tiny — change the call once and every role benefits.

For this pipeline our roles don't actually need tools — they reason over text — so we'll call them via the simple path. The tool path is included because it's the same helper you'd use the moment a role needs a real web_search (4.7); the orchestrator wouldn't change at all.

CORE CONCEPT③ The specialist roles

A role (5.3) is nothing more than a focused system prompt. Each one narrows the same model to a single job and a single output. We define three: a researcher who gathers notes, a writer who turns notes into a draft, and a critic who reviews the draft for issues. (The "reviser" reuses the writer — it's the writer with the critic's notes in hand, so it doesn't need its own prompt.)

pipeline.py · ③ roles (system prompts)python
# Each role = a focused system prompt (5.3). Same model, three different hats.

RESEARCHER = """You are a Researcher. Given a topic, produce concise, factual notes:
5-8 bullet points covering the key ideas, terms, and any important caveats.
Notes only — no intro, no prose, no conclusion. If unsure, say so plainly."""

WRITER = """You are a Writer. Using ONLY the research notes provided, write a clear,
engaging ~250-word article for a general reader. Use a short title and 2-3
paragraphs. Do not invent facts beyond the notes. Return the article only."""

CRITIC = """You are a Critic. Review the draft against the topic and notes.
Find concrete problems: factual gaps, unclear sentences, weak structure, claims
not supported by the notes. Then respond in EXACTLY this format:

VERDICT: PASS
  (use PASS only if the draft is solid; otherwise use REVISE)
ISSUES:
- <one specific, actionable issue per line; omit this section if PASS>
Be strict but fair. Prefer at most 3 issues, the most important first."""

The discipline lives in the prompts. The researcher returns notes only — no prose to muddy the next step. The writer is told to use only the notes, which keeps it honest and grounded (no hallucinated facts). And the critic returns a structured verdict: a first line of VERDICT: PASS or VERDICT: REVISE, then issues. That structure is what lets the orchestrator make a decision from the critic's reply instead of guessing — a tiny, deliberate communication protocol between agents (5.3).

💡 Why a fixed reply format matters

When one agent's output becomes another's control flow, you need it to be parseable. Asking the critic for a literal VERDICT: line is the cheapest possible structured protocol — no JSON, no schema, just a convention both sides agree on. The orchestrator reads the first word after VERDICT: and knows whether to revise. (Communication patterns, 5.3.)

CORE CONCEPT④ orchestrate(goal) — the heart of it

Now the boss. The orchestrator owns the shared state — a plain dict it creates, then fills in as each role runs. It calls researcher → writer → critic in order, and if the critic says REVISE, it loops the writer with the critic's notes — at most MAX_REVISIONS times — before publishing whatever it has. Read the highlighted block as the beating heart of the program.

pipeline.py · ④ the orchestratorpython
def orchestrate(goal):
    """Research -> write -> review -> (revise) -> publish, over a shared state."""
        state = {                                        # the SHARED STATE: the team's workspace (5.3)
            "topic": goal,
            "notes": None, "draft": None, "review": None, "final": None,
        }

    # 1. RESEARCH — researcher reads topic, writes notes
    print("🔎 researcher: gathering notes…")
    state["notes"] = run_agent(RESEARCHER, f"Topic: {state['topic']}")

    # 2. WRITE — writer reads notes, writes the first draft
    print("✍️  writer: drafting…")
    state["draft"] = run_agent(WRITER,
        f"Topic: {state['topic']}\n\nNotes:\n{state['notes']}")

    # 3+4. REVIEW & REVISE — bounded critic loop (5.2). Stop on PASS or budget.
    for rnd in range(MAX_REVISIONS + 1):       # 1 review + up to MAX_REVISIONS rounds
        print(f"🔍 critic: reviewing (round {rnd})…")
        state["review"] = run_agent(CRITIC,
            f"Topic: {state['topic']}\n\nNotes:\n{state['notes']}"
            f"\n\nDraft:\n{state['draft']}")

        if "VERDICT: PASS" in state["review"].upper():   # stop condition: critic approves
            print("   ✅ critic: PASS")
            break
        if rnd == MAX_REVISIONS:                  # budget spent — ship what we have
            print("   ⚠️ revision budget reached — publishing latest draft.")
            break

        # reviser = the writer, now holding the critic's issues
        print("   🛠️  reviser: applying critic notes…")
        state["draft"] = run_agent(WRITER,
            f"Topic: {state['topic']}\n\nNotes:\n{state['notes']}"
            f"\n\nYour previous draft:\n{state['draft']}"
            f"\n\nThe critic asked you to fix:\n{state['review']}"
            f"\n\nRewrite the article addressing every issue. Return the article only.")

    # 5. PUBLISH — the approved (or budget-capped) draft becomes the final
    state["final"] = state["draft"]
    print("📤 published.\n")
    return state

Walk the structure slowly, because this is the automation:

📖 Bounded critic loop

A critic loop repeats "draft → review → revise" to improve quality. Bounded means it has a stop condition: it ends when the critic approves or when it hits the revision budget. Without that cap, two agents can ping-pong forever — the critic always finds something, the writer always changes something — burning money on diminishing returns (5.2).

And the run block at the very bottom — the line that actually kicks it off:

pipeline.py · ④ run itpython
if __name__ == "__main__":
    result = orchestrate("How honeybees navigate using the sun")
    print("=" * 60)
    print(result["final"])              # the finished, reviewed article

SEE ITRun the pipeline

Here's orchestrate("How honeybees navigate using the sun") executing, beat by beat. Press ▶ Step to walk one full run: the researcher gathers notes → the writer drafts → the critic reviews (and finds two issues) → the reviser fixes them → the critic passes → it publishes. Watch the shared-state dict grow on the right, and which role/function is active on the left. Or hit Run all.

🏗️ Interactive · One complete pipeline run, beat by beat

Goal: “How honeybees navigate using the sun.”  ·  Revision budget: 2

Ready

Press ▶ Step to begin. We'll run the pipeline on one topic, end to end.

Active role: —

shared state · the dict
Beat 0 of 0

Notice the rhythm: research → write → review → revise → review → publish. No role talks to another directly; they communicate entirely through the dict — one writes notes, the next reads it. And the revision budget sits over the loop like a guardrail: even if the critic kept finding issues, the run would publish after round 2 rather than ping-ponging forever.

PRACTICALHow to actually run it

This isn't a thought experiment — paste the four sections into one pipeline.py and it runs. Three commands stand between you and a working content pipeline on your own machine:

terminalshell
# 1. install the SDK
pip install anthropic

# 2. set your API key as an environment variable (never in the code — 4.10)
export ANTHROPIC_API_KEY="sk-...your-key..."

# 3. run it
python pipeline.py

What you'll see: a trace of each role firing — researcher, writer, critic, maybe a reviser, then "published" — followed by the finished article. Change the topic string in the run block and you've got a reusable little newsroom: hand it a subject, get back a reviewed draft. Every model call goes through the one run_agent helper, so the cost is just "a few calls per run, plus one per revision round."

💡 Make it more real in one edit

The researcher currently reasons from the model's own knowledge. Give it a real web_search tool — define the function and schema (4.7), then call run_agent(RESEARCHER, msg, tools=SEARCH_TOOLS, dispatch=SEARCH_FNS). The tool path in run_agent handles the loop, and orchestrate doesn't change a line. That's the payoff of one shared helper.

WEAKNESSHonest notes — what this is and isn't

You now have a real multi-agent automation. It's simple on purpose — every line is readable — and being honest about its limits is part of using it well.

⚠️ This is a real pipeline — but not a production one

It works and teaches every Stage 5 idea, but it has no error handling (a network blip crashes the run), no retries on a failed call, no observability beyond print, and no cost caps beyond the step/revision budgets. A production version adds reliability (retries, timeouts), logging/tracing so you can see what each agent did, and hard spend limits. That's the focus of Lesson 5.7. The skeleton here is correct; production is this skeleton hardened.

⚠️ A single strong agent might be enough

For a simple topic, one good prompt to one capable agent ("research and write a reviewed ~250-word article on X") may match this pipeline at a fraction of the cost and latency. The team earns its keep when the work genuinely separates into specialist steps and the critic measurably improves quality. Always compare against the soloist baseline first (5.1) — don't build a newsroom for a tweet.

Neither caveat makes the pipeline wrong. They make it honest: a correct foundation you'd harden for production and reach for only when a soloist can't keep up.

WEAKNESSCommon mistakes to avoid

✗ No stop condition on the revision loop

If the critic loop has no cap, two agents ping-pong forever: the critic always finds some nit, the writer always changes something, and you pay for model calls until you notice the bill. Bound it — for rnd in range(MAX_REVISIONS + 1) with a PASS break. Every loop in an agentic system needs a hard stop (5.2, 4.7).

✗ Blindly reading response.content[0].text

The first content block isn't guaranteed to be text — when the model uses a tool, block 0 is a tool_use block with no .text, and your program crashes mid-run. Always pull text defensively: next((b.text for b in response.content if b.type == "text"), ""). Our final_text helper does exactly this so every role is safe.

✗ Reaching for a team a soloist would nail

The most common over-build. A content pipeline is satisfying to write, but for an easy topic one strong agent does the same job cheaper and faster, with one thing to debug instead of four. Build and measure the single-agent baseline first (5.1); add roles only when the soloist provably can't keep up. Complexity you don't need is just bugs you haven't met yet.

KEY INSIGHTWhere this connects in your course

  • A real working agent (4.7) — the run_agent helper is that single-agent loop, made reusable so every role shares it.
  • Multi-agent in code (4.8) — orchestrate is the orchestrator-and-workers + critic pattern from that lesson, now with a real shared state and bounded revision loop.
  • When to use a team (5.1) — the honest notes are this lesson's "compare to a soloist first" applied to our own pipeline.
  • Orchestrator-worker & critic (5.2) — the architecture we just implemented: a boss delegating to roles, with a critic and a bounded loop.
  • Roles, communication & shared state (5.3) — the three role prompts, the critic's VERDICT: protocol, and the state dict are exactly these ideas in code.
  • Reliability, observability & cost (5.7) — next on the production path: error handling, retries, tracing, and hard spend caps on top of this skeleton.

This is the summit of Stage 5's "build it yourself" arc. You no longer just describe multi-agent systems — you've written one from import to published article, and you understand every line. Up next, Lesson 5.5 shows how a no-code tool like n8n expresses this same pipeline visually.

GLOSSARYKey terms introduced

Pipeline
A multi-agent automation where work flows through ordered stages — here research → write → review → revise → publish — each owned by a role, with the output of one stage feeding the next.
Orchestrator
The coordinating function (orchestrate) that runs the roles in order, reads and writes the shared state, and decides what happens next. It delegates the work rather than doing it itself (5.2).
Specialist agent
A role: the same model narrowed by a focused system prompt to one job and one output — researcher, writer, or critic (5.3).
Critic loop
The repeated "draft → review → revise" cycle that improves quality, driven by a critic agent — and bounded so it stops on approval or a budget (5.2).
Shared state dict
The plain dictionary ({topic, notes, draft, review, final}) every role reads from and writes to — the team's workspace, how agents coordinate without talking directly (5.3).
Revision budget
The cap on how many revision rounds the critic loop may run (MAX_REVISIONS) before publishing whatever it has — the stop condition that prevents infinite critic ping-pong.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1What are the four sections of pipeline.py, and which Stage 5 idea does each map to?›

① Setup (client, model id, the step and revision budgets), ② the run_agent helper (one reusable model call, with a tool loop if given tools — 4.7), ③ roles (researcher / writer / critic as focused system prompts — 5.3), and ④ orchestrate (runs the roles over the shared-state dict with a bounded revision loop — 5.2). Concatenated in order, they form one runnable file.

2What is the shared state, and how do the roles use it to coordinate?›

It's a plain dict — {topic, notes, draft, review, final} — that the orchestrator creates and fills in as the run proceeds. Each role reads the keys it needs and writes the one it owns: the researcher writes notes, the writer reads notes and writes draft, the critic reads both and writes review. The agents never message each other directly — they coordinate entirely through this shared workspace (5.3).

3What two things end the revision loop, and why does it need a stop condition at all?›

It ends when (a) the critic returns VERDICT: PASS (the draft is good — break) or (b) it hits MAX_REVISIONS rounds (publish what we have). Without a cap, the critic and writer can ping-pong forever — the critic always finds some nit, the writer always changes something — burning model calls and money on diminishing returns (5.2).

4Why is response.content[0].text dangerous, and what should you do instead?›

The first content block isn't always text — when the model calls a tool, block 0 is a tool_use block that has no .text attribute, so the access crashes the run. Pull text defensively by scanning for the first text block: next((b.text for b in response.content if b.type == "text"), ""). Our final_text helper does this so every role stays safe.

You built a whole multi-agent automation. Next: the same pipeline, no-code →