One incident-triage agent, built three times over. Build it once and you learn the loop. Build it three times and you can finally say, from experience, what a framework buys you and what it quietly takes.
Here is the task. An alert fires for delivery zone LDN-CENTRAL-03. The agent gathers state, decides whether this is a genuine incident, and either resolves it or pages the on-call engineer.
Why this and not the usual research-assistant demo? Because one of its tools wakes a person at three in the morning. That gives every design decision on this page a cost you can name.
Three implementations follow, in this order: no framework, CrewAI, LangGraph. The order is not neutral. Anthropic’s own guidance is to start by calling the API directly, because frameworks “often create extra layers of abstraction that can obscure the underlying prompts and responses, making them harder to debug”.
That is not an argument against frameworks. It is an argument for knowing what sits underneath one before you have to debug through it during an incident.
Read across a row to compare the three, or down a column for one of them. Four rows are close enough that preferring one is mostly taste. The third row is not, and it is the whole argument. Select an implementation for the verdict.
One requirement decides this: a human approval that survives a deploy. Take it away and the eighty-line version wins on every axis you care about at 3am.
The tool definitions below carry more of this agent’s quality than the system prompt does. Two things to look for as you read them.
First, there are three tools and only one has a side effect. That one spends a whole sentence of its description on when not to use it. That sentence prevents more spurious pages than any amount of prompt tuning.
Second, the documented empty case on recent_advisories. An empty list is the common case here, not a failure. A model that has not been told so will read it as a broken tool and call it again with different arguments. Half of what looks like reasoning failure is really an undocumented normal case.
TOOLS = [
{
"name": "get_zone_state",
"description": (
"Current operational state for one delivery zone: riders on shift, "
"orders in flight, utilisation, predicted demand for the next hour. "
"Returns nulls if the zone is closed - that is not an error."
),
"input_schema": {
"type": "object",
"properties": {
"zone_id": {"type": "string", "description": "e.g. LDN-CENTRAL-03"},
},
"required": ["zone_id"],
"additionalProperties": False,
},
"strict": True,
},
{
"name": "recent_advisories",
"description": (
"Advisories active in this zone in the last N minutes - roadworks, "
"weather, a planned restaurant outage. An empty list means none are "
"active. That is the common case, not a failure."
),
"input_schema": {
"type": "object",
"properties": {
"zone_id": {"type": "string"},
"minutes": {"type": "integer", "minimum": 5, "maximum": 240},
},
"required": ["zone_id", "minutes"],
"additionalProperties": False,
},
"strict": True,
},
{
"name": "escalate",
"description": (
"Page the on-call engineer. Use ONLY when the zone is degraded and "
"no advisory already explains the degradation."
),
"input_schema": {
"type": "object",
"properties": {
"zone_id": {"type": "string"},
"severity": {"type": "string", "enum": ["low", "medium", "high"]},
"reason": {"type": "string", "description": "One line, for the pager"},
},
"required": ["zone_id", "severity", "reason"],
"additionalProperties": False,
},
"strict": True,
},
]Roughly forty lines, guards included. The version without guards is a version you rewrite in week one, so they are here from the start.
Three details are where the real bugs live, and all three are marked in the comments. Tool results go back on a user message. Each result’s content is a string. And the loop branches on stop_reason rather than on whether a tool call happened to be present.
import json
from anthropic import Anthropic
client = Anthropic()
MODEL = "claude-opus-5"
SYSTEM = (
"You triage delivery-zone alerts. Gather state before deciding. "
"If an advisory already explains the degradation, do not escalate. "
"Stop as soon as you have a decision."
)
def triage(zone_id, max_turns=8, budget_usd=0.50):
messages = [{"role": "user", "content": f"Alert fired for zone {zone_id}."}]
spent, seen = 0.0, set()
for _turn in range(max_turns): # guard: iteration cap
r = client.messages.create(
model=MODEL, max_tokens=2048, system=SYSTEM,
tools=TOOLS, messages=messages,
)
spent += price(r.usage)
if spent > budget_usd: # guard: spend cap
return manual_ticket(zone_id, "budget exceeded")
messages.append({"role": "assistant", "content": r.content})
# Branch on stop_reason, never on "no tool_use block in the reply".
if r.stop_reason == "max_tokens": # truncation, not a decision
return manual_ticket(zone_id, "model reply truncated")
if r.stop_reason != "tool_use":
return decision_from(r)
results = []
for block in r.content:
if block.type != "tool_use":
continue
key = (block.name, json.dumps(block.input, sort_keys=True))
if key in seen: # guard: repeat detector
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": "Repeat call. You already have this result. Decide now.",
"is_error": True,
})
continue
seen.add(key)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
**run_tool(block.name, block.input), # content is a STRING
})
# Tool results go back on a USER message.
messages.append({"role": "user", "content": results})
return manual_ticket(zone_id, f"no decision in {max_turns} turns")The seen set is six lines, and it is doing more work than it looks like. The largest published study of multi-agent failures derived 14 failure modes from 150 hand-annotated traces (Cohen’s κ = 0.88), then scaled the labelling to over 1,600 traces across seven frameworks. Step repetition came out as the single most frequent mode, at 15.7%.
So those six lines are aimed at the most common failure in the literature. Nothing else in this file returns as much for as little.
This is the piece that turns a probabilistic step into a checked one. It is a plain function sitting between the model’s proposed action and the side effect actually firing.
Read it as ordinary business logic, because that is all it is. No model is involved. It runs without an API key. You can unit-test it.
def validate_escalation(zone_id, severity, reason):
"""Deterministic gate. No model involved, and unit-testable."""
state = get_zone_state(zone_id)
advisories = recent_advisories(zone_id, minutes=60)
if state["riders_on_shift"] is None:
return False, "zone is closed - there is nothing to escalate"
if advisories:
return False, f"advisory {advisories[0]['id']} already explains this"
if state["orders_in_flight"] < 5:
return False, "below the volume threshold for a page"
if severity == "high" and state["utilisation"] < 0.9:
return False, "severity high requires utilisation >= 0.9"
return True, "ok"
def run_tool(name, args):
if name == "escalate":
ok, why = validate_escalation(**args)
if not ok:
return {"content": f"escalation rejected: {why}", "is_error": True}
try:
out = TOOL_FNS[name](**args)
return {"content": out if isinstance(out, str) else json.dumps(out)}
except Exception as exc:
return {"content": f"error: {type(exc).__name__}: {exc}", "is_error": True}The best public evidence for this pattern is not an agent paper. Airbnb migrated nearly 3,500 Enzyme test files to React Testing Library with an LLM. In the first four hours, 75% succeeded. Four days of prompt-and-script refinement took that to 97%. The last 3% were finished by hand in another week. Six weeks in total, against an estimate of a year and a half by hand.
The loop itself was cheap. What made it converge was that every attempt was checked by a deterministic pass/fail the model could not talk its way past.
Here is the comparison, step by step rather than file by file. Pick a stage of the build, then switch the implementation underneath it.
The snippets are the shape each vendor documents. The two notes beneath each one are what matters. Read the second note first — what the framework is doing instead of you. That is the one that costs money eighteen months later.
Pick a step of the build, then switch the implementation underneath it. Read the two notes below each snippet rather than the snippet itself — what a framework does for you is easy to see, and what it does instead of you is the part that costs money later.
The one tool with a side effect: escalate.
TOOLS = [{
"name": "escalate",
"description": (
"Page the on-call engineer. Use ONLY when the zone is degraded "
"and no advisory already explains the degradation."
),
"input_schema": {
"type": "object",
"properties": {
"zone_id": {"type": "string"},
"severity": {"type": "string", "enum": ["low", "medium", "high"]},
"reason": {"type": "string", "description": "One line, for the pager"},
},
"required": ["zone_id", "severity", "reason"],
"additionalProperties": False,
},
"strict": True,
}]Nothing at all, and that is the point. The bytes in this dict are the bytes the model sees, so the enum, the strict flag and the “use ONLY when” sentence are each under your direct control and visible in a diff.
Nothing — including the work. There is no validation of your own schema, no Python signature to typecheck the handler against, and you write the name-to-function dispatch table by hand.
Step 01 verdict · Nobody wins on lines. The question is whether you want the schema the model sees to be a literal you can read, or a derived artefact you have to go and print.
No framework · Declare the tool · 18 lines shown
Read across the five steps and a pattern falls out. At steps one and three the three implementations are nearly equivalent, so preferring one is mostly taste. At step two the frameworks take the loop from you and hand back a weaker vocabulary of terminal states. At steps four and five they offer something you genuinely cannot get for free: a pause and a resume that survive a process ending.
That is the whole shape of the decision. It is worth being able to draw it from memory.
LangGraph re-executes a node from the top on resume, not from the line after interrupt(). The documentation states it plainly: “the runtime restarts the entire node from the beginning — it does not resume from the exact line whereinterrupt() was called”. And so “any code that ran before the interrupt() will execute again”.
Put the validation and the interrupt in the same node and that sentence stops being trivia. Here is the sequence. The human takes twenty minutes to answer. The replay re-reads a world that has moved on. The gate returns false this time, and the function returns before execution ever reaches the interrupt.
The approval is discarded with no exception, no warning and no page. So splitting the node is not style. It is the difference between a working gate and one that loses approvals silently.
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
from typing_extensions import TypedDict
class S(TypedDict):
zone_id: str
assessment: str
gate_ok: bool
gate_reason: str
escalated: bool
def assess(state: S):
return {"assessment": call_model(state["zone_id"])}
def gate(state: S):
"""Validation only. No interrupt here, and no side effect."""
ok, why = validate_escalation(state["zone_id"], "high", state["assessment"])
return {"gate_ok": ok, "gate_reason": why}
def approve(state: S):
if not state["gate_ok"]:
return {"escalated": False}
# One state read above the interrupt and nothing else, because this node
# re-runs FROM THE TOP on resume. Re-validating here would silently
# discard an approval whenever the world changed while we waited.
approved = interrupt({"zone": state["zone_id"],
"assessment": state["assessment"]})
return {"escalated": bool(approved)}
def act(state: S):
if not state["escalated"]:
return {}
# Reserve BEFORE the side effect, never after. A ledger written afterwards
# means a crash in between re-pages on replay; a ledger written first means
# the worst case is a page that has to be retried by a human.
if not ledger.reserve(state["zone_id"], status="in_flight"):
return {} # already reserved - this is a replay
pager.page(state["zone_id"], "high", state["assessment"])
ledger.mark_done(state["zone_id"])
return {}
b = StateGraph(S)
for name, fn in [("assess", assess), ("gate", gate),
("approve", approve), ("act", act)]:
b.add_node(name, fn)
b.add_edge(START, "assess")
b.add_edge("assess", "gate")
b.add_edge("gate", "approve")
b.add_edge("approve", "act")
b.add_edge("act", END)
with PostgresSaver.from_conn_string(DB_URL) as saver:
saver.setup() # creates the checkpoint tables; idempotent
graph = b.compile(checkpointer=saver)
cfg = {"configurable": {"thread_id": alert_id}}
graph.invoke({"zone_id": zone}, cfg) # runs, then pauses in approve
# ... twenty minutes and one deploy later, in a different process ...
graph.invoke(Command(resume=True), cfg)The component below runs that same twenty-minute approval under both layouts. An unrelated advisory opens for the zone nine minutes in. Same human, same approval, same gap — only the node boundaries differ. Watch what the one-node version does with the answer.
Identical run, identical human, identical twenty-minute gap — and an unrelated advisory opens for the zone at t+9m in both. Step through each layout and watch the state panel.
validate_escalation() runs: two network reads for zone state and active advisories. No advisory, utilisation 0.94, eleven orders in flight. ok = True, held in a local variable.
My own reading, stated as opinion rather than as documentation: a checkpointer is not durable execution. It restores state at node boundaries, and it is genuinely valuable for that. But it gives you no retries and no exactly-once side effects. LangGraph’s own guidance that work before an interrupt() must be idempotent is a polite way of saying at-least-once. So if you adopt LangGraph for the durable pause, you have bought the pause and nothing more. The ledger is still yours to write, and the act node above is where it goes.
The framework decision is not one decision. It is five, and they price differently. The verdict worth reading first is the one marked skip.
Nearly all guidance on this topic is written for one company size and then read by everyone. Pick yours — the list re-sorts, and what you should deliberately not build drops to the bottom.
A plain function between the model’s proposed action and the thing that pages, pays or deletes.
At this stage · Every write path. This is the control that turns an agent from a demo into something you can put on a rota, and it is usually a bad week that makes the case if you have not.
Build the forty-line version and run it against real traffic before adopting anything that wraps it.
At this stage · Still worth it for each genuinely new agent shape. Not for the fifth variant of one you already operate — at that point you are rehearsing, not learning.
Standardising on CrewAI, LangGraph or similar rather than a house loop per service.
At this stage · By now the same three concerns — state, ordering, resumption — have been solved differently in three services. Pick one and standardise before the fourth.
Reserve a row keyed on the alert or order id, checkpoint, then execute — never write the ledger after the effect.
At this stage · The moment runs are resumable, they replay. A pager that fires twice teaches people to ignore the pager, which is a more expensive failure than the duplicate itself.
An approval that survives a deploy, so the on-call can answer twenty minutes later from a different process.
At this stage · A ticket row and a resume endpoint. You do not need a checkpointer yet; you need a status column, an idempotent handler, and a test that resumes twice.
Nothing is optional at this stage. That is itself the finding — the cost of the control set is part of the cost of operating here.
The three implementations differ mainly on one axis: which parts of the agent you get to version independently of the others. Nubank published the most detailed public answer to that question. They also published the numbers that do not flatter them.
Nubank serve over 100 million customers, and they stopped treating a ReACT agent as one artefact. Instructions, Routines, Macros, tool specifications and working memory are each defined and independently versioned. Instructions carry role and compliance guardrails. Routines are standard operating procedures rewritten as ordered steps. Macros are response templates. Working memory is a scratchpad tracking what has been gathered so far. The engineering blog puts the principle in one line — “we treat prompts like code, segmenting them into modules… that evolve independently”. The Card Delivery agent reported a 37-percentage-point improvement in AI transactional NPS and 29 points of self-service.
Two things to carry from this. First, the axis those five components sit on is exactly the axis the three implementations in this lesson differ on. The real framework question is not which API you like. It is which parts of your agent you can change without changing the rest. Second, the honesty. Their starter LLM-judge prompt scored Cohen’s κ = 0.00 between two models, one of which was assigning a single class to everything; after GEPA optimisation the same pair reached 0.745. And Table 3 publishes the result most vendors would omit: across all five production deployments the AI still trails expert human agents on tNPS, by 1.1 to 23.6 percentage points. A paper that reports its own ceiling is a paper you can plan against.
For this agent it is one requirement: a human approval that survives a deploy. That single requirement points at LangGraph. Remove it and the eighty-line version wins on every axis you care about at 3am. “We used a framework” is not an answer. “We needed durable interrupts” is.
None of the frameworks changes where the deterministic check goes. It is ordinary Python, it is doing the real work, and it is the thing you would keep if you migrated between all three tomorrow.
Not from the line after interrupt(). Anything above it executes again. So validation and the pause belong in separate nodes, and any side effect belongs behind a ledger you reserve before you act, never after.
CrewAI buys a readable role metaphor and pays in prompt tokens and blurred failure attribution. LangGraph buys a durable pause and typed state, and pays in a runtime whose replay semantics you must know. Both are fair trades once you can state them in that form.
Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.
The MAST taxonomy: 14 failure modes from 150 hand-annotated traces at Cohen’s κ = 0.88, scaled to 1,600+ traces across seven frameworks. Step repetition is the single most frequent mode at 15.7%, which is what the six-line seen set in the loop is defending against.
The architectural answer to this lesson’s question. Instructions, Routines, Macros, tool specifications and working memory are each independently versioned. Card Delivery: +37pp AI transactional NPS, +29pp self-service. A starter LLM-judge prompt scored κ = 0.00; after GEPA optimisation, 0.745 / 0.895 / 0.950. Table 3 publishes the negative result — AI trails expert humans on tNPS in all five deployments, by −1.1pp to −23.6pp.
The definition this lesson builds on: workflows orchestrate models through code paths you wrote in advance, agents let the model direct its own process. Also the advice most often skipped — start with the API directly, because frameworks “often create extra layers of abstraction that can obscure the underlying prompts and responses, making them harder to debug”.
Why the tool descriptions in this lesson read the way they do — describe the tool as you would to a new hire, return high-signal fields rather than raw records, and make error messages “specific and actionable” rather than opaque codes.
The strongest published evidence for the validator-gate pattern. Nearly 3.5K Enzyme test files: 75% migrated in four hours, 97% after four days of sample-tune-sweep, the last 3% by hand in another week — six weeks against an estimate of 1.5 years. The loop was cheap; the deterministic pass/fail check on every attempt is what made it converge.
The engineering-blog companion to the paper, by Aman Gupta and Daniel Braithwaite. The line that matters for framework choice: “We treat prompts like code, segmenting them into modules (e.g., Tone, Tooling, Safety) that evolve independently.” Also the Card Delivery move from an LLM-orchestrated chain to a single composite deterministic tool.
Worth reading once. The prebuilt router documents itself as: “if the last AIMessage contains tool calls, route to the tool execution node; otherwise, end the workflow.” That is presence-of-tool-call routing, not stop_reason routing — exactly the shortcut the hand-written loop is told to avoid.
The three details the no-framework loop gets right. A tool result is returned by “sending a new message with the role of user”; its content is “the result of the tool, as a string… or a list of nested content blocks”, never a bare object; and the response carrying tool calls has stop_reason tool_use.
strict: true constrains sampling to schema-valid outputs, so the tool input always matches the schema. Note what it does not do: it guarantees shape, never judgement, which is why the validator gate still exists.
@start and @listen over a typed Flow[StateModel], plus @persist for state across restarts (SQLite by default, resumed with kickoff(inputs={"id": uuid})) and @human_feedback for a pause. Read the emit parameter closely: it routes the human’s free-text reply by asking an LLM to classify it.
Where the iteration cap goes when you stop writing the for-loop. max_iter defaults to 20 and is documented as the “maximum iterations before the agent must provide its best answer” — so exhaustion arrives as an answer, not as an exhaustion.
The trap, in the vendor’s own words: on resume “the runtime restarts the entire node from the beginning — it does not resume from the exact line where interrupt() was called”, so “any code that ran before the interrupt() will execute again” and side effects before it should be idempotent.
PostgresSaver.from_conn_string(...) followed by .setup(), which creates the checkpoint tables and must be called by you the first time. Checkpoints give thread-scoped state, human-in-the-loop and time travel — not retries and not exactly-once side effects.