Agent Loops
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The loop is the heart of an agent and also where most of the danger lives. A loop with no limits can spend your money all afternoon. A loop with limits but no explanation leaves you guessing why it stopped. This lesson goes through what makes a loop safe to run: the stop conditions, how to count what's been spent, and how to report a stop honestly.
What you'll learn
- The anatomy of one loop iteration.
- The four limits worth setting: iterations, tokens, time and tool calls.
- Why the loop returns a status instead of throwing an exception.
- The beta "task budget" feature, and why it doesn't replace your own limits.
Before you start
One iteration
check limits ──over?──► stop, say why
│
▼
call the model (messages so far)
│
├─ stop_reason = tool_use ──► run tools ──► append results ──► loop
├─ stop_reason = pause_turn ─► send it back as it is ──► loop
└─ anything else (end_turn, max_tokens, refusal...) ──► finish
Look back at _loop in the agent from lesson 6.1. The limit check comes before the model call, so a run that has already used up its budget doesn't start another expensive request. The assistant's whole turn is stored exactly as returned, because the next request has to include it.
The four limits
@dataclass
class Budget:
max_iterations: int = 10
max_total_tokens: int = 60_000
max_seconds: float = 90.0
max_tool_calls: int = 20
- Iterations stop a model that keeps asking for tools without getting anywhere.
- Tokens bound the cost. We add the input and output tokens from every response's
usage. Because each iteration re-sends the conversation, input tokens grow quickly, and this is usually the limit that trips first on a long run.
- Time bounds how long a user waits. We add up the time spent in model calls.
- Tool calls bound side effects, which matter more than tokens when tools change things.
These limits are checked between iterations, so a single iteration can still go a little over. That's fine for a safety net, but don't treat the number as an exact ceiling.
Return a status, don't throw
When a limit is hit, our loop returns a Run whose status is stopped and whose reason says which limit. In module 4 the loop raised an exception. For an agent that's the wrong shape, because hitting a limit isn't a bug; it's an expected outcome that the caller has to handle, usually by handing the case to a person. A returned status makes that branch visible in the calling code:
run = agent.run(email_text)
if run.status == "done":
save_draft(run.text)
elif run.status == "paused":
queue_for_approval(run.pending, run.state)
else: # stopped
escalate_to_person(reason=run.reason, trace=run.trace)
The same function also reports max_tokens as the reason when the model's own reply was cut off, rather than pretending the answer was complete. A half-sentence reply that gets sent to a customer is a worse failure than an error.
The trace
Every run returns trace, a list of events: each tool call with its input and whether it failed, a pause, a rejection, a stop. When someone asks "why did it do that?", this is the answer, and it's also what you'll want in your logs. Keep the trace free of secrets and don't log full customer messages unless you've decided you should.
Task budgets (beta)
Anthropic has a beta feature called task budgets, where you tell the model roughly how many tokens a whole agentic task may use, and the model sees a running countdown and tries to wrap up in time. Two facts from the documentation matter here: the budget is advisory, a hint the model aims for rather than a hard stop, and it's a beta feature with a minimum size, so check the current page before using it. It also isn't something you can switch on in Claude Code. It complements your own limits; it doesn't replace them, because only your code can actually stop the loop.
Testing the loop
With a fake client that returns scripted replies, we tested each limit separately: three iterations stops a model that wants to call tools forever, a 1,100-token response stops a 1,000-token budget before a second request is sent, and three tool calls in one turn stop a budget of three. We also tested that an unknown tool name and a tool that raises both come back to the model as errors, not as exceptions in your code, so one bad call can't crash the whole run.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
An internal assistant is told to investigate a failed invoice. A tool returns a very long audit log, the model asks for another page, then another. With only an iteration limit, the run would use a large number of tokens before the tenth iteration. With a token budget as well, it stops at a known cost, returns token_budget, and the case goes to an accountant with the trace attached. The cost of a runaway is capped, and a person sees exactly where the agent got stuck.
Mistakes to avoid
- Only limiting iterations. Ten iterations can be cheap or very expensive depending on what they read.
- Raising an exception on a limit and letting it surface as a 500 error to a user.
- Relying on an advisory budget as if it were a hard stop.
- Retrying the whole run automatically after a stop. If it stopped at the limit once, it will likely do so again, only now it's cost you twice.
Security notes
Limits are a security control too. A prompt-injected agent that has been told to "keep trying" is bounded by your tool-call limit, which caps how many actions it can take before a person looks. Keep that number as low as the task allows.
Cost and speed
Choose the limits from measured runs: look at the tokens used by successful runs, and set the budget somewhat above the upper end. Too tight and good runs fail. Too loose and it protects nothing. Log the used amount for every run, so you can tune it.
Key takeaways
- Check limits before each model call, not after.
- Four useful limits: iterations, tokens, time, tool calls.
- Return a status with a reason; let the caller decide what a stop means.
- Keep a trace. Task budgets are advisory and don't replace your own limits.
Lesson recap: check four limits before every model call, return a status with a reason, and keep a trace.
Quick quiz
- Why check limits before the model call?
- Which limit usually trips first on a long run, and why?
- Why return a status instead of raising an exception?
- What does
max_tokens as a stop reason tell you?
- Why can't a task budget replace your own limits?
Answers and explanations
- So a run that is already over budget doesn't start another request, which would cost more.
- Usually tokens, because every iteration re-sends the growing conversation, so input tokens climb quickly.
- Hitting a limit is an expected outcome the caller must handle, such as escalating to a person, not a bug.
- The model's reply was cut off by the output limit, so the text may be incomplete and shouldn't be treated as a finished answer.
- It's advisory: the model aims for it, but only your code can actually stop the loop.
Official references and further reading
Related tutorials