Why Token Consumption Explodes in the Agent Era
This article explains why AI agents consume millions of tokens on seemingly simple tasks. The main driver is not code generation but the repeated carrying of full conversation history across multi-step tool loops, which pushes cost growth well beyond linear. It breaks down what fills the context, why memory is necessary for stateful decisions, and how to control cost through state externalization, context compression, retrieval and tool design, prefix caching, and observability. Readers will find practical patterns and example structures for keeping token usage predictable without losing task continuity.
When a developer uses an AI coding tool to complete a complex task, they are often surprised that token consumption can reach tens of millions or more. The answer is not mysterious: most of the cost is not spent on “writing code” but on making the model “remember what happened before.” The most fundamental difference between an agent and a single-turn conversation is that an agent must make continuous decisions: read files, retrieve information, modify code, run tests, inspect errors, and fix them again. Each step is not an isolated action but must build on the historical state. As a result, the context is carried repeatedly from one round to the next, and token consumption grows at roughly a quadratic rate. Understanding this mechanism is the prerequisite for cost governance and performance optimization.
1. Where Tokens Actually Go: The Cumulative Structure of Multi-Turn Calls
An agent task can be abstracted as a loop: the model outputs a decision, the runtime executes a tool, the tool returns a result, and the result is appended back to the context for the next round.
Illustrative pseudocode:
messages = [system_prompt, tool_schema, user_task]while not finished:resp = model.call(messages) # Input: the full messagestool_call = parse(resp)result = execute(tool_call) # File reads/retrieval/test execution, etc.messages.append(resp) # Output, reasoning, tool callsmessages.append(result) # Tool return results
The key point is that model.call(messages) passes the “full history” every time. Round 1 may contain only the system prompt, tool schema, and user task; round 2 must additionally carry the output and tool results from round 1; round N carries the content of all previous rounds. The idea that “the context of the first step is sent many times” means exactly this: the first step is not executed many times, but its text is repeatedly counted into many inputs.
Therefore, if the context length of a single round is L and the task runs for N rounds, the cumulative input size is on the order of L×N; and since L itself grows with the number of rounds, the overall cost grows noticeably faster than linearly. This is why a seemingly simple request can quickly inflate the bill after dozens of tool calls.
2. What Is Actually in the Context: Four Sources of Information
To optimize consumption, first understand the composition of the context. It can usually be split into four categories:
- Static instruction layer: system prompts, role constraints, coding standards, and security policies. It is carried every round and is a fixed cost.
- Capability declaration layer: tool schemas and parameter structure descriptions. The more tools there are and the more detailed the descriptions, the higher the fixed cost.
- Task and historical decision layer: the user’s initial request, the model’s successive outputs, reasoning processes, and tool call parameters. This part determines the completeness of “memory.”
- Environment feedback layer: file snippets, retrieval results, command output, test logs, and error stacks. It is often the largest in size and the most likely to be stuffed into the context without restraint.
Many teams focus only on the “model unit price” but overlook that categories 3 and 4 offer the greatest room for compression. In particular, long logs, large files, and repeated retrieval results can rapidly drive up costs if they enter the context without filtering.
3. Why You Cannot “Send Only the Current Step”: The Necessity of Memory
Some may ask: since history is so expensive, why not send only the current action? Because an agent’s decisions depend on state. The prerequisite for deciding which line to change at step 200 is the file structure read at step 100 and the failure cause exposed by tests at step 150. Remove the history, and the model degrades into a “stateless function” that can only perform single-point text generation and cannot complete cross-step engineering tasks.
So the essence of token consumption is “trading input for continuity.” The engineering goal is not to eliminate context but to make the context carry the necessary state at a lower cost. This leads to the next section: which information must be kept, and which can be externalized.
4. The First Principle of Cost Governance: Externalize State, Keep Only Indexes in Context
A mature approach is to place the “complete state” in the runtime environment rather than stuffing all of it into the model input. The model only needs locating information and summaries, then retrieves details on demand through tools.
For example:
- Do not paste entire file contents; provide only paths, symbol indexes, and key snippets.
- Do not expand all retrieval results; keep only the top few and the hit locations.
- Do not feed test logs back verbatim; first cluster errors and keep only the first root-cause stack.
- Archive the detailed process of completed subtasks, and keep only conclusions and artifact paths in the context.
This is equivalent to migrating “memory” from the model context to external storage and retrieval systems. The context changes from a “warehouse” into a “directory,” and tokens naturally decrease.
5. Context Compression and Summarization: Turning History from “Raw Text” into “Conclusions”
The second category of techniques is compression. Common strategies include:
- Rolling summarization: every few rounds, compress earlier conversation into a structured summary (goal, completed work, open questions, key files).
- Layered memory: keep recent rounds verbatim, and keep only summaries and pointers for distant rounds.
- Structured artifacts instead of process text: replace ten rounds of trial-and-error records with a single change list.
- Deduplication and trimming: remove repeated tool declarations, repeated directory listings, and low-information confirmation statements.
Note that compression loses detail, so a “traceable entry point” must be preserved: record key paths and identifiers in the summary, and allow the model to pull the raw text again when necessary. Compression is not deletion but controlled downsampling.
6. Retrieval and Tool Design: Turning “Large Inputs” into “Precise Inputs”
Much token waste stems from tools returning too much. Optimizing tool contracts is often more effective than switching models:
- Retrieval tools should support pagination, thresholds, and field trimming to avoid returning an entire database at once.
- Code viewing tools should support reading by symbol or line range rather than whole files.
- Execution tools should return only summaries and error codes by default, with detailed logs downloaded on demand.
- Tool descriptions should stay concise to avoid carrying lengthy explanations every round.
Illustrative tool return structure:
{"summary": "3 files matched, 1 likely root cause","items": [{"path": "src/a", "score": 0.91}],"detail_ref": "artifact://log/8f3c"}
The model first reads summary and items, and retrieves details via detail_ref only when necessary. This “index first, fetch later” pattern can significantly reduce the average context length.
7. Caching and Reuse: Do Not Pay Repeatedly for the Same Prefix
Multi-turn calls share a large common prefix (system prompt, tool schema, initial task). The industry commonly uses prefix caching to reduce repeated computation and cost; on the engineering side, the goal is to keep the prefix stable:
- Keep the system prompt and tool schema as unchanged as possible, and place variable content later.
- Move volatile fields such as timestamps and random identifiers out of the prefix.
- Solidify stable specification documents into cacheable segments.
- Cache repeated retrieval and repeated command results locally to avoid re-entering the context.
The more stable the prefix, the higher the cache hit rate, and the more controllable the marginal cost of long tasks.
8. Observability: No Measurement, No Optimization
To govern tens of millions of tokens, you must first be able to “see” the consumption structure. It is recommended to collect at least the following metrics:
- Input/output tokens per round, and cumulative tokens.
- The proportion of each context segment (instructions/tool schema/history/environment feedback).
- Number of tool calls, average return size, and repeated call rate.
- Task success rate, average number of steps, and cost per task.
With these data, you can determine whether the bottleneck is “tool returns that are too large” or “history accumulating too fast,” and act accordingly. An observability system can typically be built on general cloud capabilities such as logging services, monitoring and alerting, and distributed tracing, independent of any specific vendor.
9. Implementation Suggestions in Baidu AI Cloud Scenarios
If you use Baidu AI Cloud capabilities to host an agent runtime, you can adopt a general architectural approach: use a container platform to host the execution sandbox, use object storage to hold large logs and artifacts, use a message queue to decouple tool execution, and use logging services with monitoring and alerting for cost observability. The core remains the principle emphasized in this article: keep only the necessary state in the context, externalize details, retrieve on demand, make them cacheable, and make them measurable. This preserves task continuity while keeping token consumption within a predictable range.
Conclusion: Pay for Memory, but Buy It More Wisely
Developers consume large amounts of tokens every day, and the output is not “more text” but “cross-step continuity.” Truly mature agent engineering is not about blindly extending the context, but about designing a memory system: keep what should be remembered firmly, externalize what should be externalized, compress what should be compressed, and cache what should be cached. When the context changes from “full-volume transport” to “precise indexing,” tens of millions of tokens are no longer an out-of-control bill but an optimizable, predictable, and sustainable engineering cost.
