Lesson 3 of 6 · 4 min read
Stop Conditions and Budgets
In this lesson
TL;DR: The model's "I'm done" is a proposal; the harness decides when a run ends. Count steps, tokens, time, money and per-tool calls in code, set each limit from what successful runs actually use, stop hard when one is spent, and hold back a reserve so the stopped run can still return a partial result with its exit reason.
After this lesson, you should be able to list the budgets an agent needs, implement them so the model cannot talk its way past them, choose limits from production data, and design what a run returns when it stops early.
Before you read
Commit to an answer now. The lesson that follows explains it, and having guessed first, even wrongly, makes the explanation easier to remember.
1A system prompt says 'You have a budget of 20 tool calls; be economical.' Is that a budget?
The run that did not stop
A research agent is told to compile a competitor report. Partway through, a search provider starts returning HTTP 429 (rate limited). The agent reads each 429, decides the search failed, and tries a slightly different query. Its only exit is "the model returns a final answer", and the model never feels finished, because it never gets results. By morning the run has made 1,900 search calls, the transcript has been compacted eleven times, and the bill is several hundred dollars for a report that was never written.
Every piece of that was ordinary. The provider throttled, the model behaved sensibly turn by turn, compaction worked. What was missing was an exit the model could not override.
What to count
| Budget | Counts | Why it exists |
|---|---|---|
| Steps | Model turns | Bounds every kind of loop, including ones you did not foresee |
| Input and output tokens | Usage reported by the API per call | Long runs grow quadratically in input tokens |
| Money | Tokens × price, plus paid tool calls | The number finance asks about |
| Wall-clock time | Elapsed time since the run started | Users and upstream callers have deadlines |
| Per-tool calls and failures | Calls to each tool, and consecutive failures per tool | Stops a storm against one dependency early |
| Retries | Harness retries across the run | Retries multiply load during an outage |
| Depth | Levels of sub-agents spawned | A sub-agent that spawns sub-agents is a loop with extra steps |
All of these are counted by the harness from facts it already has: the API's usage fields, its own clock, its own dispatch table. None depends on the model reporting accurately.
Enforcing it in code
import time
class BudgetSpent(Exception):
pass
class Budget:
def __init__(self, steps, usd, seconds, per_tool, reserve_usd=0.0):
self.limits = {"steps": steps, "usd": usd, "seconds": seconds}
self.per_tool, self.reserve = per_tool, reserve_usd
self.used = {"steps": 0, "usd": 0.0}
self.tool_calls, self.start = {}, time.monotonic()
def charge_model(self, in_tok, out_tok, in_price=3e-6, out_price=15e-6):
self.used["steps"] += 1
self.used["usd"] += in_tok * in_price + out_tok * out_price
self._check(spendable=self.limits["usd"] - self.reserve)
def charge_tool(self, name):
self.tool_calls[name] = self.tool_calls.get(name, 0) + 1
if self.tool_calls[name] > self.per_tool.get(name, 10**9):
raise BudgetSpent(f"tool:{name}")
self._check(spendable=self.limits["usd"] - self.reserve)
def _check(self, spendable):
if self.used["steps"] >= self.limits["steps"]:
raise BudgetSpent("steps")
if self.used["usd"] >= spendable:
raise BudgetSpent("usd")
if time.monotonic() - self.start >= self.limits["seconds"]:
raise BudgetSpent("seconds")
b = Budget(steps=40, usd=2.00, seconds=600, per_tool={"search": 25}, reserve_usd=0.20)
try:
for turn in range(1000):
b.charge_model(in_tok=6000 + 400 * turn, out_tok=300)
b.charge_tool("search")
except BudgetSpent as why:
print("stopped:", why, b.used["steps"]) # => stopped: tool:search 26
Three design choices in those forty lines matter more than the arithmetic. The budget raises an exception the loop catches, so no code path can forget to check it. The per-tool cap (search: 25) refuses the 26th search request, long before the step or dollar limit, which is the point: one misbehaving dependency is stopped early while the rest of the run could continue. And reserve_usd keeps twenty cents the run cannot spend on exploration, so it can still afford one final model call to summarise what it found.
Ending well when the money runs out
A run stopped by a budget should return something better than silence. On BudgetSpent, the harness spends the reserve on one last call with a fixed instruction: summarise what was established, what remains open, and which sources were consulted. It returns that summary with the exit reason (stopped: search) so the caller, or a person, can decide whether to resume with a bigger budget, fix the dependency, or accept a partial report.
What it must never do is pass off the model's last half-finished message as the answer. The exit reason is part of the result's contract.
Setting the numbers
Guessing limits produces either runs that die before finishing or limits so loose they never fire. Set them from the runs that succeeded:
successful runs, steps used: p50 = 9 p95 = 17 p99 = 26
hard step limit 30 just above p99: kills only runs in trouble
alert threshold 20 above p95: worth a look, not worth a kill
cost limit p99 cost × 1.2, plus the reserve
per-tool limits from the same distribution, per tool
Revisit them when the model, the prompts or the tools change, because the distribution moves. A limit that fired on 0.1% of runs last month and fires on 5% this month is an alert worth having on its own: something upstream got worse.
- 01userCompile a report on Acme's pricing changes this year.
- 02toolsearch(q="Acme pricing 2026")
- 03result8 resultsok
- 04toolsearch(q="Acme price increase announcement")
Normal start
Two searches return results. The run is doing what it should.
Done is a predicate, not a feeling
The same logic applies to the happy exit. "The model returned no tool calls" means the model believes it is finished. For many tasks the harness can check: the report has every required section and each claim cites a source; the tests pass; the ticket's required fields are filled. Where a check exists, completion is the check passing, and a model that declares victory early is sent back with what failed. Where none exists, say so in the result, so nobody downstream mistakes confidence for verification.
Say it in 30 seconds
"The model proposes being done; the harness decides when the run ends. I count steps, tokens, money, wall-clock time, per-tool calls, retries and sub-agent depth in code, raise when one is spent, and catch it in one place. Limits come from the distribution of successful runs, just above p99, with alerts above p95. I keep a reserve so a stopped run can summarise what it found, and every result carries its exit reason. Where completion can be checked, it is a check, not the model's word."
Check yourself
Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.
1Successful runs use 6 steps at p50, 14 at p95 and 19 at p99. Where do you put the hard limit and the alert?
2Why is a per-tool call limit worth having when you already have an overall step limit?
3A budget is spent on turn 23. What should the run return?