Every framework in this space is wrapping about forty lines of code. Write those lines once and no framework is mysterious again. Better still, you stop being surprised by what one of them is doing on your behalf.
An agent is a model that decides which tools to call, in what order, until it decides it is done. That is the whole definition, and it is the one that has held up.
Anthropic’s framing draws the line precisely. A workflow runs models and tools through code paths you wrote in advance. An agent lets the model direct its own process. Everything expensive about agents follows from that single handover: the cost, the latency, the debugging.
The code itself is genuinely small. Thorsten Ball built a working code-editing agent in under four hundred lines, most of it boilerplate, and described the substance as “an LLM, a loop, and enough tokens”. Hugging Face’s smolagents keeps its core agent logic inside about a thousand lines.
So the shape is small on purpose. What is not small is everything you add around it once real users arrive, and that is most of this lesson.
Read the cost lane left to right — three of the four are lines of code, and only the fourth is real work. Select a guard for the detail.
Four guards. Three are cheap enough that skipping them is never defensible; the fourth is a genuine waste of a seed team’s only scarce resource.
Before any code, the architecture: five components and a cycle. The second box is the one that surprises people. The agent has no memory at all. The entire state of the run is an array you rebuild and resend on every single iteration.
Sit with that for a moment, because two things later in this lesson fall straight out of it. One is the cost curve. The other is why a chatty tool result is a state problem rather than an untidy one.
Select any box, or any guard, for what it does and why it is placed there.
An agent has no memory. The complete state of the run is this array, which you rebuild and resend on every single iteration. That is why context is a budget rather than a container — and why a 40,000-token tool result is not a formatting problem, it is a state-management problem that will be paid for on every subsequent turn.
Here it is, with the guards already in place. A version without them is a version you rewrite in its first week of traffic. Two details carry most of the real bugs, and both are marked in the comments.
import json
import anthropic
client = anthropic.Anthropic()
MAX_TURNS = 12
def run(user_message, tools, handlers):
messages = [{"role": "user", "content": user_message}]
seen = set()
for turn in range(MAX_TURNS): # guard: hard iteration cap
response = client.messages.create(
model="claude-opus-5",
max_tokens=2048,
tools=tools,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
# Branch on stop_reason, NOT on "is there a tool_use block".
# A reply truncated at max_tokens has no tool_use block either, and
# code that tests for absence reads that truncation as a finished
# answer. This is the single most expensive bug in the pattern.
if response.stop_reason == "max_tokens":
raise RuntimeError("truncated: raise max_tokens or shrink context")
if response.stop_reason != "tool_use":
return response
results = []
for block in response.content:
if block.type != "tool_use":
continue
key = (block.name, json.dumps(block.input, sort_keys=True))
if key in seen: # guard: repeated identical call
out = "Already called with these arguments. Use the earlier result."
else:
seen.add(key)
out = execute(block, handlers)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": out, # a STRING, never a dict
"is_error": out.startswith("ERROR"),
})
# Results go back on a USER message. This trips up almost everyone.
messages.append({"role": "user", "content": results})
raise RuntimeError(f"no answer in {MAX_TURNS} turns")
def execute(block, handlers):
# Errors are returned to the model, not raised. An agent told that a
# query failed can correct itself; an agent whose process died cannot.
try:
return json.dumps(handlers[block.name](**block.input))
except Exception as exc:
return f"ERROR: {type(exc).__name__}: {exc}"That is the entire mechanism. A framework adds retries, tracing, streaming and a graph abstraction on top. All of that is genuinely useful, and none of it changes the shape.
Which is the payoff for writing it yourself. If you cannot draw this on a whiteboard, you cannot debug what a framework is doing at two in the morning.
The other half of the work is the tool definition. It carries more of the quality burden than the prompt does — provided you know which of your constraints are real.
Set strict and the sampler is constrained to the schema. An invalid enum value or an unexpected key stops being unlikely and becomes structurally impossible. Numeric and string-length constraints are a different matter. They are documented as unsupported, so a schema that declares them reads as safer than it is. Anything you need bounded, you bound yourself, in the handler.
import re
TOOLS = [{
"name": "issue_refund",
"description": (
"Issue a refund against a delivered order. Amounts above the market's "
"auto-approval ceiling are held for human approval and return "
"status=blocked. Call get_refund_policy first to read the ceiling."
),
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"amount_inr": {"type": "integer"},
"reason": {"type": "string", "enum": [
"late_delivery_quality", "missing_item", "wrong_order",
]},
},
"required": ["order_id", "amount_inr", "reason"],
"additionalProperties": False,
},
# Constrains sampling to the schema: the enum, the required keys and
# additionalProperties are guaranteed. Numeric and length constraints
# (minimum, maximum, minLength, maxLength) are NOT enforced — the docs
# list them as unsupported, so anything you need bounded, you bound.
"strict": True,
}]
def validate(order_id, amount_inr, reason):
if not re.fullmatch(r"[0-9]{7}", order_id):
return f"ERROR: order_id must be 7 digits, got {order_id!r}"
if not 1 <= amount_inr <= 20_000:
return f"ERROR: amount_inr out of range: {amount_inr}"
return NoneReading a loop is not the same as watching one execute. Below is a real-shaped trajectory — the whole sequence of steps in one run. Ten turns, four tools, a refund on a late food-delivery order in Bengaluru. Watch the counters. They are the part almost nobody works out from the code alone.
Ten turns of a four-tool agent handling a ₹684 refund in Bengaluru. Step through it and watch the right-hand counters — they are the part that surprises people.
My order came 50 minutes late and the food was stone cold. Order 8842137.
The 1,240 tokens before a word of conversation are the system prompt and the JSON schemas of four tools. Tool definitions are context, and you pay for them on every turn of the run.
Two things in that run are worth carrying into an interview. The first is the cost shape. Every turn resends the whole array, so a run’s billed input grows with roughly the square of its length. Cut one tool call from a ten-turn agent and you save far more than one turn’s worth.
The second is turn eight. The model proposed an action that contradicted a rule it had read two turns earlier. No prompt would have made that reliable. A comparison against a number did. That is the case for a deterministic check — plain code, no model — made in one turn of one run.
The four guards are not a checklist to complete. Three are cheap enough that skipping them is never defensible, at any stage. The fourth is a genuine waste of a seed team’s only scarce resource.
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 hard maximum on loop turns, with the run recorded as capped rather than as a success.
At this stage · Same three lines, now with an alert when the cap trips more than rarely — a rising cap rate is the earliest signal that a tool has quietly broken.
A set of (tool, arguments) pairs; on a repeat, return an error result telling the model it already has this.
At this stage · Worth logging repeats as a metric now — a climbing repeat rate usually means a tool description has drifted out of date.
A deterministic check between the model's proposed action and the side effect actually firing.
At this stage · Now on every write path. This is usually the stage where the first expensive incident makes the case for you, and it is better to have it before that.
Persist messages[] after each turn so a failure at step 18 costs one step rather than the whole trajectory.
At this stage · A JSON blob in Postgres keyed by run id is enough. You do not need a durable-execution framework to survive a redeploy mid-run.
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.
Both of these sit outside the usual Silicon Valley case list. Both turn on the same boundary: what the model is allowed to do, versus what it is only allowed to propose.
TRIM-AI reads SMS messages sent by pregnant women to the PROMPTS helpdesk and classifies how clinically urgent each one is. The messages are code-mixed: English and Swahili inside the same text. A weighted F1 of 0.774 sounds far too low to ship. Then you notice what the model is actually for. It does not answer the mother. It orders a queue that human helpdesk agents then work through.
That is the “decides but never acts” boundary, drawn around a whole product. A person is the actuator — the thing that finally acts — so a misranking costs a delayed call rather than wrong clinical advice. At that price, 0.774 is a perfectly shippable number. Now move the same model one box to the right and let it reply directly. The identical F1 becomes indefensible. The metric did not change. The position of the human did.
Air Canada’s website chatbot told a bereaved passenger he could apply for a bereavement fare retroactively. Another page on the same website said the opposite. The airline argued that the chatbot was a separate entity, responsible for its own actions. The tribunal rejected that, found negligent misrepresentation, and awarded CAD 650.88.
The damages are trivial. The engineering lesson is not. This was not a hallucination problem in any interesting sense. It was two sources of truth on one domain, with nothing watching for them to diverge. So the fix is architectural rather than a better prompt. Generate from the same canonical policy document the web page renders from, cite it in the answer, and alarm on drift. And note where the ruling leaves you: “the bot is a separate system” is now a defence that has been tested in front of a tribunal and lost.
Whoever owns the for-loop owns retries, budgets, timeouts, logging, and the ability to stop. That is the whole reason to write it once before adopting anything that hides it.
There is no memory. You rebuild and resend everything each turn. That is why cost grows with the square of the trajectory, and why a verbose tool result is a state problem rather than a formatting one.
Not on the absence of a tool call. Truncation and completion look identical to code that tests for absence.
Keep the gap between decision and side effect real, and put a deterministic check in it. Every approval gate, spend cap and audit trail you will ever need lives in that gap.
Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.
Yao et al., ICLR 2023. Interleaving a reasoning trace with actions — the shape almost every agent loop still has, three years on.
Schick et al., 2023. The other root of the idea: a model deciding for itself when an external tool beats its own weights.
December 2024. The distinction the whole field now uses: workflows orchestrate LLMs through predefined code paths; agents let the model direct its own process and tool use. Also the origin of the five workflow patterns.
April 2025. A working code-editing agent in under 400 lines, most of it boilerplate — "an LLM, a loop, and enough tokens". The best antidote to framework mystique.
TRIage for Mothers using AI. Classifies the emergency level of inbound SMS written in code-mixed English and Swahili, weighted F1 0.774 on real-world data, in the field since June 2022. The model prioritises; the human helpdesk answers.
A barebones agent library whose core logic fits in about a thousand lines. Worth reading precisely because there is so little of it to read.
Factor 8, own your control flow, and Factor 3, own your context window, are the two that decide whether you can debug the thing at 2am.
The round trip in full: stop_reason "tool_use", a tool_use block, your execution, a tool_result block sent back on a user-role message. Also strict:true for schema conformance and disable_parallel_tool_use.
British Columbia Civil Resolution Tribunal. The airline argued its chatbot was a separate entity responsible for its own actions; the tribunal rejected that, found negligent misrepresentation, and awarded CAD 650.88.