Agents: loops, planning, memory, and when not to use one
A model in a loop with tools and a stop condition. The loop is easy; the stop condition, the budget and knowing when a workflow would do are the engineering
An agent loop has no step limit. Its first request is 2,000 input tokens, and each step adds about 1,000 tokens of tool calls and results to the history. On an unanswerable question it runs 40 steps. How does the input cost of step 40 compare with step 1?
The previous chapter’s loop already is an agent in miniature: the model chose customer_orders, read the result, chose lookup_order, and stopped. Nothing in your code said which tool came second. That is the whole definition. An agent is a model in a loop, with tools to act through, that decides its own next step, plus a stop condition that ends the loop. The model part you rent. The loop, the tools, the budgets and the stop conditions you write, and they decide whether the thing is useful, affordable and safe.
This chapter covers the loop and its parts: how agents reason and plan, where they keep state, how you bound them, and how you see what they did. It starts and ends with the question that matters more than any of those: whether you need an agent at all.
Workflows before agents
Anthropic’s “Building effective agents” (December 2024) draws the distinction this course uses. A workflow is a system where models and tools run along a path your code defines. An agent is a system where the model directs its own process and tool use. Its central advice is to find the simplest solution that works and add complexity only when it is needed, and for many applications a single well-built model call, with retrieval and good examples, is enough.
The post names five workflow patterns, and each replaces an agent in a common case:
| Pattern | Shape | Use it when |
|---|---|---|
| Prompt chaining | call A’s output feeds call B, with code checks between | the task splits into fixed steps (draft, then translate, then check) |
| Routing | one call classifies; code sends the input to a specialised path | inputs fall into categories that need different handling |
| Parallelisation | several calls on parts of the input, or the same call several times, combined by code | the parts are independent, or you want a vote |
| Orchestrator-workers | a model breaks the task into subtasks, workers do them, code merges | subtasks cannot be known in advance but each is self-contained |
| Evaluator-optimiser | one call produces, another critiques, loop until it passes | there is a clear quality bar a model can check |
A workflow has properties an agent lacks. Its cost per input is bounded by the number of calls you wrote. Its latency is predictable. You can test each step on its own, and when something goes wrong you know which step it was. An agent trades all of that for flexibility: it can take a path nobody wrote down.
Before reaching for one, ask four questions. Is the task multi-step and hard to specify in advance? Is the result valuable enough to pay for more calls and more latency? Can the model actually do this kind of task? And can its mistakes be caught and undone, by tests, review or rollback? A “no” to any of them is a reason to stay with a workflow. A shop support assistant that answers order questions passes all four. A nightly report that runs three known queries and summarises them fails the first, and as an agent it would cost more, run slower and occasionally decide to run a fourth query.
The ReAct loop
ReAct (Yao et al., 2022) named the pattern that every tool-using agent now follows: interleave reasoning (a thought about what to do next), acting (a tool call) and observing (the result), and repeat. The paper’s finding was that the two halves need each other. Reasoning without acting hallucinates facts it could have looked up. Acting without reasoning loses track of what it has learnt and repeats itself.
In the 2022 paper the thought, action and observation were lines of text in one prompt, parsed with regular expressions. With native tool use the same loop has a cleaner shape. The thought is the model’s thinking block and any text before the call; the action is a tool_use block; the observation is a tool_result. On Claude Opus 5.5 thinking is always on, so each turn reasons before it acts. Your loop’s job is to keep those pieces in order: append each assistant response whole, thinking blocks included, and never edit earlier turns, because current models invalidate thinking from an edited history.
Planning styles
How much an agent plans before it acts is a design choice with costs on both sides.
Interleaved planning is the default ReAct behaviour: decide one step, see the result, decide the next. It adapts well to surprises and is cheap per step. It can wander, because no step looks further ahead than the next.
Plan then execute asks for a full plan first, then runs it. The plan is inspectable (you can show it to a user, or check it in code before anything runs) and execution can be cheaper because a smaller model or plain code can carry it out. It breaks when an early result invalidates the plan, so practical versions re-plan: execute, and when a step fails or returns something unexpected, revise the remaining plan.
Reflection adds a step where the model reviews its own progress: what have I learnt, is the approach working, should I stop? Reflexion (Shinn et al., 2023) showed that agents improve across attempts when they write such critiques into memory. Inside a single run, a short reflection prompt after a failure or every few steps is the cheapest defence against wandering. The lab adds one in four lines and you can measure what it costs and saves.
Chip Huyen’s treatment of agents in AI Engineering sorts planning failures into useful categories: invalid tools, valid tools with wrong parameters, goals not met, and plans that ignore constraints such as a budget. Each is something you can detect in a log, which is where the observability section below comes in.
Memory: conversation, scratchpad, external
An agent remembers in three places, and they have different costs.
Conversation memory is the message history: every call, every result, every thought. It is free to write and expensive to keep, because the whole of it is resent on every step. Claude Opus 5.5 has a 1M-token context window, so you will rarely hit the limit on a short task; you will hit the bill long before. Shape tool results small, and for long runs use server-side compaction (a beta that summarises older context when the conversation passes a threshold) or context editing (which clears old tool results), both covered in later chapters.
Scratchpad memory is state the agent writes for itself within a run: a plan, a list of what it has checked, intermediate results. It can live in the conversation (the model writes notes as text) or in a tool (write_note, read_notes). A scratchpad tool keeps notes out of the growing history and lets your code inspect them.
External memory persists across runs: a database of facts about the user, past resolutions, a vector store. It is how an agent “remembers” yesterday. It is also a new attack surface, because anything written there in one run is read as trusted context in the next. Retrieval, in module three, is the disciplined version of this.
Budgets: steps, tokens, money, time
An agent without a budget is an unbounded loop whose iterations cost money. Four budgets, all checked in your code before every model call:
| Budget | What it bounds | Typical setting for a support agent |
|---|---|---|
| Steps | model turns or tool calls | 8 to 15 |
| Tokens | total input plus output across the run | a few hundred thousand |
| Money | cost computed from usage at known prices |
a few cents to $0.50 per run |
| Time | wall clock from start | 30 to 120 s, which is what a user will wait |
They overlap, and you want all four, because each catches a different failure. A step budget catches loops of cheap calls. A token budget catches a few calls that each return enormous results. A money budget is the one finance cares about and the only one that survives a price change correctly, so compute it from response.usage at the model’s per-token prices, not from step counts. A time budget catches a slow tool that never errors.
The arithmetic in the Predict question is why budgets matter more for agents than for single calls. With history resent each step, input tokens grow with the square of the step count. A run of 10 steps with 2,000 tokens to start and 1,000 per step sends about 65,000 input tokens: $0.26 on Claude Opus 5.5 at $4 per million, plus output. At 30 steps it is about 495,000 input tokens, $1.98. At 1,000 runs a day, the difference between a budget of 10 and no budget on the runs that go wrong is thousands of dollars a month. Prompt caching makes the repeated prefix much cheaper, and the caching chapter measures it; budgets come first.
The API offers help at two levels. A task budget (a beta on current models, set as task_budget inside output_config, minimum 20,000 tokens) tells the model how many tokens it has for an agentic task so it can pace itself and finish gracefully. It is advisory: the model sees a countdown, and nothing stops it if it ignores it. Managed Agents sessions can carry hard, dollar-denominated budgets enforced by the platform. Neither replaces the check in your own loop, which is the only one you control completely.
Stop conditions and the infinite loop
A loop needs a reason to stop. The natural one is the model ending its turn without a tool call (stop_reason: "end_turn"). Everything else is a safety net, and you need several:
- Budget exhausted. Steps, tokens, money or time. Do not throw. Make one final call with
tool_choiceset tononeand an instruction to answer from what it has and say what it could not find. A partial answer is worth more than an exception. - Repetition. The same tool with the same arguments twice in a row means the agent is stuck. Detect it in code (hash the name and input) and either stop or inject a note: “You called this already; the result was the same.”
- No progress. Several steps of empty results or errors. A reflection prompt here often gets the model to conclude the task is impossible, which is the right answer.
- Truncation and refusal.
max_tokensmid-turn means the tool call may be incomplete;refusalmeans the model declined. Neither should send the loop round again unchanged.
The classic infinite loop comes from an unanswerable task meeting a system prompt that forbids giving up: “Keep trying until you find the answer.” The model obliges. It searches with different words, iterates through ids, re-reads results it already has. Each step is plausible on its own, and the loop has no way to notice that the sum is futile. The lab builds exactly this and lets a cost cap stop it. The fix is partly prompt (“if the tools cannot answer, say so and stop” is a legitimate instruction) and mostly code: the budgets and detectors above.
Observability of an agent run
You cannot debug an agent from its final answer. You need the trajectory: what it did, in what order, at what cost. Log one structured record per step:
- a run id, the step number, and the timestamp
- the tool calls proposed (name and input) and whether each was executed, refused or errored
- the size of each result in tokens or bytes, not only the content
usage.input_tokensandusage.output_tokens, the running cost, and the latency of the model call and of each tool- the
stop_reason
From those records you can answer the questions that come up in production. Which runs cost the most and why? Which tool fails most often? How many steps does a typical successful run take, and what does the tail look like? Where do runs that hit the budget get stuck? A JSON line per step in a file is enough for the lab. In production the same fields become spans in a trace, one span per model call and per tool call under a parent span for the run; the observability chapters in module four connect them to OpenTelemetry. Log the trajectory from day one, because the first time you need it is the first time an agent does something surprising, and you cannot reconstruct it afterwards.
When not to use an agent
Use a workflow when the steps are known. Use a single call when one call will do. Use plain code when no judgement is needed. Use an agent when the path depends on what the tools return, the task is worth several calls, the model is capable of it, and its mistakes can be caught before they cost more than the task is worth. Then bound it in code, log every step, and keep the actions it can take as narrow as the task allows. The project at the end of this module builds exactly that: a support agent over the shop with three read-only tools, a budget, and a cost per conversation you can state.
You will write a 60-line agent loop over the three shop tools with a step budget, a cost cap and a log; take the budget away and watch an unanswerable task run until the cap stops it; then put the budget back with a reflection step and compare. Work in labs/ai/tools/, next to shop_tools.py.
Cost: claude-opus-5-5 at $4 per million input tokens and $20 per million output. A normal two-tool question is about $0.04. The no-budget run in step 3 is capped at $0.50 by design. The whole lab is $1.00 to $1.50.
1. The loop. Create agent.py:
import json, os, sys, time
import anthropic
from shop_tools import TOOLS, FUNCS
MODEL = "claude-opus-5-5"
PRICE_IN, PRICE_OUT = 4.00 / 1e6, 20.00 / 1e6 # USD per token for claude-opus-5-5
MAX_STEPS = int(os.environ.get("MAX_STEPS", "8")) # tool steps; 0 means no step budget
MAX_USD = float(os.environ.get("MAX_USD", "0.50")) # cost cap: always on
REFLECT = os.environ.get("REFLECT") == "1"
SYSTEM = os.environ.get("SYSTEM", "You answer questions about the shop using the tools. "
"If the tools cannot answer the question, say so and stop.")
client = anthropic.Anthropic()
log = open("agent_log.jsonl", "a")
def run_tool(block):
try:
out = json.dumps(FUNCS[block.name](**block.input), default=str)
return {"type": "tool_result", "tool_use_id": block.id, "content": out}
except Exception as e:
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": f"{type(e).__name__}: {e}"}
def agent(task):
messages, spent, step, run, t0 = [{"role": "user", "content": task}], 0.0, 0, f"{time.time():.0f}", time.time()
while True:
if spent >= MAX_USD:
return f"STOPPED by cost cap: ${spent:.2f} spent in {step} steps, no answer."
final = bool(MAX_STEPS) and step >= MAX_STEPS
r = client.beta.messages.create(model=MODEL, max_tokens=4000, system=SYSTEM, tools=TOOLS, messages=messages,
output_config={"effort": "low"},
betas=["server-side-fallback-2026-07-01"], fallbacks="default", # the API chapter's rule
tool_choice={"type": "none"} if final else {"type": "auto"})
spent += r.usage.input_tokens * PRICE_IN + r.usage.output_tokens * PRICE_OUT
messages.append({"role": "assistant", "content": r.content})
calls = [b for b in r.content if b.type == "tool_use"]
log.write(json.dumps({"run": run, "step": step, "stop": r.stop_reason, "in": r.usage.input_tokens,
"out": r.usage.output_tokens, "usd": round(spent, 4), "secs": round(time.time() - t0, 1),
"calls": [[c.name, c.input] for c in calls]}) + "\n")
log.flush()
print(f"step {step:2d} in={r.usage.input_tokens:6d} ${spent:.3f} {r.stop_reason:8s}",
" ".join(f"{c.name}({json.dumps(c.input)})" for c in calls))
if r.stop_reason != "tool_use":
return next((b.text for b in r.content if b.type == "text"), f"(stop_reason {r.stop_reason})")
step += 1
content = [run_tool(c) for c in calls]
notes = []
if MAX_STEPS:
notes.append(f"{max(MAX_STEPS - step, 0)} tool steps left.")
if step >= MAX_STEPS:
notes.append("Step budget used up: answer now from what you have and say what you could not find.")
if REFLECT and step % 3 == 0:
notes.append("Before your next call, in two sentences: what have you learnt so far, and can these "
"tools answer the question at all? If they cannot, stop and say so.")
if notes:
content.append({"type": "text", "text": " ".join(notes)}) # text goes after the tool results
messages.append({"role": "user", "content": content})
if __name__ == "__main__":
print("\n" + agent(sys.argv[1]))uv run agent.py "What did customer 42 buy most recently, and is it in stock?"step 0 ... tool_use customer_orders({"customer_id": 42}), step 1 ... tool_use lookup_order({"order_id": ...}), step 2 ... end_turn, then the answer. The running cost is about $0.04. The in= column grows each step as the history grows. agent_log.jsonl now has three records with tokens, cost, seconds and calls for each step: this is the trajectory, and every later step of the lab reads it.2. An unanswerable task, with the budget on.
uv run agent.py "Find the customer who phoned on Tuesday to say their kettle arrived broken, and give me their phone number."3. Remove the budget and the permission to stop. Same task, no step budget, a system prompt that forbids giving up, and the cost cap as the only safety net:
MAX_STEPS=0 MAX_USD=0.50 SYSTEM="You are a persistent shop assistant. Never give up and never ask the user for more information. Keep using the tools until you find the answer." uv run agent.py "Find the customer who phoned on Tuesday to say their kettle arrived broken, and give me their phone number."customer_orders({"customer_id": 1}), then 2, then 3…), and looks up their orders for a kettle. Each step is reasonable on its own. Watch the in= column climb and the cost per step rise with it. Typically the run ends with STOPPED by cost cap: $0.50 spent in 15 to 30 steps, no answer. Some runs end earlier with the model admitting defeat despite the prompt; if yours does, re-run with MAX_USD=0.25 and a stronger prompt to see the cap fire. Either way, compute from the log what this costs at a thousand such conversations a day.4. Read the trajectory. Summarise the runs from the log:
uv run python - <<'PY'
import json, collections
runs = collections.defaultdict(list)
for line in open("agent_log.jsonl"):
r = json.loads(line); runs[r["run"]].append(r)
for run, steps in runs.items():
calls = [json.dumps(c, sort_keys=True) for s in steps for c in s["calls"]]
repeats = len(calls) - len(set(calls))
print(f"run {run}: {len(steps)} steps ${steps[-1]['usd']:.3f} {steps[-1]['secs']}s "
f"input tokens {sum(s['in'] for s in steps)} repeated calls {repeats} last stop {steps[-1]['stop']}")
PY5. Budget back, plus reflection.
MAX_STEPS=8 REFLECT=1 SYSTEM="You are a persistent shop assistant. Never give up and never ask the user for more information. Keep using the tools until you find the answer." uv run agent.py "Find the customer who phoned on Tuesday to say their kettle arrived broken, and give me their phone number."MAX_STEPS=8 but delete the tool_choice={"type": "none"} if final else ... argument, so the final call still allows tools, and re-run step 5 without REFLECT. The model ignores the ‘answer now’ note often enough that the loop calls a ninth, tenth and eleventh tool, because nothing in code stops it: the step budget only worked because the last call made tool use impossible. A budget the model is asked to respect is a suggestion. A budget your code enforces is a budget.Template
# Decision memo: <task>, workflow, single call or agent?
Owner: <role>. Decider: <role>. Date: <date>. Decision needed by: <date>.
## 1. The task and the decision
<One paragraph: what the task is, who uses it, what you need decided.>
Out of scope: <what this memo does not decide>
## 2. The options, measured
| Option | Cost per run | Latency | Success | Source of each figure |
|---|---|---|---|---|
| Fixed workflow (code fixes the steps) | | | | |
| Single model call | | | | |
| Agent loop (model chooses the steps) | | | | |
## 3. Recommendation
<The option, and the reason in two or three sentences.>
## 4. Limits, if an agent is chosen
| Limit | Value | What happens when it is hit |
|---|---|---|
| Steps | | |
| Money per run | | |
| Wall-clock time | | |
Tools allowed: <list, read-only or not>. Never allowed: <list>. Rollback: <how a bad run is undone>.
## 5. How this could be wrong
<One way, and the signal in the logs that would show it.>
Revisit when: <trigger or date> WORKED EXAMPLE
Written by the engineer who built the support agent; approved by the head of engineering.
Task: answer shop order questions such as ‘What did customer 42 buy most recently, and is it in stock?’ Decision needed by Friday: which shape ships.
| Option | Cost per run | Latency | Success | Source |
|---|---|---|---|---|
| Fixed workflow | not measured | not measured | cannot handle questions outside the two fixed steps (assumed) | no lab run |
| Single call | not measured | not measured | fails, as it holds no order data (assumed) | no lab run |
| Agent loop | about $0.04 | not measured; the log’s secs column will show it | 1 question tried, answered in 3 steps (lab step 1) | lab output |
Recommendation: the agent loop. The chapter’s four questions all pass: the path depends on what the tools return, the answer is worth a few calls, the model can do it, and read-only tools mean mistakes can be caught. A fixed workflow would be cheaper, but assumed to break on questions it was not written for.
Limits: 8 steps, then one final call with tools disabled; $0.50 per run, the lab’s cap; 60 seconds (assumed). On the unanswerable phone-number task, the unbudgeted run hit the cap after 15 to 30 steps with no answer, while the budgeted run with reflection cost between $0.05 and $0.25 and explained itself. Tools: the three read-only shop tools. Never: writes. Rollback: none needed, as nothing is changed.
Could be wrong if most real questions are two fixed steps; the logs would show the same two tools in the same order every time, and a workflow would then replace the agent.
Now you
You work for Lumora Mobile, the mobile network operator with 31 million subscribers. Its customer-care assistant already answers on the Claude API with three tools: lookup_data_usage, check_data_session and refund_data_bundle. The customer-care lead proposes a new job: when a subscriber writes in saying their data bundle ran out too fast or will not connect, the assistant should work out why (bundle used up, no data session, or a fault on the network side) and, where the evidence supports it, refund the bundle without a human. Some cases are one lookup; others need several. The refund is the only tool that changes anything. The head of customer-care operations must decide whether this should be a fixed workflow, a single call or an agent loop. Reuse the lab’s figures for cost per run, the $0.50 cap and the step counts, and label anything else as an assumption. A refund cannot be taken back by the model, so say what limits apply to it. Write the memo for the head of customer-care operations, who decides, and the customer-care lead, who lives with the result.
Self-check
The operations team wants a weekly report posted to Slack every Monday: last week's orders, revenue and refund rate by country from the shop database, with a short paragraph noting anything unusual compared with the previous four weeks. A colleague has prototyped it as an agent with a run_sql tool and the instruction 'produce the weekly ops report'. What do you ship?
- POST Building effective agents Erik Schluntz and Barry Zhang (Anthropic), 2024
The workflow-versus-agent distinction, the five workflow patterns, and the case for the simplest thing that works. Read all of it; the appendix on tool design pairs with the previous chapter. The page notes that some tooling it mentions has changed since 2024; the patterns have not.
- BOOK AI Engineering: Building Applications with Foundation Models Chip Huyen, 2025
The best book-length treatment of the field this course covers. Its agents section covers tools, planning, reflection and a taxonomy of agent failures that maps onto the logs you wrote in the lab. Read: chapter 6, the second half on agents; the first half on RAG belongs with module three.
- POST Agents Chip Huyen, 2025
The agents section of the book, adapted as a free post. Read it if you do not have the book; the sections on planning and on failure modes and evaluation are the most useful.
- PAPER ReAct: Synergizing Reasoning and Acting in Language Models Yao et al., 2022
The loop every agent in this chapter runs. The trajectories show both failure modes the paper set out to fix: reasoning that hallucinates without actions, and actions that repeat without reasoning. Read: sections 1 to 3 and the example trajectories.
- PAPER Reflexion: Language Agents with Verbal Reinforcement Learning Shinn et al., 2023
Self-critique written to memory as a way to improve across attempts. The reflection step in the lab is the in-run version of this idea; the paper shows when it helps and when it does not. Read: sections 1 to 3; skim the programming experiments.
- DOC Handling stop reasons
Every stop_reason your loop has to handle, including pause_turn for server tools, refusal, and context-window exhaustion. Read the quick-reference table and the tool-use section; the rest is reference.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.