How AI Coding Agents Work: Technical Architecture and Token-Based Billing Explained
AI coding agents go far beyond simple code completion—they understand projects, plan tasks, call tools, and verify results in a closed loop. This article explains the core architecture of intelligent coding agents (interaction, context building, reasoning, tool execution, and security layers), walks through how a typical task is completed step by step, and breaks down why a single task can consume large numbers of tokens. It also covers context caching, the general billing formula for input, output, cache-read, and cache-write tokens, how to correctly calculate costs through API gateways with group-based multipliers, common misconceptions, and practical optimization tips.
1. What Is an AI Coding Agent?
An AI coding agent is a class of AI system designed for software development scenarios. Rather than generating code from a single natural-language prompt, it can work through a development task in a continuous loop: understand the project, make a plan, call tools, verify results, and revise based on feedback.
Traditional code completion typically focuses on local fragments within the current file—for example, predicting the next lines of code based on what appears before and after the cursor. An AI coding agent has a much broader scope, usually including:
- Analyzing the project’s directory structure and tech stack;
- Reading multiple source files, configuration files, and documentation;
- Decomposing tasks based on the user’s goal;
- Querying, creating, or modifying files;
- Executing development operations such as tests, builds, and static analysis;
- Reading execution results and continuing to fix issues;
- Finally explaining the changes, verification results, and potential risks to the user.
In essence, it is not a simple “chat window” but a task execution system composed of a large language model, a context manager, a tool execution layer, and a security control layer.
2. Core Architecture: The Model Reasons, the Tools Act
From a system perspective, an AI coding agent can typically be abstracted into the following layers:
2.1 Interaction Layer
The interaction layer receives natural-language requirements from the user, such as “add parameter validation to this API,” “find the cause of the test failure,” or “refactor this duplicated logic.” It also displays the agent’s plan, file changes, command execution results, and final summary.
2.2 Context Building Layer
The model cannot automatically read an entire code repository; the system must first build the context based on the task. Common inputs include:
- The user’s current instruction;
- The currently open file or code snippet;
- Project directory and file summaries;
- Source code relevant to the task;
- Configuration files, API definitions, and test files;
- Conversation history and previous tool execution results.
Context building is a critical factor affecting both quality and cost. If too few relevant files are selected, the model may lack necessary information; if too many are selected, input token usage grows, and important content may be diluted by large amounts of irrelevant information.
2.3 Reasoning Layer
The reasoning layer is handled by the large language model. Based on the context, the model determines the task goal, identifies code relationships, generates an action plan, and decides whether to call a tool next.
Note that the model’s output is not necessarily a final answer—it may be a structured operation, such as reading a file, searching for a symbol, modifying code, or running tests. The system then feeds the tool result back to the model, forming a multi-turn loop.
2.4 Tool Execution Layer
The tool execution layer converts the model’s intent into actual actions. Common tool categories include:
- File reading and directory browsing;
- Code search and symbol lookup;
- File creation, modification, and deletion;
- Test and build execution;
- Version diff viewing;
- Log reading and result analysis.
The tool execution layer typically enforces permission boundaries. For example, reading and modifying files may require different authorizations; executing external commands, accessing the network, or deleting data may require user confirmation. This layer determines whether the agent can safely participate in real development workflows.
2.5 Security Control Layer
The security control layer restricts high-risk behaviors, including access to sensitive files, execution of dangerous commands, bulk modifications, external network access, and credential leakage. Mature implementations do not give the model unlimited permissions. Instead, they rely on mechanisms such as least privilege, operation confirmation, execution isolation, and audit logging.
3. How a Task Is Completed
Take “fixing a failing test” as an example. A typical flow looks like this:
Step 1: The system receives the user’s request and identifies the project scope, the error symptoms, and the expected outcome.
Step 2: The context manager gathers the test file, the code under test, the error logs, and any potentially relevant configuration.
Step 3: The model analyzes the cause of the failure and forms one or more candidate solutions. At this point it may propose plans such as “check parameter types,” “verify boundary conditions,” or “compare against the caller’s expectations.”
Step 4: The agent calls tools such as file reading and code search to obtain more precise information.
Step 5: The model generates a fix, and the tool layer applies the changes to the workspace.
Step 6: The system runs the relevant tests and passes the output back to the model.
Step 7: If the tests still fail, the model continues adjusting based on the new error information; if verification passes, it produces a change summary, test results, and risk notes.
This process can be represented as:
User request↓Task understanding and context building↓Model planning↓Tool calls↓Execution results returned↓Model review and revision↓Test verification and final summary
Therefore, an agent’s capability depends not only on the model itself, but also on context selection, tool design, permission control, and the feedback loop.
4. Why a Single Task Can Consume a Large Number of Tokens
Many users find that although they only typed one sentence, the actual token consumption far exceeds that sentence’s length. The reason is that usage or billing statistics typically include not just the user’s input, but also the context repeatedly sent during the agent’s operation.
A complete task may include:
- System instructions;
- Project structure summaries;
- The contents of multiple files;
- Conversation history;
- Tool call parameters;
- Tool results;
- Plans and explanations generated by the model;
- Test logs and error messages.
If the agent needs multiple rounds of tool calls, the same or similar context may be included in subsequent requests multiple times. Therefore, “the number of characters the user typed” cannot be equated with “actual input tokens.”
For large projects, the following factors are especially likely to amplify consumption:
- Individual files that are very long;
- Resending the full history in every round;
- Tools returning large amounts of irrelevant logs;
- Overly broad search scopes;
- A single task involving multiple modules at once;
- Multiple retry rounds after test failures.
5. The Role of Cached Tokens
To reduce the latency and cost of repeated context, model services typically provide a context caching mechanism. Cache-related usage generally falls into two categories.
5.1 Cache Write
When a long context is first established and written to the cache, cache write usage is generated. This can be understood as the cost of “saving reusable context.”
5.2 Cache Read
When subsequent requests reuse that cached context, it does not have to be fully processed as regular input; instead, cache read usage is generated. Cache read pricing is usually lower than regular input, but the exact rules depend on the service provider’s pricing policy.
Caching does not mean all content is stored permanently, nor that every request will hit the cache. Whether caching takes effect usually depends on the context content, validity period, how requests are organized, and the service implementation. Therefore, when estimating costs, rely on the actual usage fields returned by the API rather than inferring from the number of requests.
6. The General Billing Formula
The usage of a single request can typically be broken down into four categories:
- Non-cached input tokens;
- Output tokens;
- Cache read tokens;
- Cache write tokens.
Let:
- Input volume = I;
- Output volume = O;
- Cache read volume = R;
- Cache write volume = W;
- The corresponding price per million tokens = Pi, Po, Pr, Pw.
Then the cost at official list prices is:
Cost at list price =I / 1,000,000 × Pi+ O / 1,000,000 × Po+ R / 1,000,000 × Pr+ W / 1,000,000 × Pw
If the user accesses the model through a gateway, unified account, or other aggregation service, the platform may apply a multiplier based on the account’s group. Let the group multiplier be M. Then the actual deducted amount is:
Actual deducted amount = cost at list price × M
Two concepts must be distinguished here:
- Official unit price: the base price published by the model service provider;
- Group multiplier: an adjustment coefficient set by the platform for different resource pools, account types, concurrency capabilities, or operational policies.
The multiplier does not change how tokens are counted; it only affects the final cost.
7. How to Correctly Check and Reconcile Costs
When reconciling actual costs, follow these steps:
Step 1: Confirm the model’s official unit prices
Check all four prices: input, output, cache read, and cache write. Do not look at only the input price, because coding agents often generate substantial output and tool interaction content.
Step 2: Read the usage fields returned by the request
Prioritize the actual usage returned by the API or console, rather than estimating from character counts, conversation turns, or file counts. Token counts can vary significantly across languages, code formats, and context structures.
Step 3: Confirm your account’s group
The same model may have different multipliers in different groups. If the platform offers an “all,” “default,” or combined view, the prices shown on that page may not be the official list prices—they may already reflect a default multiplier.
Step 4: Apply the formula
Multiply each of the four token categories by its unit price to compute the base cost, then apply the group multiplier.
Step 5: Confirm the currency unit of your balance
Some platforms display balance amounts with a dollar sign, but this does not necessarily mean actual dollars are charged to your bank card. If the platform uses a different recharge currency, credits, or another internal unit, follow the platform’s published conversion rules. When comparing platform balances against official USD prices, also account for exchange rates and pricing-unit differences.
8. Common Misconceptions and Optimization Tips
Misconception 1: Treating the default page price as the official price
Combined pages may use a default group multiplier. When checking prices, first switch to the group your current API key or account actually belongs to.
Misconception 2: Estimating cost based only on output
Model output is only one part of the cost. For coding agents, input context, tool results, and cached data may account for a much larger share.
Misconception 3: Assuming cache reads are free
Cache reads are usually cheaper, but not necessarily free, and should still be included in the full formula.
Misconception 4: Assuming automatic failover to another resource pool
In systems with isolated group resources, a model not provided by a group typically returns an “unavailable” error rather than automatically switching to another group. Confirm model availability within your group before use.
Optimization Tips
First, narrow the task scope—avoid asking the agent to scan an entire project in one go. Second, for large projects, provide clear directory descriptions and module boundaries so the system can select context more precisely. Third, control test log output and keep only the error-relevant portions. Finally, reuse stable project descriptions and context for repeated tasks, but periodically clean out stale content to avoid invalid caches or conflicting information.
9. Summary
The technical principle of AI coding agents can be summarized as: the large language model handles understanding and reasoning, the tool system handles reading and execution, the context manager organizes information, the security layer constrains risk, and the feedback loop handles verification and revision.
The cost can be summarized in two steps:
Four token categories × respective official unit prices = base costBase cost × account group multiplier = actual deducted amount
As long as you separately confirm the actual usage, model unit prices, cache billing rules, account group multiplier, and balance currency unit, you can accurately explain the cost of a development task. For individual developers and enterprise teams alike, understanding this mechanism not only helps control budgets, but also improves the agent’s overall efficiency by optimizing context, reducing irrelevant tool output, and refining task decomposition.
