Sub topic 14
Budgets, step limits and guardrails
This chapter assumes you have read the earlier chapters on token pricing, agent loop cost and measuring usage. You should be comfortable with the per-request cost formula and with reading usage data from API responses. Measuring spend shows you what a run cost after it finishes. Budgets and guardrails stop a run from costing too much while it is still going.
Why measurement is not enough
An agent loop decides for itself how many turns it takes. A test that keeps failing, a file read that returns a huge log, or a retry cycle can each push one task far past its normal cost. Because every turn resends the whole context, the cost of a runaway loop grows faster than the number of turns. A dashboard that reports the overspend the next day does not help with that run.
Three kinds of limit
Each limit catches a different failure, so most setups combine them.
| Limit | What it caps | Failure it catches |
|---|---|---|
| Step limit | Number of model calls in one run | Loops that never converge, such as repeated failing edits |
| Token limit | Input or output tokens per call or per run | Oversized tool output, runaway context growth |
| Cost limit | Estimated USD per run, per day, or per user | Anything the other two miss, including a costly model choice |
A step limit is the simplest and most predictable. A cost limit is the most direct, but it depends on correct prices, so keep them in one place and update them when your provider changes rates.
A guard you can run
The guard below records usage after each model call and reports a stop reason once a limit is reached. The prices are placeholders, as in earlier chapters.
class RunGuard:
def __init__(self, max_steps, max_cost_usd, price):
self.max_steps = max_steps
self.max_cost_usd = max_cost_usd
self.price = price
self.steps = 0
self.cost = 0.0
def record(self, usage):
self.steps += 1
self.cost += (
usage["input_tokens"] * self.price["input"]
+ usage["output_tokens"] * self.price["output"]
) / 1_000_000
def stop_reason(self):
if self.steps >= self.max_steps:
return "step limit reached"
if self.cost >= self.max_cost_usd:
return "cost limit reached"
return None
price = {"input": 3.0, "output": 15.0} # placeholder prices
guard = RunGuard(max_steps=20, max_cost_usd=0.15, price=price)
for turn in range(100):
# Simulated usage: the context grows by 2,000 tokens each turn.
usage = {"input_tokens": 5_000 + 2_000 * turn, "output_tokens": 500}
guard.record(usage)
reason = guard.stop_reason()
if reason:
print(f"stopped after {guard.steps} steps: {reason} (${guard.cost:.4f})")
breakThis prints stopped after 5 steps: cost limit reached ($0.1725). The cost limit fires first because each turn costs more than the last. Note that the run ends slightly above the limit. The guard checks after a call has been paid for, so the limit can be overshot by up to one call.
Choosing limits and handling a stop
Set limits from data, not guesses. Take the cost per task from your usage records and set the run limit a few times above the typical successful run. A limit near the median will stop good runs. A limit far above it will not protect you.
Decide what a stop means before it happens. Useful options are:
- Return the partial work and say which limit was hit.
- Ask the user whether to continue with a higher limit.
- Fall back to a cheaper model for the remaining steps.
Also add guardrails that are not about money. Cap the size of a single tool result, so one file read cannot add 100,000 tokens. Stop when the agent repeats the same failing tool call several times in a row.
Provider-side spend caps and alerts are a useful second layer for daily and monthly totals. They work on delay, so they are a backstop for a single run, not a replacement for a guard.
Exercise
A run uses the guard above with maxsteps=20 and maxcost_usd=0.15. Why can the final cost still be above 0.15, and what limit would you add to reduce the overshoot on a single call?
Show answer
The guard checks only after a call completes, so the call that crosses the limit is already paid for. To reduce the overshoot, add a token limit that caps the size of the context or of tool output per call, and set max output tokens on each request. That bounds how much any single call can cost.