Optimizing Token Costs in AI Coding: A Practical Guide
This article examines why a single code review task can consume nearly 1.6 million tokens and breaks down the four main sources of token usage: system prompts, file content injection, intermediate tool-call chains, and result restatement. It explains how overloading a single agent context leads to mixed responsibilities, excessive permissions, and context pollution, then introduces a subagent-based approach that splits the workflow into narrowly scoped roles with restricted tool access. The article concludes with five implementation practices: defining scope upfront, using search instead of full-file reads, embedding rules in agent prompts, constraining output formats, and tracking usage through observability. It is intended for teams looking to make AI coding costs predictable and engineering teams managing long-term API usage.
1. Where the Problem Starts: A Code Review That Burned Nearly 1.6 Million Tokens
In real development workflows, handing code review over to an AI coding tool is becoming increasingly common. The developer’s expectations are usually straightforward: scan project files, check readability, spot potential performance bottlenecks, verify best practices, suggest changes, and show both the original and improved snippets.
But when the entire task runs from start to finish in a single unified context, actual consumption can far exceed expectations. In one real-world run, the model was set to a lightweight inference tier, and the context usage recorded after the task finished was close to 1.6 million tokens. That number is not a bug in itself; it is a clear signal that the task scope was never effectively constrained.
Token consumption can roughly be broken down into four parts:
- System prompt and rule overhead: Every interaction round repeatedly carries the role definition and review rules.
- File content injection: When source code is read, entire files enter the context, often more than once.
- Intermediate reasoning and tool-call chains: Explore, search, compare, search again — forming repeated back-and-forth loops.
- Result restatement: Expanding findings one by one and pasting before-and-after code; the output volume itself counts toward consumption.
The second, third, and fourth items are the ones that can actually be controlled. As the number of project files grows, consumption does not increase linearly; it behaves more like multiplicative amplification — because every wrong exploration path drags irrelevant content back into the context.
2. Root Cause Analysis: One Context Carrying Too Many Responsibilities
Pushing all the work onto the main agent creates three types of problems at once.
Mixed responsibilities. The main agent has to understand the request, explore the codebase, perform the review, and produce the report. Rules, file paths, and conclusions all sit in the same context, interfering with one another and making omissions and duplication likely.
Overly broad permissions. Review tasks essentially require read-only capability, but under a unified configuration, write and execution tools are available too. Blurred permission boundaries not only create the risk of accidental modifications but also force the model to weigh unnecessary trade-offs when making decisions.
Context pollution. The large number of irrelevant files pulled in during the exploration phase stays resident in the context, and every subsequent step has to pay for that content. This is the main source of persistently high token consumption.
3. The Approach: Split the Review into Independent Flows with Clear Responsibilities
The core method is to introduce a subagent mechanism. A subagent can be understood as an execution unit with its own role definition, its own system prompt, and restricted tool permissions, while the main agent handles overall orchestration and delegates specific stages when needed.
An example of a workable role breakdown:
| Role | Responsibility | Suggested Permissions |
|---|---|---|
| explorer | Locate relevant files and call relationships | Read-only, search |
| reviewer | Readability and convention review | Read-only |
| code-improver | Performance and implementation quality analysis | Read-only |
| doc-writer | Produce the conclusion document | Read + write to a designated directory |
A configuration sketch (structural illustration, not a specific product interface):
agents:explorer:description: Locate files relevant to this reviewtools: [Read, Glob, Grep]reviewer:description: Review readability and best practices against unified rulestools: [Read, Grep]code-improver:description: Analyze performance and implementation risks and suggest improvementstools: [Read, Grep]
To be objective: subagents do not inherently save tokens. They have their own context and orchestration overhead. The real gains come from three things — narrowing the task scope, reducing irrelevant file reads, and avoiding repeated shuttling of results between multiple contexts.
4. Implementation Essentials: Making Fine-Grained Review Actually Work
First, define the scope before acting. Specify the file list or directory boundary before delegating, and prohibit free exploration across the whole repository. Once the scope is fixed, the upper bound on consumption is largely controllable.
Second, use search instead of full reads. Locate key snippets by symbol and reference relationships first, then read only the necessary line ranges, avoiding repeated injection of entire files.
Third, put rules in the role, not in every conversation round. Hard-code review standards into the subagent’s system prompt; the main agent only passes the task and the scope, and the repeated overhead drops accordingly.
Fourth, constrain the output format. Standardize on structured entries of “issue location + severity + cause + suggested fix”, and paste only key diff snippets when necessary to reduce verbose restatement.
Fifth, invest in observability. Using general-purpose logging services and monitoring/alerting capabilities, record context consumption and tool-call counts per task. Only then can you tell whether the optimization is actually effective rather than relying on gut feeling.
5. Conclusion
High token consumption is usually not a model capability problem but a task organization problem. Breaking a vague “review my code” request into multiple sub-flows with clear scope, restricted permissions, and standardized output both improves the consistency of the conclusions and pulls costs back into a predictable range. For teams that want to use Baidu AI Cloud’s AI coding capabilities, this splitting and constraint approach applies equally well and can serve as a general engineering practice for controlling long-term usage costs.
