The Agent Loop Cheatsheet
The runtime of an AI agent on one page — the loop, context, failure modes, and defenses.
An agent is a loop around a model. The model reads the context and either answers or requests a tool; your harness runs the tool, appends the result and calls the model again, until the model stops or a guard stops it.
Everything on this page concerns the loop’s three weak points. The context window is finite and degrades as it fills. Tools are the agent’s only way to act, so their design decides what it can do and how safely. And the model cannot tell when it is wrong, so stopping and verification must be engineered from outside it.
The loop
- Plan
- Model reads context, decides the next move (or that it’s done)
- Act
- Model emits a tool call; the harness runs it
- Observe
- Result appended to context; loop repeats
- Stop when
- Final answer, max steps, budget hit, or stuck-detected
- stop_reason
- loop on
tool_use, stop onend_turn(Anthropic); OpenAI’sfinish_reasonistool_calls/stop - Truncated turn
- a reply cut off by the token limit is not a final answer — detect it and continue
- Parallel tool calls
- one turn can request several tools; run them concurrently and return all results together
Context management
- What fills it
- System prompt + tools + history + RAG + output reserve
- Compaction
- Summarize old turns before overflow; keep recent in full
- Memory
- Short-term = context; long-term = write/retrieve store
- Prompt caching
- stable prefix first; cached reads cost about a tenth of normal input on Anthropic’s API
- Just-in-time retrieval
- give the agent search and read tools instead of pasting everything up front
- Truncate tool results
- cap long logs and files, and say how to fetch more — huge results crowd out the task
- Scratchpad / todo list
- the agent writes its plan and progress down and re-reads it instead of remembering
- Subagent summaries
- delegate a messy search; only the distilled answer returns to the main context
- Append-only history
- editing earlier turns invalidates the cache from that point on — append instead
Failure modes → fixes
- Infinite loop
- Step limit + stuck detection
- Hallucinated tool/args
- Strict schemas + validation
- Prompt injection
- Instruction hierarchy, sanitizing, output filter, tool gate
- Runaway cost
- Model routing, context trimming, caching
- Context rot
- Quality degrades as the window fills with stale turns — compact and prune aggressively
- Silent wrong result
- Independent verification — a checker that is not the actor (tests, a reviewer subagent)
- Premature victory
- declares done after a partial fix — require evidence such as test output
- Repeated calls
- the same tool and arguments over and over — hash recent calls and break the cycle
- Reward hacking
- edits or skips the test instead of fixing the code — protect tests, review diffs
- Swallowed errors
- a failed tool returns nothing useful — return the error text so the model can adapt
- Goal drift
- long runs wander from the request — keep the goal and acceptance criteria in the scratchpad
Tool calling
- Who runs the tool
- The harness (your code), never the model — the model only emits a structured request
- Tool schema
- Name, description, typed params (JSON Schema) — the model picks and fills from it
- Result handling
- Append the observation to context; on error, feed the error back so the model can retry
- Least privilege
- Grant only the tools/permissions a task needs — an injected instruction can only reach what you exposed
- Strict mode
strict: trueon a tool (Anthropic, OpenAI) guarantees arguments match the schema
Tool design
- Few, distinct tools
- overlapping tools confuse selection; merge near-duplicates and name each by its job
- Descriptions are prompts
- say when to use the tool, when not to, and what it returns, with an example
- Enums over free text
- constrain arguments to allowed values so invalid ones cannot be produced
- Return what is needed
- concise, structured results with IDs for follow-up calls — not raw dumps
- Idempotent writes
- tool calls get retried, so creates and charges must be safe to repeat
- Dry run first
- destructive tools offer a preview the agent must call before the real action
Patterns
- ReAct
- interleave a reasoning step with each action — the loop most frameworks run
- Plan-and-execute
- write the whole plan first, then run the steps, often with a cheaper model
- Router
- classify the request, then hand it to a specialized prompt or model
- Orchestrator-workers
- a lead agent splits the task, workers run in parallel, the lead merges results
- Evaluator-optimizer
- one model drafts, another critiques against criteria, repeat until it passes
- Workflow before agent
- if the steps are known in advance, hard-code them; use a loop only when they are not
Safety & permissions
- Sandbox execution
- run code and shell tools in a container with no secrets and limited network
- Human approval
- gate irreversible actions — payments, deletes, outgoing email — behind a confirm step
- Budget caps
- max steps, tokens, dollars and wall-clock time per run, enforced by the harness
- Secrets stay out
- inject credentials in the tool layer so the model never sees the key
- Tool output is data
- pages and files can carry instructions; they must never change what the agent may do
Evaluate & observe
- Trace every step
- log prompts, tool calls, results, tokens and latency per step so failures can be replayed
- Task success rate
- measure on a fixed suite of real tasks with checkable outcomes
- pass@k vs pass^k
- succeeds in any of k tries vs in all k — production reliability needs the second
- Cost per solved task
- total spend divided by successes; cheap runs that fail are not cheap
- Step-count spread
- a long tail of step counts reveals loops and confusion before users report them
Worked example: one bug-fix run, step by step
Task: “refund_total double-counts partial refunds; fix it.” Each row is one model call.
step model requests harness returns
1 grep "refund_total" src/ both run concurrently,
+ read tests/test_refunds.py results sent in one message
2 read src/refunds.py 2,400 lines: lines 1-200 + "use offset= for more"
3 edit src/refunds.py "applied 1 hunk"
4 bash pytest tests/test_refunds.py 1 failed; last 40 lines of output only
5 edit src/refunds.py "applied 1 hunk"
6 bash pytest tests/test_refunds.py 3 passed
7 end_turn: "Fixed: ..." harness reruns pytest itself: pass, returnFour rows from this sheet did the work: parallel calls at step 1, a truncated result at step 2, a failure fed back at step 4, and a check by the harness, not the model, at step 7.
Why the run costs more than its final context. Every call re-sends the whole history. Take a 4,000-token prefix (system prompt and tools) and 1,500 new tokens per step, over 10 steps:
no caching sum of 4,000 + 1,500 × (k − 1), k = 1..10 = 107,500 input tokens
final context 4,000 + 9 × 1,500 = 17,500 tokens
with caching new tokens at 1.25× (cache write), rest 0.1× ≈ 30,900 token-equivalentsInput grows with the square of the step count. That is why caching, compaction and short runs matter more than the size of any one prompt. The 1.25× and 0.1× are Anthropic’s multipliers for a five-minute cache.
Recipes
A minimal agent loop
def run_agent(task, max_steps=25):
messages = [{"role": "user", "content": task}]
for step in range(max_steps):
reply = model(messages, tools=TOOLS)
messages.append({"role": "assistant", "content": reply.content})
if reply.stop_reason != "tool_use":
return reply.text
results = [run_tool(call) for call in reply.tool_calls]
messages.append({"role": "user", "content": results})
raise StepLimitExceeded(task)The model only ever requests tools; the harness runs them, returns every result in one message and enforces the step limit itself.
Detect a stuck agent
import json
from collections import deque
recent = deque(maxlen=6)
def is_stuck(call):
key = (call.name, json.dumps(call.args, sort_keys=True))
recent.append(key)
return recent.count(key) >= 3Three identical calls among the last six means the loop is not learning from its results. Stop the run, or tell the model what it has already tried.
Budget a context window (worked example)
window 200,000 tokens
system + tools -12,000
memory files -3,000
output reserve -16,000
--------------------------------
history + results 169,000 available
compact at ~70% summarize once the history passes ~118,000Reserve output space first and compact well before the limit, because quality degrades as the window fills, not only at the very edge.
Verify before declaring done
1. The agent edits code to fix the bug
2. The harness runs the test suite itself (not the agent's claim)
3. Tests fail: append the failure output and continue the loop
4. Tests pass: a reviewer subagent with fresh context reads the diff
5. Only then return "done", with the test output attachedThe actor is never its own judge: completion is a fact the harness checks with tests and a fresh-context reviewer, not a sentence the model writes.
When to use it, and when not
Use a loop when the path cannot be written down in advance but success can be checked: getting a failing test to pass, researching across sources, editing many files to a spec. The check is what makes it safe. Without one, a loop only produces confident text more slowly.
- One model call when one input gives one output: classify, extract, summarize.
- A fixed workflow when the steps are known: retrieve, answer, check the format. Cheaper, faster, and testable step by step.
- An agent loop when the next step depends on what the last one found.
Avoid a loop when the answer is needed in one round trip, when actions cannot be undone and no human can approve them, or when nothing outside the model can tell success from failure.
Trade-offs and limits
Each step is a full model call, so a loop pays in tokens, latency and compounding error.
| Cost | Why | Lever |
|---|---|---|
| Tokens | history is re-sent every step, so total input grows quadratically | caching, compaction, subagents |
| Latency | steps run one after another, each waiting on a model reply | parallel tool calls, fewer steps |
| Reliability | independent errors compound: 95% per step is 0.9520 ≈ 36% for 20 clean steps | checks along the way, resume from checkpoints |
| Attack surface | every tool result is input an attacker may control | least privilege, approvals |
| Debugging | the same task takes a different path on each run | full traces, a fixed eval suite |
The reliability row is why short loops with a checker beat long autonomous ones: a failed check turns an invisible error into a visible retry.
Common mistakes
- Orphaned tool calls. Anthropic’s API rejects a request in which a
tool_useblock is not answered by atool_resultwith the sametool_use_idin the next user message. When you trim or compact history, drop a call and its result together. - One message per parallel result. Return every result of a parallel turn together in one user message. Anthropic’s documentation warns that splitting them teaches the model to stop calling tools in parallel.
- Crashing on a tool error. An exception that escapes the harness kills the run and loses the trace. Catch it and return the error text as the result (on Anthropic’s API,
is_error: true) so the model can try another route. - Treating a token-limit stop as an answer. A reply that ends on
max_tokensmay hold half a sentence or an unfinished tool call. The minimal loop above has this flaw: it returns on anything that is nottool_use. - Changing text at the top of the prompt. A timestamp or request ID in the system prompt makes every call a cache miss, multiplying the input cost of the whole run.
- A judge that shares the actor’s context. A reviewer that has read the agent’s reasoning inherits its blind spots. Give the checker fresh context: the requirement and the diff, nothing else.
Check yourself
The minimal loop gets a reply with stop_reason: "max_tokens". What does it do, and what should it do?
It returns reply.text as the final answer, because its only test is != "tool_use". It should treat max_tokens as unfinished: raise the limit or ask the model to continue, and never run a tool call that was cut off.
With the stuck detector, an agent calls read(a.py), grep(x), read(a.py), bash(pytest), read(a.py). On which call does is_stuck first return true?
The fifth: the third identical read(a.py) among the last six calls. Argument order does not matter, because sort_keys=True turns {"line": 3, "file": "a.py"} and {"file": "a.py", "line": 3} into the same key.
Each step of a 20-step task is right 95% of the time, independently. How often is the whole run clean?
0.9520 ≈ 0.358, about 36%. At 10 steps it is about 60% (0.9510 ≈ 0.599). Long unattended runs need checks along the way, not only at the end.
A task passes 70% of single attempts. What are pass@3 and pass^3?
pass@3 = 1 − 0.3³ = 0.973: at least one of three tries succeeds. pass^3 = 0.7³ = 0.343: all three succeed. A user who gets one try sees 70%; pass^k says how often it works every single time.
Questions about The Agent Loop Cheat Sheet
What is an agent loop?
An agent loop is the control structure that turns a language model into an agent. The model receives the conversation and a list of tools, and either answers or requests one or more tool calls. The surrounding program, called the harness, executes those calls, appends the results to the conversation and calls the model again. This repeats until the model produces a final answer or the harness stops it on a step, token, cost or time limit. The model decides what to do next; the harness decides what is allowed and when to stop.
How do you stop an AI agent from looping forever?
Use several independent guards, because the model cannot reliably notice its own loops. Set hard caps in the harness for steps, tokens, money and wall-clock time. Detect repetition by hashing recent tool calls and their arguments, and stop or intervene when the same call keeps recurring. Define verifiable stop conditions, such as tests passing or a file existing, instead of trusting the model to say it is finished. When a guard trips, end the run with a clear status and the full trace rather than silently retrying from the start.
What is the difference between an AI agent and a workflow?
In a workflow, your code fixes the sequence of steps and the model fills in each one, for example extract, then classify, then summarize. In an agent, the model chooses the next step at run time, including which tools to call and when it is done. Workflows are cheaper, faster, easier to test and more predictable, so use them whenever the steps are known in advance. Agents earn their extra cost when the path genuinely varies from task to task, as in debugging, research or editing a large codebase.
How do you defend an agent against prompt injection?
Assume that any text the agent reads, whether web pages, emails, documents or tool results, may contain instructions written by an attacker. Then limit what a successful injection can reach: give the agent only the tools and permissions the task needs, keep credentials out of its context, and require human approval for irreversible actions such as payments, deletions or outgoing messages. Mark untrusted content clearly as data in the prompt and filter outputs that could leak sensitive information. No wording alone is a complete defense, so permission design does the real work.