Table of Contents
- The Bill That Surprised Everyone
- Why Loops Multiply Cost Exponentially
- Where Token Spend Actually Goes in Agent Workflows
- Loop Detection Patterns That Catch Runaway Costs
- Budget Caps and Circuit Breakers
- Model Choice Is a Multiplier, Not the Root Cause
- What Good Cost Architecture Looks Like
The Bill That Surprised Everyone
You shipped an AI agent. Users loved it. Then the API bill arrived and it was 50x what you projected.
The finance team wants answers. You look at your logs and see the model choice is reasonable, the prompts are optimized, and average session length looks normal. So why did costs explode?
The problem isn't what you're measuring. It's what you're not measuring. Agent loops accumulate context in ways that don't show up in monthly totals. A single retry at turn 40 costs more than your entire onboarding flow. One user who hit an edge case ran 200 tool calls before giving up.
Analogy: Monitoring monthly agent costs is like tracking your car's fuel consumption by the year. You know you spent more, but you can't tell whether it was the commute, that road trip, or the time you left it idling in the driveway for six hours.
This post explains where agent costs really come from, which patterns to watch, and how to set guardrails before your next billing cycle.
Why Loops Multiply Cost Exponentially
AI agents don't execute once and stop. They loop. Each turn reads the full conversation history, calls a tool, adds the result to context, and decides what to do next. Token count grows with every iteration.
Here's what happens in a typical agent session:
| Turn | Input Tokens | Output Tokens | Cumulative Input |
|---|---|---|---|
| 1 | 500 | 150 | 500 |
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| --- | --- | --- | --- |
Notice the cumulative input column. By turn 40, you've processed 728,000 input tokens even though output stayed relatively stable. Input tokens dominate agentic workflows. Studies show they often exceed 99% of total token spend.
Retries make this worse. If your agent hits an error and retries three times before succeeding, you're paying for context accumulation on every attempt. A retry at turn 40 costs 10x what the same retry costs at turn 4.
Most cost explosions come from:
- Retry loops: Agent tries the same failing action repeatedly
- Context bloat: Full conversation history included on every turn
- Tool call cascades: One action triggers five more, each reading full context
- Oversized file reads: Agent loads a 50KB file into context and keeps it there
- Session length: User leaves agent running overnight on a stuck task
None of these show up clearly in a monthly billing summary.
Where Token Spend Actually Goes in Agent Workflows
To control costs, you need to understand where tokens accumulate. Here's the breakdown from real agentic coding sessions:
| Cost Driver | Share of Total | Why It Matters |
|---|---|---|
| Input tokens | 95-99% | Grows with every loop iteration |
| Output tokens | 1-5% | Relatively stable across sessions |
| Tool call overhead | Included in input | Each call adds context |
| Model API rate | Multiplier | Applied after loop accumulation |
The key insight: model choice is a multiplier on top of loop behavior. If your agent runs 40 turns with 700K cumulative input tokens, switching from a premium model to a cheaper one saves money. But fixing the loop that caused 40 turns in the first place saves more.
GPU utilization data backs this up. Analysis of 23,000 GPU clusters found average utilization at just 5%. Most provisioned AI capacity sits idle while teams burn through operating budgets on the capacity they do use. The gap between provisioned resources and actual productive work is massive.
Loop Detection Patterns That Catch Runaway Costs
You can't fix what you don't measure. Effective cost control requires detecting problematic loop patterns before they accumulate.
Here's what to instrument:
Turn count per session. Sessions that exceed 20 turns deserve investigation. Sessions over 50 turns are almost always stuck or inefficient.
Token growth rate. Track cumulative input tokens per turn. If the rate accelerates (turn 10 uses 2x the tokens of turn 5, turn 15 uses 2x turn 10), context bloat is happening.
Retry frequency. Count how often the agent attempts the same tool call. Three consecutive failures should trigger a circuit breaker.
Tool call diversity. If your agent calls the same tool five times in a row with similar arguments, it's stuck in a loop.
Session duration. A user session that runs longer than your expected task completion time (e.g., 10 minutes for a code review) may be spinning.
Here's a simple detection pattern:
class LoopDetector:
def __init__(self, max_turns=30, max_retries=3):
self.max_turns = max_turns
self.max_retries = max_retries
self.tool_history = []
def check_turn(self, turn_num, tool_name, cumulative_tokens):
if turn_num > self.max_turns:
return "MAX_TURNS_EXCEEDED"
self.tool_history.append(tool_name)
recent_calls = self.tool_history[-self.max_retries:]
if len(recent_calls) == self.max_retries and len(set(recent_calls)) == 1:
return "RETRY_LOOP_DETECTED"
return None
This catches the most common failure modes: sessions that run too long and agents stuck retrying the same action.
Budget Caps and Circuit Breakers
Detection alone doesn't stop cost accumulation. You need enforcement mechanisms.
Per-session token budgets. Set a hard cap on cumulative tokens per session. When hit, gracefully terminate with a message like "This task exceeded complexity limits. Please break it into smaller requests."
Turn limits. Stop sessions after a fixed number of turns (20-30 is typical). This prevents infinite loops regardless of token count.
Retry budgets. Allow a maximum of 2-3 retries per tool call. After that, fail fast and report the error to the user.
Rate limiting. Limit how many concurrent agent sessions a single user can run. This prevents one user from consuming all capacity.
Cost tiers. Route simple requests to cheaper models and reserve premium models for complex tasks. Not every request needs your most expensive model.
Here's what a budget system looks like:
| Budget Type | Limit | Action on Exceed |
|---|---|---|
| Session tokens | 100K cumulative | Graceful termination |
| Turn count | 30 turns | Hard stop |
| Tool retries | 3 per call | Fail and report |
| Concurrent sessions | 5 per user | Queue or reject new |
| Daily user spend | 1M tokens | Soft throttle |
Implement these as middleware in your agent framework. They should trigger before the model call, not after.
Model Choice Is a Multiplier, Not the Root Cause
Model pricing matters, but it multiplies whatever loop behavior you already have.
If your agent runs 40 turns with 700K input tokens, here's what different model choices cost:
| Model Tier | Cost Factor | Total Session Cost |
|---|---|---|
| Premium (e.g., Opus) | 10x | High |
| Standard | 1x | Baseline |
| Budget | 0.1x | Low |
The absolute numbers change, but the pattern doesn't. A retry loop at turn 40 costs 10x what it costs on a budget model, but it still costs 100x more than a well-designed flow that completes in 4 turns.
Model choice optimization matters after you've fixed loop behavior. If your agent runs efficiently (under 10 turns, minimal retries, controlled context), then model choice becomes the primary cost lever.
The right strategy:
- Fix loop behavior first. Instrument, detect, and prevent runaway sessions.
- Route intelligently. Use cheaper models for routine work, premium models for hard problems.
- Monitor model impact. Once loops are controlled, A/B test model tiers to find the cost/quality sweet spot.
Local models will matter more over time. Not because they beat frontier models, but because they can absorb routine work cheaply and privately. Enterprises that send every task to the most expensive model are leaving money on the table.
What Good Cost Architecture Looks Like
A well-architected agent system has cost controls at every layer:
Request layer: Authenticate, rate limit, check user quotas before any work happens.
Budget layer: Enforce per-session token caps and turn limits. Reject requests that will obviously exceed budget.
Routing layer: Send simple tasks to cheap models, hard tasks to premium models. Don't default to the most expensive option.
Execution layer: Instrument turn count, token growth, retry frequency, and tool call patterns. Kill loops early.
Monitoring layer: Track cost per session, cost per user, and cost per task type. Alert on anomalies.
This architecture prevents cost surprises. You catch runaway loops before they accumulate 700K tokens. You route intelligently instead of defaulting to premium models. You know which users and tasks drive cost.
Conclusion
Agent costs explode because loops accumulate context exponentially. Model choice matters, but it multiplies existing loop behavior. Fix the loops first.
Instrument turn count, token growth, and retry patterns. Set hard caps on session budgets and turn limits. Route requests to appropriate model tiers. Monitor costs by user and task type.
The teams that control agent costs are the ones that measure loop behavior, not just monthly spend. Build detection and enforcement into your agent architecture from day one. Your finance team will thank you.