AI Agent Cost Overruns: Where Do Tokens Actually Go?
Autonomous coding agents can read code, locate bugs, edit files, and run tests, but their token costs are often unpredictable and can reach hundreds of dollars before a task fails. This article explains why agent costs are hard to estimate, focusing on context growth, input-token dominance, and billed failures. It then outlines practical controls: preflight budgets, context governance, loop circuit breakers and divergence detection, retry and model routing, and treating cost as a first-class evaluation metric.
1. A Familiar Scenario for Developers
Letting a coding agent autonomously fix a bug in a repository sounds appealing: it reads the code, locates the issue, changes the code, and runs tests. But many teams have seen a similar outcome: the agent runs all afternoon, the token bill reaches hundreds of dollars, and the final response is “task execution failed.” The money is spent, and the work is not done.
What this exposes is not that agent capabilities are fundamentally lacking, but that the cost model is severely opaque. A traditional API call is “one request, one response,” so cost is relatively easy to calculate. An agent, by contrast, makes “multiple rounds of autonomous decisions.” Each round may trigger new model calls, tool calls, and context reassembly. Cost keeps rolling and accumulating as the task progresses, and the accumulation path is completely unpredictable.
2. Why Agent Costs Are Hard to Estimate
Task Structure Is Nothing Like a Single Call
Token consumption for ordinary code completion or conversational reasoning is relatively easy to estimate: the input is the current context, and the output is a piece of code or an answer. When an agent executes a coding task, however, it may involve dozens of loop iterations:
- Each round must reassemble the system prompt, task description, interaction history, and tool results into context.
- Every tool call—reading files, retrieval, running tests—writes results back into the context, further inflating the next round’s input.
- The more complex the task, the larger the repository, and the more failure retries, the more loop iterations are needed, and cost grows nonlinearly.
Input Tokens Are the Main Cost
A common misunderstanding in the industry is: “Output tokens have a higher unit price than input tokens, so cost is mainly in output.” For agent-style tasks, the opposite is true. Because each round carries an ever-growing history context, total input-token consumption is often several times or even dozens of times higher than output. For a task that runs dozens of rounds, cumulative input may reach millions of tokens, while the output that actually “does the work” accounts for only a small fraction.
This means the cost ceiling of an agent is mainly determined by “how much history it is carrying,” not by “how much code it writes.”
Failures Are Still Billed
Agents often fail not by crashing immediately, but by repeatedly trying in the wrong direction: editing the wrong file, breaking tests, rolling back, and starting over. Every invalid attempt consumes real tokens. The final bill is determined by the total cost of the exploration process, regardless of whether the task succeeds. This is the root of “hundreds of dollars spent for a task failed message.”
3. Three Key Cost Questions
Drawing on systematic industry research findings, the cost profile of agents can be understood at three levels:
Agent Tasks Cost Much More Than Ordinary Inference
With the same underlying model, token consumption for autonomous agent coding is usually much higher than for single-turn code Q&A. The reason is the loop-inflation mechanism described above: context is not static; it grows every round.
Costs Vary Greatly Across Models
Different models differ significantly in how many loop iterations they need to complete the same task, how they manage context, and how strongly they tend to retry. Some models prefer to output a long plan in one pass, while others make frequent short calls. For the same task and the same unit price, total cost can differ by several times.
Run-to-Run Variance for the Same Model Is Also Striking
Agent behavior is stochastic: the same task run twice may converge in 10 rounds once and diverge for 40 rounds another time. This means “average cost” has limited meaning for agents. What teams really need to focus on is the cost distribution and tail risk.
There is also a counterintuitive warning worth noting: token consumption is not positively correlated with task success. Tasks that burn more tokens are not necessarily doing better work—the extra tokens may well be consumed by ineffective wandering.
4. Practical Cost Controls
Build a Budget Preflight Mechanism
Before a task starts, make a coarse-grained cost estimate: based on repository size, task type (bug fix, feature development, refactoring), and historical run data, set a token budget cap for the task. Before each round, the agent checks the remaining budget; if the limit is exceeded, it actively terminates and outputs a staged conclusion. The budget-check logic can be very simple:
# Illustrative: budget circuit breaker before each loop iterationif usage.total_tokens >= budget_limit:agent.stop(reason="budget_exhausted")return summarize_progress() # Output completed intermediate results
Context Governance Is the First Lever for Saving Money
Since input tokens are the main cost, governing context means governing cost:
- Limit the amount of history carried in each round, and summarize early rounds instead of carrying full text.
- Trim tool results to keep only the parts relevant to the current decision, and avoid stuffing entire files into context.
- Define task boundaries clearly, and prevent the agent from “incidentally” exploring unrelated modules.
Loop Circuit Breakers and Divergence Detection
Monitor the agent’s most recent actions: if similar tool calls appear repeatedly, the same file is read repeatedly, or tests fail repeatedly, classify this as divergence and terminate early. This is more precise than simply setting a maximum round count, and it can cut costs early during ineffective exploration.
Retry Strategy and Model Routing
For high-variance tasks, do not retry blindly. Tasks can be tiered by difficulty: use a low-cost model for simple tasks and call a high-capability model only for complex tasks. When retrying, include a summary of the previous failure so the agent does not start from zero and repeat the same detours.
Make Cost a First-Class Evaluation Metric
When selecting and tuning agents, the evaluation dimensions should not be limited to success rate. They should also include “expected cost per successful task,” “cost P95/P99 distribution,” and “sunk cost of failed tasks.” A solution with a slightly lower success rate but low cost variance is often engineering-wise better than one with a slightly higher success rate but uncontrollable spend.
5. Conclusion
The cost problem of AI agents is fundamentally an engineering observability problem: without measurement, there is no control. Teams should establish budget, monitoring, circuit-breaker, and retrospective mechanisms for agents, just as they do for the latency and cost of online services. Only then can agents move from being “the most expensive intern engineer” to a truly controllable, trustworthy, and optimizable productivity tool.
