How AI Coding Agents Work: The Agent Loop, Context Engineering, and Token Billing Explained
This article breaks down the technical mechanics behind modern AI coding tools: how tool calling turned code completion into task delegation, how the agent loop is structured and guarded, how context is scheduled inside a limited window, how the four token types and prefix caching shape the bill, and how to model and optimize costs when accessing models through a gateway or aggregation platform. You will also find three common billing misreadings and a practical cost-optimization checklist.
1. The Dividing Line: From Code Completion to Task Delegation
Early coding assistance was essentially sequence prediction: given the context around the cursor, continue a few characters or a few lines. It solved the problem of “typing slowly.” What is now commonly called an AI coding tool solves a different problem — “working slowly.” You give it a natural-language requirement, and it reads files, searches the codebase, edits multiple implementations, runs tests, reads the errors, and iterates again.
The technical dividing line of this shift is that tool calling (Tool Calling / Function Calling) went from an optional feature to the main mechanism. The model no longer emits plain text only; it emits structured call intents. A host program running on the user’s machine does the actual execution and feeds the results back to the model. The model decides, the host executes, and together they form a closed loop. Understand that loop and you understand the entire technical skeleton of these tools — and where their cost comes from.
2. Core Mechanism: The Agent Loop
The backbone of any tool in this category can be abstracted into the following pseudocode:
messages = [system_prompt, user_task]while True:resp = model.call(messages, tools=tool_schema)usage += resp.usage # the four token types accumulate hereif resp.tool_calls:messages.append(resp.assistant_message)for call in resp.tool_calls:result = dispatch(call) # read file / search / write file / run commandmessages.append(tool_result(call.id, result))continue # decide again with the new evidenceif task_done(resp) or budget_exceeded(usage):break
Four engineering points in this loop deserve attention:
1) Termination conditions must be multiple. Checking only “the model stopped requesting tools” is not enough. You also need a maximum number of rounds, a maximum token budget, a timeout, and repeated-action detection (the same file being read and written repeatedly with no progress). Without these guardrails, an agent will keep confirming itself on a wrong assumption indefinitely.
2) The tool set design defines the product’s capability boundary. If tools are too coarse (for example, a single “modify the project” tool), the model cannot express intent precisely. If they are too fine (dozens of atomic operations), selection cost rises and misuse becomes likely. The stable set the industry has converged on is roughly: file reading, content search, exact string replacement, command execution, and one controlled sub-task dispatch.
3) Permissions and sandboxing are the security baseline. Command execution and write operations must pass through a confirmation policy, path allowlists, and a version-control precondition check that keeps changes revertible. Any agent capable of writing files and executing commands should default to working in an isolated environment under version control.
4) Observability determines maintainability. Input tokens, output tokens, tool latency, and failed retries for every round should be logged in structured form. This is both the basis for troubleshooting and the raw data for cost accounting.
3. Context Engineering: Scheduling Information Within a Finite Window
The model’s context window is a hard constraint, while a real codebase far exceeds its capacity. Much of the competitive strength of these tools therefore lies in context engineering:
- Layered loading: the system prompt and tool definitions stay resident; project structure and rule files come next; specific files are read on demand, with the model explicitly specifying the range to read.
- Retrieval instead of full ingestion: use keyword/symbol search to locate candidates, then read them closely, rather than pushing the whole repository into the window.
- Compression and summarization: as the threshold approaches, summarize earlier rounds, keeping decisions and conclusions while discarding verbose intermediate output.
- Sub-context isolation: hand large-scale investigation to a sub-task that returns only its conclusion, so the main context is not polluted by noise.
This scheduling directly determines the cost structure: the longer the context, the more input tokens are billed repeatedly each round — which is exactly why caching exists.
4. The Four Token Types and Prompt Caching
The usage information returned with a request typically contains four token types. They have different unit prices, and this is the basis of any bill:
| Token type | Meaning | Relative unit price |
|---|---|---|
| Non-cached input | New context that did not hit the cache | Highest |
| Output | Content generated by the model | Higher than input |
| Cache read | Repeated context that hit the prefix cache | Significantly lower than non-cached input |
| Cache write | Additional overhead from writing to the cache for the first time | Slightly higher than non-cached input |
The benefit of caching comes from “prefix stability”: the system prompt, tool definitions, and long-lived project rules must sit at the very front and remain byte-for-byte unchanged so they can be hit repeatedly. Conversely, putting a timestamp or a randomly ordered file list at the start of the prompt invalidates the cache every round and multiplies the cost. This is purely an engineering habit, yet it is often the single largest source of cost difference.
5. A General Cost Model: List-Price Cost × Group Multiplier
When you access a model through a relay gateway or an aggregation platform, billing can be abstracted into two steps. The first step computes the “list-price cost” of the request from the upstream official rates:
list_price_cost = non_cached_input × input_price+ output × output_price+ cache_read × cache_read_price+ cache_write × cache_write_price
The second step multiplies by the multiplier of the group your access credential belongs to:
credits_deducted = list_price_cost × group_multiplier
The key point: token metering for the same model is identical across groups; the only difference is that final multiplier. The platform sets multipliers dynamically based on channel type, concurrency guarantees, and stability commitments, and they change over time, so confirm the current value on the platform’s model catalog page before use. Enterprise groups commonly use a custom multiplier rather than a fixed one.
Verify with illustrative numbers (unit prices below are illustrative per million tokens, not any real quote): assume input 4, output 20, cache read 0.2, cache write 5. For a round with 100,000 non-cached input tokens, 20,000 output tokens, 800,000 cache-read tokens, and 50,000 cache-write tokens, at a multiplier of 2: list_price_cost = 0.4 + 0.4 + 0.16 + 0.25 = 1.21, and credits deducted = 2.42.
6. Three Frequent Misreadings
First, the default “All” view is not the official list price. When no group is selected, the catalog page usually displays prices at some default multiplier, so the same model appears as a multiple of its official rate. Select the group your credential belongs to before comparing prices.
Second, a platform’s “credit unit” is not a US dollar. Aggregation platforms often credit at a 1:1 ratio with a local currency, so the deducted number corresponds to a local-currency balance, whereas direct official billing settles in real US dollars. Complete the currency and recharge-ratio conversion before comparing the two sides, or the conclusion will be exactly reversed.
Third, the model list inside a group is a subset. A group may cover only some models, and calling a model not included fails outright with an error rather than falling back to another group’s billing. In production, run a capability probe at startup and fix the list of available models.
7. Cost Optimization Checklist
- Stable prefix: keep the system prompt and tool definitions unchanged to maximize cache hits.
- Precise reads: replace whole-file and whole-repository feeding with range reads and symbol search.
- Sub-task isolation: push large-scale investigation into a sub-context and return only conclusions.
- Budget guardrails: set caps on rounds, tokens, and cost; stop and report when exceeded.
- Billing attribution: record the four token types and the multiplier per session to build a verifiable cost ledger.
- Group matching: choose a group based on concurrency and stability needs, not the multiplier number alone.
- Environment isolation: confine write operations to version control and a sandbox so everything stays revertible.
8. Conclusion
The technical principles behind AI coding tools are not mysterious: an agent loop with tools and guardrails, a context scheduling strategy, a layer of prefix caching, and a “list-price cost × group multiplier” metering model. Once these three layers are clear, you can judge both the capability boundaries and the security risks of such a tool, and turn the bill from a black-box deduction into an engineering metric that can be derived, verified, and optimized. To build similar capabilities yourself, you can construct the isolated execution and observability layer on general-purpose container platforms, object storage, log services, and monitoring/alerting, and access model capabilities on demand through compliant cloud service APIs.
