AI Coding Tools: How They Work and How Token Costs Are Calculated
Explore the architecture behind AI coding tools, from code retrieval and context engineering to tool execution and agent loops. Learn how token usage, prompt caching, and provider pricing multipliers affect costs, where billing estimates commonly go wrong, and how to make usage more predictable and manageable.
1. Why AI Coding Tools Are More Than Autocomplete
AI coding tools with code-generation and repository-level understanding capabilities have become increasingly common over the past two years. Many developers still view them as smarter autocomplete. From an engineering perspective, however, they are better understood as distributed systems built around a large language model, supported by retrieval and tool execution.
Understanding how these systems work helps developers provide more effective prompts and context. It also makes their usage costs easier to control.
This article follows two connected threads: how a model receives the information it needs to understand and modify a codebase, and how the tokens consumed during that process are counted and priced.
2. The Architecture: Four Layers
A typical AI coding tool can be divided into four layers:
- Interaction layer: An editor extension, command-line interface, or web session. It captures user intent, displays streaming responses and diffs, and handles execution approvals.
- Context-building layer: Supplies the model with relevant code through repository indexing, symbol retrieval, dependency analysis, and recently edited file collection.
- Reasoning and orchestration layer: Assembles system prompts and context, sends model requests, parses tool-call requests, and manages multi-turn execution loops.
- Execution and sandbox layer: Applies changes by reading and writing files, running tests, and executing builds, typically with permission allowlists and isolated environments.
The central point is that the model does not inherently know your project. Each response depends on the information included in that request’s context window. The impression that a tool understands an entire repository comes largely from its context-building and orchestration layers.
3. Core Technical Principles
3.1 Code Retrieval and Context Engineering
Most repositories are too large to fit into a model’s context window, so the system must first select relevant information. Three common approaches are:
- Lexical and symbol retrieval: Matches identifiers, file paths, and call relationships. This is useful for locating definitions.
- Vector retrieval: Uses a retrieval-augmented generation (RAG) approach, encoding code chunks as vectors and retrieving them by semantic similarity. This helps locate implementations with related functionality.
- Structural retrieval: Uses abstract syntax trees (ASTs) and dependency relationships to assess the potential impact of a change.
In practice, systems often combine all three: retrieve an initial set of candidates, rerank them, and trim the results to fit a token budget. The quality of context engineering largely determines the quality of the resulting output.
3.2 System Prompts and Role Constraints
System prompts serve three main purposes:
- Define the model’s role and output requirements, such as making minimal changes and preserving tests.
- Provide environment information, including the operating system, directory structure, and available commands.
- Specify available tools and their invocation formats.
System instructions are typically included in each model request. As a result, longer system prompts increase the recurring input-token load across the task, with the billed cost depending on applicable caching rules.
3.3 Tool Calling and Agent Loops
Tool calling is what allows a coding assistant to take action. The model does not directly modify files; it produces structured tool-call requests. An external execution layer performs those operations and returns the results to the model.
Start loop├─ Assemble context: system prompt + history + retrieved snippets├─ Call the model├─ If a tool call is returned:│ execute in the sandbox → append results to context → continue└─ If a final response is returned:display diff / summary → end loop
The number of iterations, the context size in each iteration, and any retries jointly determine the actual consumption of a task. A request that looks like a single question may trigger more than a dozen model calls behind the scenes.
3.4 Context Compression and Long-Running Tasks
Long conversations accumulate context. Common ways to manage this growth include summarizing earlier history, retaining tool-result conclusions rather than full output, and pruning failed attempts.
These techniques improve performance while also reducing costs.
4. Token Pricing: Understanding the Bill
4.1 Tokens Are Not Characters
Tokens are the units produced by a tokenizer and used to measure model usage. Different tokenizers can produce different counts for the same code. Chinese text, comments, indentation, and long identifiers can all affect tokenization.
Character counts cannot be used as a direct substitute for billable token counts. Use the usage statistics returned by the tool or API for accurate accounting.
4.2 Input, Output, and Cached Tokens
A common billing model distinguishes among:
- Input tokens: The prompt and context supplied to the model.
- Output tokens: The completion generated by the model.
- Cache-read tokens: Input processed through an applicable prompt cache.
When successive requests share an identical prefix, the server may reuse previously computed intermediate results. Cache reads are typically priced substantially below ordinary input processing.
This leads to a useful practice: place stable content at the beginning of the prompt and frequently changing content toward the end to improve the likelihood of cache hits.
4.3 Provider Multipliers: Different Prices for the Same Model
The same model may be available through different access providers or service tiers. Some apply a pricing multiplier to the base token rates:
Effective unit price = Base unit price × Provider multiplierTotal cost = Σ(Token count for each category × Its effective unit price)
Multipliers can change as providers adjust their pricing policies. Check the rates published for the selected provider or tier at the time of purchase rather than relying on an older figure.
The following code illustrates a cost estimate:
def estimate_cost(usage, base_price, factor):# usage: {"input": n, "output": n, "cache_read": n}# base_price: Base rates per million tokens for input, output, and cache readstotal = 0.0for key, tokens in usage.items():total += tokens / 1_000_000 * base_price[key] * factorreturn round(total, 4)
4.4 Four Common Billing Mistakes
- Applying the multiplier incorrectly. It multiplies the base unit rate; it is not an amount added to the total. If a displayed rate already includes the multiplier, do not apply it again.
- Assuming the default view shows the lowest-priced tier. A pricing page may display a default provider or tier when none is selected. An apparent twofold price difference may simply reflect different tiers.
- Treating platform credits as currency. Some platforms bill in credits rather than money. Convert deductions using the platform’s credit-to-currency ratio, even when that ratio is 1:1. Before comparing with direct official API pricing, normalize the currency and exchange rate.
- Assuming model availability is identical across providers. Availability can vary by access channel. If a selected provider does not offer a model, the request may fail rather than automatically switch to another provider and incur charges there. Check availability before launching batch tasks.
5. Cost Optimization and Governance
- Route tasks by model capability: Use lightweight models for completion and formatting, and more capable models for architectural work and difficult refactoring.
- Keep context focused: Include relevant files and necessary snippets instead of sending the entire repository.
- Stabilize prompt prefixes: Improve cache-hit rates and reduce repeated input-processing charges.
- Set budgets and alerts: Use monitoring, alerting, and logging services to track usage by project and individual, with defined spending thresholds.
- Enforce security boundaries: Keep code and secrets out of untrusted contexts. Run generated code in containers or isolated sandboxes. Treat infrastructure such as object storage and message queues as general-purpose supporting services, granting access according to least-privilege principles.
6. Conclusion
The model sets the capability ceiling of an AI coding tool, but context engineering and orchestration determine much of its practical experience and cost.
Understanding token accounting, caching, and provider pricing multipliers turns AI-assisted development from an intuitive, loosely tracked activity into an engineering workflow that can be budgeted, optimized, and governed.
