Why AI Agents Consume So Many Tokens: A Cost Diagnosis and Optimization Guide
A single user question can trigger dozens of model calls, so token spend is driven by call count, repeated context, tool output, and cache pricing—not by the question itself. This guide explains how cumulative token cost differs from context-window size, how to separate uncached input, cached input, and output charges, and how to record calls, govern context, shrink tool results, and sequence changes so quality stays acceptable while total cost falls.
1. Why one question can generate a large token bill
A user asks one question, but an agent may call the model many times in the background: understand the request, retrieve material, read files, make a plan, call tools, interpret results, edit code, run tests, and then revise again based on failures.
User questions and model calls are therefore different metrics. One complex task may include dozens of calls, and each call may carry accumulated messages, file contents, tool descriptions, and execution results.
Suppose a task makes 40 model calls and each call averages 30,000 input tokens. Cumulative input alone is 1.2 million tokens. This example only illustrates the accounting mechanism; it is not a typical figure for any specific system.
Two concepts must be kept separate:
- Context window: how much content a single call can hold.
- Cumulative token consumption: the sum of inputs, outputs, and other billed items across every call in the task.
Millions of tokens over a task do not mean any one request had a context of that size. What matters is how many calls ran, what each call sent, which content was resubmitted, and whether repeated content received a cache discount.
A question that consumes millions of tokens should not be treated as automatically normal, nor should a complex task be assumed to need a fixed context size. Whether the spend is reasonable depends on task difficulty, the execution path, and final quality.
2. Build a cost model: more tokens do not always mean a higher bill
2.1 High input share is a mechanism outcome, not proof of waste
In coding, document analysis, and long workflows, the input often includes a large amount of background material, while the output may be only a patch, a short conclusion, or the next instruction. Input volume much larger than output volume is common, but that does not imply every task should follow a fixed ratio.
What matters is whether the input is useful:
- Input that supplies evidence needed for a correct decision is a reasonable cost.
- Repeated reads of irrelevant files, stale state, and the same failure logs may be avoidable cost.
- Repeated content that hits a billing cache still increases the token count, but it is not necessarily charged at the full input price.
These three cases should be handled separately.
2.2 Price uncached input, cached input, and output separately
A general estimate is:
Task cost =uncached input volume × uncached input unit price+ cached input volume × cached input unit price+ output volume × output unit price+ other billed items
Volumes and unit prices must use the same units. Whether other billed items exist depends on the actual service terms and invoice; do not assume every service uses the same rules.
If the cached-input price is a fraction r of the normal input price, and the input cache hit rate is h, the average input price as a fraction of the normal input price is:
Average input price ratio = (1 - h) + h × r
As a math illustration only: when h is 90% and r is 10%, the average input price ratio is 19%, not 10%. The 10% that misses the cache is still charged at the normal input price.
Cache hit rate and discount depth must be analyzed together. A cheap cache price does not mean the entire long context receives that discount.
2.3 Caching usually lowers cost, but it does not reduce input tokens
Some systems support prompt caching, but triggers, retention, minimum length, and matching rules can differ. Similar content may not hit the cache, and a local edit can also reduce reuse of later content.
The direct value of caching is mainly lower repeated computation or related charges. Whether latency improves should be measured. Caching does not replace context governance, and it does not remove the distraction of irrelevant information.
3. The first step is accounting, not compression
3.1 Record tasks and individual calls
Daily totals rarely show where the cost comes from. Give each task its own identifier and record, for every call:
- Time, step number, and purpose
- Input tokens, output tokens, and cached input tokens
- Actual charge and its billing source
- Tool type and the size of the returned content
- Latency, retry count, and stop reason
- Whether the task ultimately passed acceptance
Fields should come from real responses and invoices. Do not invent metrics the service does not provide. Label local estimates so they are not mixed with billed figures.
An illustrative record:
Task: fix data validation logicStep: model call 8Purpose: analyze a failing testInput volume: record actual usageCached input volume: use the actual response fieldOutput volume: record actual usageTool result: failing-test summaryAcceptance status: not yet passed
3.2 Find the expensive steps instead of optimizing by feel
Aggregating cost by task, step, and input source usually reveals a few patterns:
- A single request is too large because it attaches irrelevant material.
- There are too many calls because the task loops through edit, verify, and edit again.
- Tool results are too long because whole files or full logs are resubmitted.
- Cache hits are unstable because static content keeps changing.
- Retries multiply cost: the same failing request runs again without fixing the cause.
Having the agent analyze its own logs can help, but only if the system explicitly grants log access. A model does not inherently know its full call history or invoice. When code, credentials, or business data are involved, redact and apply access control first.
4. Govern context: keep evidence, not the entire history
4.1 Split context into four types
A clear organization is:
Stable rules: task boundaries, coding conventions, and output constraints. These should not change arbitrarily on every turn.
Task state: the current goal, completed work, key decisions, and open issues.
On-demand material: relevant file excerpts, interface definitions, failing-test details, and necessary documents.
Temporary process: exploratory discussion, repeated logs, and discarded hypotheses. These usually should not be kept for long.
This split avoids treating the full chat transcript as the only carrier of task state.
4.2 Replace mechanical truncation with a structured state summary
Cutting the oldest messages by length can drop requirements and key decisions. A more reliable approach is a structured summary:
Goal:- Fix input validation without changing the existing calling contractConstraints:- Stay backward compatible- Do not widen the change scopeConfirmed facts:- The problem appears on boundary inputs- The normal input path has already been checkedDone:- Located the relevant functions- Added boundary testsNext:- Change the validation logic- Run the related regression testsEvidence locations:- Relevant file paths and line numbers- Names of failing tests
A summary is not a substitute for original evidence. Important conclusions should keep their source locations so they can be reread when needed. Exact numbers, interface constraints, and failure causes should not be reduced to vague prose.
4.3 Compression has a cost; decide whether it is worth it
Writing a summary itself requires a model call and can lose information. If the task is about to end, one large compression pass may not pay off.
A simple check:
Expected benefit =later call count × input volume saved per turn × applicable input unit price- summary generation cost- rework cost caused by lost information
The applicable input price should account for caching. If most of the old context already hits the cache, replacing it with a new summary may temporarily lower the hit rate. Evaluate the rest of the workflow, not only the next turn’s input length.
5. Cut tool cost: expose less, return less, repeat less
5.1 Expose only the tools the task needs
Tool definitions, parameter descriptions, and usage constraints often become part of the model input. More tools and longer descriptions can raise the base input of a turn and can also increase wrong tool choices.
Not every system sends the full tool list on every turn. Confirm this from actual request logs rather than assuming it.
In practice, group tools by task type. A code-change task needs the necessary file read, edit, and test capabilities. An analysis task needs the necessary search and extraction capabilities. Tools that are irrelevant for now do not need to stay exposed.
5.2 Shrink results on the tool side first
Do not send a full log to the model and then ask it to find the error. Filter deterministically first:
- Return only the relevant time range, severity, and necessary context from logs.
- Prefer the target function, related definitions, and dependency excerpts when reading files.
- Return a summary and location for search results, and read the full text only when needed.
- Highlight failing cases, exceptions, and key call sites in test results.
- Deduplicate repeated results so they are not carried across many turns.
Filtering must keep the evidence the model needs to judge. Cutting too hard can force another query and raise total cost.
5.3 Control tool feedback loops
When the same error repeats, stop mechanical retries and check for missing permissions, an unsuitable environment, flaky tests, or a wrong task assumption.
Retries need a cap, and each retry should record what changed. Repeating a call with no new evidence and no new strategy usually does not move the task forward.
6. Optimize orchestration around acceptance
6.1 Define done before starting
“Optimize the code” invites open-ended exploration. A clearer task states the goal, scope, and acceptance criteria, for example:
- Fix the failure for a specific class of inputs
- Do not change unrelated modules
- Add the corresponding tests
- Stop when those tests pass
- Finally output only a change summary and verification results
Clear stop conditions reduce extra explanation, repeated checks, and aimless expansion.
6.2 Split tasks that are actually independent
When a new problem does not truly depend on the old task, a fresh task context is usually better. Information that must carry over should travel in a short handoff, not the entire history.
Strongly related work should not be split merely to save tokens. Rebuilding background and rereading files also costs money. The test is task dependency, not conversation length.
6.3 Multiple agents are not automatically cheaper
Parallel analysis can speed some tasks, but it can also reread the same material and add coordination and summary charges.
A subtask is a better candidate for parallelism when it has a clear boundary, limited input, and a defined output. If several agents each need the full project context and their work overlaps heavily, serial execution or a shared compact state may be cheaper.
6.4 Do not send every problem to the strongest model
Format checks, simple classification, and deterministic transforms can use rules or ordinary programs first. Reserve a capable model for hard reasoning and critical decisions.
Capability tiering should not look only at the price of one call. A cheaper call that causes more retries and manual repair may cost more overall.
7. Choose a plan after optimization, not before
Subscriptions, credit packs, and pay-as-you-go billing are payment methods. They do not remove inefficient calls.
When comparing plans, check what the allowance covers, cache billing rules, concurrency limits, overage charges, and usage limits, then estimate cost against real workloads. “How many tokens can be consumed per day” is not the only measure of value.
For developers and organizations, a more useful metric is:
Average cost per successful task =related total cost in the period ÷ number of tasks that passed acceptance
Total cost can include model charges, tool charges, and human rework, depending on what you are managing. Also watch completion time, success rate, and defect rate so a lower bill does not hide more rework.
8. A practical order of work
Phase 1 — baseline. Record call counts, input composition, cache behavior, cost, and acceptance results.
Phase 2 — obvious waste. Trim tool results, drop irrelevant context, cap useless retries, and state stop conditions.
Phase 3 — context management. Maintain structured task state, read evidence on demand, and stop moving the same material repeatedly.
Phase 4 — orchestration and billing. Use measured results to adjust task splits, capability tiers, and plan choice.
Change one class of variable at a time, and compare tasks of similar difficulty. Only then can you tell whether an improvement came from less input, a better cache hit rate, fewer calls, or a sacrifice in task quality.
The point of saving tokens is not to make the agent see less and think less. It is to give every call a clear purpose, bring necessary evidence in when it is needed, and drop history that no longer helps. The goal is not the smallest token count. It is completing the task at a lower total cost, within acceptable quality and time.
