From Per-Request to Per-Token: Managing Usage and Cost for AI Coding Assistants
This article explains what changes when AI coding assistants move from per-request billing to per-token billing, why input tokens dominate cost, and how long sessions compound spending. It walks through what tokens are made of, context engineering techniques such as retrieval-first context building, project rules files, prefix caching, task-tiered model routing, and output constraints, plus the new cost dimension introduced by multimodality. It closes with team-level cost metrics like cost per task and input/output ratio, and a practical implementation checklist for controlling usage and lowering cost per deliverable.
1. What Actually Changes When the Billing Metric Shifts
Early AI coding tools commonly billed per request. The logic was simple, but it was severely disconnected from the compute actually consumed on the server side. A “help me look at this error” and a “refactor this entire module and fill in the tests” both count as one request, yet the compute they consume can differ by one to two orders of magnitude. The result: light users feel their quota is being crowded out by “heavy” work, while heavy users are repeatedly throttled by artificial rate policies.
Switching to per-token billing means replacing the unit of measurement with “the actual volume of information processed.” This has three direct consequences:
- Billing aligns with load. The server no longer needs to approximate compute usage with a crude request count, and rate policies usually relax as a result, because metering itself now provides load protection.
- Costs become predictable. Developers can estimate in advance “roughly how much context this task needs and how much code it will produce,” and decide whether it is worth starting.
- The optimization target shifts. From “send fewer requests” to “make each request denser in information and lower in noise.”
2. What Tokens Are Made Of: The Input/Output Asymmetry
A token is the smallest unit the model processes and bills for. Different models use different tokenizers, but a common rough rule of thumb is: Latin text such as English runs about 4 characters per token, Chinese runs about 1 character per token, and symbols, indentation, and camelCase naming in code get split into extra tokens.
What really drives the bill is that within a single request, input far outweighs output:
- Fixed overhead: the system prompt, tool definitions, and project conventions, carried with every request.
- Dynamic context: relevant source files, error stack traces, dependency notes, terminal output.
- Conversation history: in a multi-turn session, everything said before is sent again.
- Output: the code, explanations, and reasoning the model generates.
In typical coding scenarios, input is often 5–10x the output. That means optimizing the input side pays off far more than agonizing over “making the model write two fewer comment lines.”
# Rough token estimation, for cost prediction before starting a task only# For exact metering, defer to the usage field returned by the serverdef estimate_tokens(text: str) -> int:cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")other = len(text) - cjk# ~1 token per Chinese character; others estimated at 4 chars per tokenreturn cjk + (other + 3) // 4
3. The Compounding Effect of Long Sessions: Why Longer Chats Cost More
This is the most easily overlooked cost source once billing becomes usage-based. Every request must carry the full history, so the input for a single turn grows roughly linearly with the number of turns, while the cumulative consumption of the whole session is its integral, trending quadratic:
def session_input_tokens(history, new_msg) -> int:total = SYSTEM_PROMPT_TOKENSfor turn in history: # every prior turn must be re-senttotal += turn["prompt_tokens"]total += estimate_tokens(new_msg)return total# Turn n input ≈ n × average message size per turn# Total session consumption ≈ on the order of O(n^2)
Running the numbers with illustrative data: the system prompt and project conventions are about 1K tokens, 8 relevant files about 12K, and the task description plus history about 3K, so single-turn input is about 16K and output about 2K. If you keep asking follow-up questions for 10 turns in the same session, cumulative input climbs from 16K all the way past 160K, for a total close to 900K, while the final useful code produced might be only around 20K.
The conclusion is clear: don’t share one long session across different tasks. Task A’s debugging trail is worthless to Task B, yet you keep paying for it every turn.
4. Context Engineering: Spending Every Unit of Compute in the Right Place
4.1 Retrieval First, Not Dumping the Whole Repository
Stuffing an entire repository into the context at once is the most typical waste. The right order is to locate first, then trim, and keep only interface signatures for large files:
def build_context(query, repo_index, budget=6000):picked, used = [], 0for f in repo_index.search(query): # retrieve first, ranked by relevanceif used + f.tokens > budget: # hard budget constraintbreakpicked.append(f.path)used += f.tokensreturn render(picked, signatures_only=True)
4.2 Replace Repeated Explanations with a Project Rules File
Codifying your tech stack, directory layering, naming conventions, and no-change zones into a rules file that is committed with the repository is cheaper and more stable than repeating them in every conversation:
# Project conventions (fixed context for every session)## Tech stack and layering- Backend layers: controller / service / repository; no cross-layer direct calls- Frontend: do not introduce new UI frameworks or global state libraries## Change constraints- Modify only files directly related to the task; don't rewrite unrelated modules- Any new dependency must state its rationale, size impact, and maintenance risk## Output format- Conclusion first, then diff fragments; don't output whole files unless explicitly asked## Testing requirements- Logic changes include a minimal runnable test; stub all external dependencies
4.3 Task-Tiered Routing
Not every task needs the most powerful model. Formatting, comment completion, and simple type annotations can go to a lightweight model; cross-module refactoring, concurrency bug localization, and performance bottleneck analysis can be escalated to a stronger model. The tiering basis can come from task labels, the number of changed files, or historical acceptance rates, and the payoff is immediate.
4.4 Reuse Cacheable Prefixes
The system prompt and project rules are a prefix that does not change from request to request. Most inference services support caching and reusing a stable prefix, so you are billed only for the new content. The engineering implication: put volatile content at the tail of the request and stable content at the head. Don’t concatenate timestamps or random IDs into the system prompt just to make it look tidy.
4.5 Constrain the Output Shape
Explicitly requiring “diff only,” “don’t rewrite the whole file,” and “keep explanations to three sentences” can significantly shrink output tokens while also lowering the cost of manual review.
4.6 Fix the Context Before Retrying
When the build fails or tests fail, repeatedly clicking “try again” means paying for the same context over and over. A more effective approach is to add the full error stack trace and key intermediate artifacts to the context, so the model gets new information instead of repeating the same guesses.
5. A New Cost Dimension from Multimodality
Native multimodality lets coding assistants read screenshots, design mockups, sequence diagrams, and error screens directly. But images are not billed the same as text of equal length: an image is usually split into tiles and converted to tokens per tile, and a high-resolution screenshot’s equivalent token count is often far higher than a passage of descriptive text.
Practical advice: crop to the relevant region instead of taking a full-screen shot; compress moderately before submitting; and when structured information can express the same thing, prefer a structured description (such as an interface definition, a DOM fragment, or raw log text), saving screenshots for cases that genuinely require visual judgment.
6. A Team Perspective: From “Monthly Total” to “Cost per Task”
If quota management only watches the monthly total, you cannot attribute costs afterward. Consider establishing the following metrics:
- Cost per effective task: the total tokens consumed to complete one deliverable task, a more meaningful efficiency metric than the total.
- Input/output ratio: a persistently rising ratio usually signals that context is out of control.
- Prefix cache hit rate: reflects whether your rules files and prompt design are sound.
- Retry rate and human acceptance rate: a high retry rate indicates poor context quality, while a low acceptance rate indicates a model-selection mismatch.
- Cost distribution by person / by repository: used to spot abnormal usage rather than to simply cap consumption.
If your R&D toolchain is already deployed in the cloud, you can bring usage data into a unified observability system using general-purpose logging services, monitoring and alerting, and metering capabilities (cloud vendors such as Baidu AI Cloud offer products in these categories) to set up threshold alerts and per-team quota allocation, instead of relying on manual tallying.
7. Implementation Checklist
- Create and commit a project rules file to eliminate repeated explanations;
- One task, one session; start a new session whenever you switch tasks;
- Enforce a hard context budget, with retrieval first and signatures only for large files;
- Place stable prefixes first to enable cache reuse;
- Route to model tiers based on task complexity;
- Define output constraints explicitly, defaulting to diff fragments only;
- Crop and compress image inputs first, and prefer text whenever possible;
- Add new information before retrying to avoid spinning;
- Build a dashboard for cost per task and the input/output ratio;
- Periodically prune redundant content from rules files and system prompts.
Conclusion
Changing the billing unit from “per request” to “per token” is, on the surface, an adjustment to how the bill is calculated. In substance, it hands optimization power back to developers. A quota is no longer an artificially carved-out fixed allowance, but a resource that maps one-to-one to actual compute. What has always been truly scarce is not the quota, but effective context: whoever can make the model get it right in one shot with less noise can accomplish several times the work at the same cost.
