Claude Certified Developer · Professional
Module 2: Multi-agent architecture that survives production
Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.
On this page
Study notes, not official course material. Our take on official course 2 (durable multi-agent systems, evolved from production evidence). Facts checked 2026-11-25.
The video opens on a terminal that says Killed halfway through a run. After the restart, the log line refund issued appears a second time. The agent didn't remember where it was, so it started again from zero. This module covers two questions people mix up: when is more than one agent worth it, and how do you make any agent run survive a crash without repeating what it already did?
What you'll be able to do
Place a feature on the ladder (single call, fixed workflow, one agent with tools, orchestrator with workers) and name the evidence you'd need to move up a rung.
Diagnose an overloaded agent from traces: wrong tool picked, look-alike tools confused, bloated context.
Split work into specialists with small tool sets and typed handoff contracts that pass ids and summaries, not transcripts.
Write a correct tool loop: all tool results back in one message, failures marked as errors, history kept append-only.
Make runs durable with a checkpoint per step, so a killed process resumes instead of restarting, and side effects don't repeat.
Put hard limits on every run (turns, spend, wall-clock time) and escalate to a person when one is hit.
Compare two architectures on the same ticket set and record the decision in a short ADR.
1. The ladder: start low, climb only with evidence
There are four rungs. Each one up buys flexibility and costs money, latency and debuggability.
| Rung | What it is | Who decides the next step | Good for |
|---|---|---|---|
| 1. Single call | One request, one response | Your code (there is no next step) | Classify, extract, summarise, answer from given context |
| 2. Fixed workflow | Several calls chained by your code | Your code, every time | Triage → retrieve → answer; steps known in advance |
| 3. One agent with tools | The model loops, choosing tools until done | The model | Open-ended tasks whose steps you can't list in advance |
| 4. Orchestrator + workers | One agent delegates to specialist agents | The model, at two levels | Distinct sub-domains, each needing its own tools and context |
Two rules:
Default to the lowest rung that works. Tagging each ticket with a category is rung 1, even if you call it "the tagging agent". A refund question that needs
get_order, then a policy lookup, then maybeissue_refundis a fair candidate for rung 3.Climb with evidence, not taste. The evidence is traces (what went wrong, and where) plus the cost of a wrong answer. "Multi-agent feels more scalable" is not evidence. "Billing tickets pick the wrong tool 18% of the time and each mistake costs a manual refund review" is.
A quick test before you build any agent: is the task hard to specify step by step? Is the outcome worth the extra cost and latency? Can the model actually do it? Can mistakes be caught and undone (tests, review, rollback)? A "no" to any of those means stay lower.
2. Diagnosing v1: one agent, fourteen tools
The course app's v1 is a single agent.ts with fourteen tools: search_docs, get_order, get_invoice, list_orders, issue_refund, update_email, reset_mfa, escalate and six more. Traces from 30 fixed tickets show three failure shapes:
Look-alike tools.
get_order("Get order details") andget_invoice("Get invoice details for an order") overlap. On billing tickets the model picks the wrong one often enough to matter, then has to recover.Bloated context. Every request carries all fourteen tool definitions plus the whole conversation so far. Tool definitions sit at the very front of the prompt, so they cost tokens on every turn.
Mixed instructions. The system prompt carries refund policy, MFA-reset rules and tone guidance for everyone. Rules for one domain leak into others ("always confirm identity" slows down simple doc questions).
Measure before you split. Add one number to the trace review: tool-choice accuracy, the share of tool calls on the 30 tickets that a person marks as the right tool. Then try the cheapest fixes first:
Give look-alike tools sharp, distinct names and descriptions that say when not to use them ("Use for invoice PDFs and tax lines only. For order status, use
get_order."). Or merge them into one tool with a clear argument.Remove tools no ticket in the sample ever needed.
If the tool set is large but genuinely one domain, consider the tool search tool: you mark most tools
defer_loading: true, and the model searches for the ones it needs instead of reading every definition on every turn. At least one tool must stay non-deferred.
If accuracy is still poor after that, or the domains genuinely need different instructions and context, you have the evidence to climb to rung 4.
3. The split: triage, specialists and a reviewer
Design choices worth copying:
Triage is a single call, not an agent. It returns a category from a fixed list. That's rung 1 inside a rung-4 system, and that's fine.
Each specialist has three or four tools. Fewer tools means fewer wrong picks and a smaller prompt.
The reviewer only sees money actions. It's a gate, not a second opinion on everything.
Routing happens in code. The model classifies; your code reads the category and calls the right specialist. The model never decides which tenant, which run or which agent gets authority.
Routing with structured output, not forced tool choice
A common older pattern forced the model to call a "route" tool with tool_choice: {type: "tool", name: ...}. On the current models used here (claude-opus-5-5, claude-sonnet-5-5), forcing a tool call with tool_choice any or tool returns a 400. Use structured output for the decision instead:
import Anthropic from "@anthropic-ai/sdk";
import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
const client = new Anthropic();
const Route = z.object({
category: z.enum(["billing", "technical", "account", "other"]),
order_ids: z.array(z.string()),
summary: z.string(),
});
export async function triage(ticketText: string) {
const r = await client.messages.parse({
model: "claude-haiku-5-5", // a small, fast model is usually enough for routing; prove it with evals
max_tokens: 4000,
messages: [{ role: "user", content: `Route this support ticket:\n\n${ticketText}` }],
output_config: { format: zodOutputFormat(Route) },
});
if (r.stop_reason !== "end_turn" || !r.parsed_output) return null; // caller escalates
return r.parsed_output;
}If you do want the model to call a tool, keep tool_choice on auto, say in the prompt which tool to use, and set strict: true on the tool so its input matches the schema. auto doesn't guarantee a call, so check for a tool_use block.
4. Typed handoffs: ids and summaries, not transcripts
The bad handoff: triage passes the billing agent the whole 40-message conversation, every tool result included. The billing agent pays for all of it on every turn, and the one fact it needs ("order A-1093 was already partly refunded") is buried in message 23.
A handoff is an interface between two programs. Treat it like one: a schema, validated on both sides.
import { z } from "zod";
export const BillingHandoff = z
.object({
run_id: z.string().uuid(),
ticket_id: z.string(),
order_ids: z.array(z.string()).min(1),
summary: z.string().max(1500), // what the customer wants, in plain words
already_refunded: z.boolean(), // required: the reviewer depends on it
customer_tier: z.enum(["standard", "priority"]),
})
.strict(); // unknown keys are an error, not silently ignored
export type BillingHandoff = z.infer<typeof BillingHandoff>;
// Sender validates before handing off; receiver validates again on arrival.
export function receiveBilling(raw: unknown): BillingHandoff {
return BillingHandoff.parse(raw); // throws loudly on a missing or renamed field
}Why validate on both sides: the sender's check catches its own bugs; the receiver's check catches a sender deployed from a different version of the contract. Module 6's incident (duplicate refunds) starts exactly here: a deploy changed the contract, already_refunded stopped arriving, and the reviewer treated "missing" as "false".
What the handoff deliberately leaves out:
The tenant. The tenant was set on the run record from the verified token (Module 1) and stays there. A handoff is written partly by a model, and anything a model writes can be steered by prompt injection. The receiving agent reads the tenant from the run, never from the handoff.
The transcript. If the specialist needs a detail, it should be a field. If it needs the source, pass an id it can fetch through a tool that's scoped to the tenant.
5. A correct tool loop
Every agent in the system runs some version of this loop. On the Messages API you can write it yourself (full control), or use the SDK's Tool Runner helper (client.beta.messages.toolRunner(...) in TypeScript), which runs the loop over tools you define and still lets you hook in approvals and error handling. Two other options exist: Managed Agents (beta), where Anthropic hosts the loop and a per-session sandbox and agent configs are stored and versioned, and the Claude Agent SDK, a separate product that packages the Claude Code harness with built-in file and shell tools. The course app writes the loop by hand so you can see every step:
const MAX_TURNS = 12;
export async function runAgent(system: string, tools: Anthropic.Tool[], first: string) {
const messages: Anthropic.MessageParam[] = [{ role: "user", content: first }];
for (let turn = 0; turn < MAX_TURNS; turn++) {
const msg = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system,
tools,
messages,
});
// Append the full content (thinking blocks included), unchanged. Never edit history.
messages.push({ role: "assistant", content: msg.content });
if (msg.stop_reason !== "tool_use") return { msg, messages };
const calls = msg.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
const results = await Promise.all(
calls.map(async (c): Promise<Anthropic.ToolResultBlockParam> => {
try {
return { type: "tool_result", tool_use_id: c.id, content: JSON.stringify(await runTool(c.name, c.input)) };
} catch (err) {
return { type: "tool_result", tool_use_id: c.id, content: String(err), is_error: true };
}
}),
);
messages.push({ role: "user", content: results }); // all results, one message
}
return { escalate: "max turns reached", messages };
}Four rules hidden in that code:
All tool results go back in one user message. When the model asks for
get_orderandsearch_docsin the same turn, run them in parallel and return both results together. Splitting them across separate messages teaches the model to stop making parallel calls.A failed tool returns a result with
is_error: true. Don't drop it, and don't pretend it succeeded. The model can then retry, pick another tool or give up honestly.History is append-only. Pass
response.contentback exactly as received. On the newest models, thinking blocks are tied to the conversation that produced them; editing or deleting earlier messages can invalidate them, and it also breaks prompt caching from the edited point onwards. If context gets too large, use a supported server-side feature or start a fresh sub-run from a summary. Don't rewrite the past.The loop has a ceiling.
MAX_TURNSis the simplest one. Section 7 adds spend and time.
6. Durable runs: checkpoint every step
The crash in the video: the billing agent issued a refund at step 4, the process was killed at step 5, and the restart began at step 1 with a fresh conversation. Step 4 ran again.
The fix is to treat a run like a small database transaction log. Every run has an id. Every step writes a checkpoint row before the run moves on. On restart, completed steps are replayed from their saved output instead of being executed.
CREATE TABLE runs (
run_id uuid PRIMARY KEY,
tenant_id text NOT NULL, -- from the verified token, set once
ticket_id text NOT NULL,
status text NOT NULL CHECK (status IN ('running', 'done', 'escalated', 'failed')),
turns int NOT NULL DEFAULT 0,
started_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE run_steps (
run_id uuid NOT NULL REFERENCES runs,
step int NOT NULL,
agent text NOT NULL,
input_hash text NOT NULL,
output jsonb NOT NULL,
PRIMARY KEY (run_id, step)
);import { createHash } from "node:crypto";
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
// Run one step at most once per run. On resume, return the saved output.
export async function step<T>(runId: string, n: number, agent: string, input: unknown, fn: () => Promise<T>): Promise<T> {
const hash = sha256(JSON.stringify(input)); // ponytail: assumes our code builds inputs in a fixed key order; use a stable stringify if not
const { rows } = await pool.query(
"SELECT input_hash, output FROM run_steps WHERE run_id = $1 AND step = $2",
[runId, n],
);
if (rows[0]) {
if (rows[0].input_hash !== hash) throw new Error(`run ${runId} step ${n}: input changed since checkpoint`);
return rows[0].output as T;
}
const out = await fn();
await pool.query(
"INSERT INTO run_steps (run_id, step, agent, input_hash, output) VALUES ($1, $2, $3, $4, $5)",
[runId, n, agent, hash, JSON.stringify(out)],
);
return out;
}Usage in the orchestrator:
const route = await step(runId, 1, "triage", { ticketId }, () => triage(ticketText));
const handoff = await step(runId, 2, "triage", { route }, () => buildBillingHandoff(runId, route));
const result = await step(runId, 3, "billing", { handoff }, () => billingAgent(receiveBilling(handoff)));The crash window inside a step
A checkpoint is written after the step finishes. If the process dies after the refund but before the INSERT, the resume runs that step again. The checkpoint alone can't close this gap. Idempotent side effects close it (Module 1):
Key by run and step (
refund:${runId}:3) when "the same run must never do this twice" is the rule.Key by business intent (
refund:${tenant}:${ticket}:${order}) when "this order must never be refunded twice for this ticket, by any run" is the rule.
For money, use the business key: a customer who reopens the ticket starts a new run, and the run-and-step key wouldn't stop that one. Pass the same key to the payment provider so the provider dedupes too.
Why the input hash
If a deploy changes step 2's code and a half-finished run resumes, step 3's saved output may no longer match its new input. The hash check turns that silent mismatch into a loud error, and the run escalates instead of acting on stale data.
What not to do
Don't wrap the whole run in one database transaction. Runs last seconds to minutes and call external APIs. A rollback can't un-send a refund.
Don't ask the model "did you already refund?" on restart. A fresh conversation has no memory of the first one. The truth is in your database.
7. Limits: every run ends, one way or another
A worker fails (get_order returns a 500), and the orchestrator keeps retrying and re-planning for 60 turns. Nobody noticed until the invoice arrived.
Every run needs three hard limits, enforced in code and checked on every turn:
const LIMITS = { maxTurns: 12, maxCostUsd: 0.5, maxMs: 120_000 }; // per run; tune from your own traces
function checkLimits(run: { turns: number; costUsd: number; startedMs: number }) {
if (run.turns >= LIMITS.maxTurns) return "turn limit";
if (run.costUsd >= LIMITS.maxCostUsd) return "spend limit";
if (Date.now() - run.startedMs >= LIMITS.maxMs) return "time limit";
return null;
}
// In the loop: const breach = checkLimits(run); if (breach) return escalate(run, breach);The cost figure is your own estimate from each response's usage fields and your price table (Module 3). It doesn't need to be exact to stop a runaway.
Inside the worker, retries are bounded and live in code: retry a 500 from your own API twice with backoff, then return the error to the model as an is_error tool result. The model decides whether there's another way. If not, it says so, and the run escalates. On a breach, the run goes to a human queue with its run id, the last checkpoint and the reason. It never loops on.
There is also a beta API feature called task budgets: you give the model a token budget for the whole agentic loop (output_config.task_budget, beta header task-budgets-2026-03-13, minimum total 20,000 tokens), and the model paces itself to finish within it. It's advisory. The model knows about it and plans around it, but it's not an enforced cap. Use it to help the model finish gracefully; keep the hard limits in your code anyway. It's also different from max_tokens, which is an enforced per-response cap that the model isn't aware of.
8. Caching in a multi-agent system
Two facts shape the design (Module 8 goes deeper):
Caches are per model. A triage on Haiku, specialists on Opus and a reviewer on Sonnet means three separate caches. A cascade of models gives up cache reuse between them.
Parallel workers with slightly different prefixes share nothing. Five workers each with their own system prompt over the same 30,000 tokens of docs write five separate cache entries and read none of each other's. A cache entry also only becomes readable once the first response has started streaming, so five identical requests fired at the same instant all pay full price.
The fix for fan-out: give workers a byte-identical shared prefix (same model, same tools, same system prompt, shared docs first) and put the worker-specific instruction at the end. Send one request, wait for its first streamed token, then send the rest. Side calls (a summariser, a reviewer of the same conversation) should copy the parent's system, tools and model exactly and add their own instruction at the end.
9. Evolve from evidence: v1 against v2, then an ADR
After the split, run both architectures on the same 30 tickets. The numbers below are fictional, for the lab:
| Metric (30 fixed tickets) | v1: one agent, 14 tools | v2: triage + 3 specialists + reviewer |
|---|---|---|
| Correct outcome | 22 / 30 | 27 / 30 |
| Tool-choice accuracy | 81% | 96% |
| Relative cost per ticket | 1.0× | 0.8× |
| p95 time to answer | 1.0× | 1.15× |
| Tickets using the account specialist | n/a | 1 / 30 |
v2 wins on accuracy and cost (smaller prompts per agent) and loses a little on latency (an extra hop). The account specialist handled one ticket in 30 and did no better than the generalist on it, so it is merged back into the technical agent. Not every agent earns its keep.
Record the decision where the next engineer will find it:
# ADR 0001: Split billing out of the single agent
Status: accepted, 2026-11-25
Context: v1 confused get_order/get_invoice on billing tickets (tool-choice accuracy 81% on the 30-ticket set).
Decision: triage (structured call) → billing / technical specialists + reviewer for refunds over the limit.
Account specialist merged back into technical (1/30 tickets, no accuracy gain).
Evidence: eval run 2026-11-25, set m02-30, results in evals/m02/2026-11-25.json.
Consequences: +1 hop on p95; contract tests required for every handoff schema.
Revisit when: tool-choice accuracy drops below 90%, or a new domain exceeds 15% of tickets.Trade-offs
One agent vs specialists. One agent has one prompt, one cache and one trace to read; it degrades as tools and rules pile up. Specialists have sharper prompts and fewer tools, but add hops, contracts and more things to version.
Writing the loop vs Tool Runner vs Managed Agents vs the Agent SDK. Your own loop gives full control and no beta dependency. Tool Runner removes the loop code but keeps you hosting. Managed Agents (beta) hosts the loop and a sandbox and stores agent configs, at the cost of a beta dependency and session-runtime billing. The Agent SDK gives you Claude Code's harness and built-in tools to run on your own infrastructure.
Summaries vs ids in handoffs. Summaries are cheap to read but lossy; ids are exact but need a tool call to fetch. Use both: a summary for intent, ids for anything the agent will act on.
Run-and-step vs business-intent idempotency keys. Run-and-step stops a resumed run repeating itself; a business key stops any run repeating an action. Money needs the business key.
Model per role. Smaller models for triage and review save cost and latency but give up cache sharing with the main model. Prove each choice with the eval (Module 4).
Common mistakes
Building an orchestrator for a task a single structured call can do.
Splitting into agents before trying sharper tool names and descriptions, or before measuring tool-choice accuracy.
Routing with forced
tool_choiceon models that reject it, or letting the model choose the tenant or the target agent's authority.Passing the whole transcript as the handoff; validating the handoff only on the sending side; letting unknown or missing fields through silently.
Sending parallel tool results in separate messages, or dropping failed tool results instead of marking them
is_error.Trimming or rewriting history between turns to "save tokens", which breaks caching and can invalidate thinking blocks.
Restarting crashed runs from step 1, or wrapping a whole run in one transaction.
Relying on a prompt line ("stop after a few tries") or an advisory budget instead of hard limits in code.
Comparing v1 and v2 on different tickets, or on vibes, and not writing the decision down.
Remember
Lowest rung that works. Climb only with evidence from traces and the cost of a wrong answer.
Few tools per agent, sharp names, and measure tool-choice accuracy before you split.
Handoffs are schemas: ids plus a summary, validated on both sides. The tenant lives on the run, never in the handoff.
All tool results in one message; failures as
is_error; history append-only.Every run has an id, every step a checkpoint, every side effect an idempotency key.
Max turns, max spend, max time, enforced in code; on a breach, a person takes over.
Same tickets for v1 and v2, then an ADR. Merge back agents that don't earn their keep.
Check before relying on it
Forced
tool_choice(any/tool) returning a 400 onclaude-opus-5-5andclaude-sonnet-5-5was documented on 2026-11-25; older models accept it.Task budgets are beta (header
task-budgets-2026-03-13, minimum total 20,000 tokens); the shape and model support may change.Tool Runner (
client.beta.messages.toolRunner) and Managed Agents are beta surfaces; Managed Agents also has its own beta multi-agent features, not covered here.The tool search tool (
defer_loading) type names carry dates; check the current version string and limits.Thinking blocks tied to the conversation (the history-editing check on the newest models) applies by model and, for some models, by account creation date; check the migration guide for your model.