Sub topic 14
Budgets, Step Limits and Guardrails
This chapter assumes you have read the earlier chapters on how tokens are billed, how an agent loop resends a growing context, and how to read usage data. You should be comfortable reading Python and JSON. Here we turn those measurements into limits that stop an agent from spending more than you intended.
Why an agent needs limits
A single request has a bounded cost. Its input size is fixed when you send it, and its output is capped by max_tokens. An agent loop has neither bound. The model decides at each turn whether to call another tool, and every call adds to a context that is resent on the next turn.
Three failure modes account for most surprise bills:
- Runaway loops. The agent repeats the same failing command, such as a test run that fails for an environment reason it cannot fix. Each turn is more expensive than the last because the context keeps growing.
- Oversized inputs. One tool call returns a huge file or log, and every later turn pays to resend it.
- Unattended scale. A job that costs a few dollars per task runs on hundreds of tasks overnight, with no one watching.
Limits do not make an agent smarter. They cap the worst case, so that a bad run costs a known maximum instead of an open-ended amount.
Kinds of limits
Limits work at different scopes. Use several together, because each catches a different failure.
| Limit | Scope | What it catches | Typical action when hit |
|---|---|---|---|
| Max steps (turns) | One task | Loops that never finish | Stop and report |
| Max tokens per request | One request | Very long outputs, runaway reasoning | Truncate or fail the step |
| Max context size | One task | Context growth from tool output | Compact, or stop |
| Cost cap per task | One task | Any expensive task | Stop and report |
| Daily or monthly budget | Team or project | Many moderate tasks adding up | Alert, then block |
| Repeat detection | One task | The same call made again and again | Stop or change approach |
The step limit is the simplest and most useful. Because the input tokens of a loop grow faster than the number of turns, a cap on turns also caps cost in a predictable way. With the earlier example (5,000 system tokens, 2,000 tokens added per turn), 20 turns bill 480,000 input tokens. Raising the cap to 40 turns bills far more than double that.
def loop_input_tokens(system_tokens, step_tokens, turns):
"""Total input tokens billed across an agent loop with no caching."""
total = 0
context = system_tokens
for _ in range(turns):
total += context
context += step_tokens
return total
for turns in (10, 20, 40):
print(turns, loop_input_tokens(5_000, 2_000, turns))
# 10 140000
# 20 480000
# 40 1760000Doubling the turn cap from 20 to 40 multiplies the worst-case input by about 3.7. Choose a step limit from the longest legitimate task you have observed, not from a round number.
A budget tracker you can run
A guardrail needs the same numbers you use for measurement: the usage reported by the API after each call. The class below keeps a running total and raises an exception when a limit is crossed. The prices are placeholders. Use your provider's current price list.
class BudgetExceeded(Exception):
pass
class Budget:
def __init__(self, max_cost_usd, max_steps, price):
self.max_cost_usd = max_cost_usd
self.max_steps = max_steps
self.price = price # USD per million tokens
self.cost_usd = 0.0
self.steps = 0
def record(self, usage):
"""Add one request's usage, then check the limits."""
self.steps += 1
self.cost_usd += (
usage["input_tokens"] * self.price["input"]
+ usage["output_tokens"] * self.price["output"]
) / 1_000_000
if self.steps > self.max_steps:
raise BudgetExceeded(f"step limit {self.max_steps} reached")
if self.cost_usd > self.max_cost_usd:
raise BudgetExceeded(
f"cost {self.cost_usd:.3f} USD over cap {self.max_cost_usd:.2f} USD"
)
budget = Budget(max_cost_usd=0.50, max_steps=30,
price={"input": 3.0, "output": 15.0})
context = 5_000
try:
while True:
usage = {"input_tokens": context, "output_tokens": 500}
budget.record(usage)
context += 2_000
except BudgetExceeded as err:
print("stopped:", err)
print("steps:", budget.steps, "cost:", round(budget.cost_usd, 3))Running this simulation stops on the cost cap at step 9, well before the step limit of 30. Which limit trips first depends on the numbers, which is the reason to set both.
Two details matter here. First, the check runs after the request, so the final request can push the total over the cap. The cap is therefore a limit on what you notice, not a hard ceiling. To get closer to a hard ceiling, estimate the next request's cost before sending it (current context size times the input rate, plus max_tokens times the output rate) and refuse to send it if it would cross the cap. Second, usage figures come from the API response. A local token estimate is fine for the pre-check but should not replace the billed numbers.
What to do when a limit is hit
Stopping is not the only choice, and a bare exception that discards the work is a poor outcome. Pick a behavior for each limit on purpose:
- Stop and report. Return the partial result, the last error, and the spend so far. This is the right default for step and cost caps, because a human can decide whether to continue.
- Compact and continue. For a context-size limit, summarize older turns and drop bulky tool output, as covered in the chapter on context management. Allow this only a fixed number of times, or compaction itself becomes a loop.
- Downgrade the model. Near the cap, route remaining low-risk steps to a cheaper tier. This follows the routing policy from the earlier chapter and works best for steps such as summarizing output.
- Ask for approval. Pause and ask whether to raise the cap. This suits interactive sessions and not unattended jobs.
Whatever you choose, log it. A limit that fires silently looks like a model failure in your evaluation data and distorts cost per resolved task.
Detecting loops without a step limit
A step limit stops a runaway loop only after it has burned its allowance. Repeat detection catches it sooner. A simple form fingerprints each tool call by name and arguments, and stops when the same fingerprint appears too often.
import json
from collections import Counter
class RepeatGuard:
def __init__(self, max_repeats=3):
self.max_repeats = max_repeats
self.seen = Counter()
def check(self, tool_name, arguments):
key = tool_name + ":" + json.dumps(arguments, sort_keys=True)
self.seen[key] += 1
return self.seen[key] <= self.max_repeats
guard = RepeatGuard(max_repeats=3)
for attempt in range(5):
ok = guard.check("run_tests", {"path": "tests/test_api.py"})
print(attempt + 1, "continue" if ok else "stop: repeated call")
# 1 continue
# 2 continue
# 3 continue
# 4 stop: repeated call
# 5 stop: repeated callThis is deliberately crude. Re-running a test after an edit is legitimate, and the arguments are identical. A better fingerprint includes something that changes when the agent makes progress, such as a hash of the edited files. Tune max_repeats against real traces so you do not stop good runs.
Guardrails beyond cost
Not every guardrail is about money, but several protect spend indirectly:
- Output caps. Set
max_tokenson every request. If you enable reasoning, set a separate thinking budget so that one hard step cannot consume a large share of the task. - Tool output truncation. Cap the size of what a tool may return, and say so in the result (for example, "truncated at 20,000 characters"), so the model can ask for a narrower read.
- Timeouts. A hung command ties up a loop and, in some setups, a billed session. Give every tool call a time limit.
- Allowed tools and paths. A subagent that only needs to read files should not receive tools that can write or run commands. This limits both the damage and the context it can accumulate.
- Concurrency limits. If you run many agents in parallel, cap how many run at once. Otherwise the daily budget can be spent in minutes before an alert reaches anyone.
Setting the numbers
Pick limits from data, in this order:
- Run a representative set of tasks with no tight limits, but with logging on.
- Record steps, tokens and cost for each task, split into resolved and unresolved.
- Look at the distribution of resolved tasks. A cap near the 95th percentile of resolved cost lets nearly all good runs finish.
- Check the unresolved tasks. If they cluster far above that cap, the cap saves money at little cost. If they overlap with resolved tasks, a tight cap will convert some successes into failures.
That last point connects to the previous chapter. A cap that is too low raises the failure count and so raises cost per resolved task, even though each individual run is cheaper. Evaluate limits the same way you evaluate models: by total spend divided by tasks resolved.
For team budgets, add alerts before the hard block. A common pattern is an alert at 50 percent and 80 percent of the period budget, and a block at 100 percent for unattended jobs only, so interactive work is not cut off without warning.
How the limits fit together
Common mistakes
- Only a monthly budget. It tells you about a problem after it has happened, and not which task caused it.
- Limits with no logging. You cannot tune what you cannot see, and capped runs pollute your success rate.
- Setting the cap at the average. About half of normal tasks then hit it. Base it on a high percentile.
- Ignoring cached tokens in the tracker. If your provider bills cache reads and writes at different rates, a tracker that uses one input rate will drift from the invoice. Track those token types separately, as in the caching chapter.
- Treating the cap as exact. Concurrent requests and post-hoc checks both allow overshoot. Leave headroom between your cap and the amount you can actually afford.
Exercise
An agent run starts with a 5,000-token context and adds 2,000 tokens per turn. You use no caching, an input price of 3.0 USD per million tokens, and ignore output cost. A task needs at most 15 turns when it succeeds. Compute the input cost of a run that reaches 15 turns and of a runaway run that is stopped by a 40-turn cap. Then say why a repeat guard could still be useful with the 40-turn cap.
Show answer
For n turns the input total is 5,000n + 2,000 × n(n−1)/2. At 15 turns: 75,000 + 2,000 × 105 = 285,000 tokens, which costs 285,000 × 3.0 / 1,000,000 = 0.855 USD. At 40 turns: 200,000 + 2,000 × 780 = 1,760,000 tokens, which costs 5.28 USD. The runaway run costs about 6 times a successful one. A repeat guard stops a loop that is calling the same failing tool with the same arguments after a few repeats, so it avoids most of that extra spend instead of waiting for the 40th turn.
Exercise
Your tracker raises BudgetExceeded after the request that crosses the cost cap. Describe one change that makes the cap closer to a hard ceiling, and one reason it still cannot be exact.
Show answer
Before each request, estimate its worst-case cost (current context tokens times the input rate plus max_tokens times the output rate) and refuse to send it if the running total plus that estimate would exceed the cap. It still cannot be exact because the context token count is an estimate until the API reports usage, and because parallel requests or other callers sharing the same key can spend money your tracker has not yet recorded.