The core of a coding agent can be surprisingly small. Give a model a task and a few tools, let it choose an action, return the result, and repeat. A search tool, a file reader, an editor, and a way to run tests can take it a long way.
The control flow can look roughly like this. This is pseudocode; permissions, error handling, and execution limits still need their own implementation:
conversation = [instructions, user_task]
while within_budget():
response = call_model(conversation, tools)
conversation.append(response)
if not response.tool_calls:
break
for call in response.tool_calls:
result = execute_tool(call)
conversation.append(tool_result(call.id, result))
Anthropic’s description of agents uses this same idea: a model choosing tools and responding to feedback in a loop. The simplicity of the loop makes it approachable. It also hides a consequential detail: every iteration gives the model another input, often containing most of the previous one.
Let’s follow one coding task and build an intuition for what that repetition means. It explains how a short tool command can introduce thousands of input tokens, what prefix caching saves, and why a model with a lower output price can still make a task more expensive.
One task, several growing inputs
Suppose we ask the agent to investigate a failing invoice test. The first call contains its instructions, tool definitions, project guidance, and our question. The model requests a file. The application reads it and includes the result in the next call.
Call 1: instructions + tools + project guidance + question
Call 2: previous conversation + read_file call + file contents
Call 3: previous conversation + run_tests call + test output
A tool call such as read_file("invoice.py") is model output. The file contents returned by the application become model input on the next iteration. A short command can bring back a large result. The amount the model writes and the amount tools add to its context are separate quantities.
Consider these illustrative input lengths:
| Model call | Input tokens in this call | Tokens appended since the previous input |
|---|---|---|
| Investigate the failure | 10,000 | 10,000 |
| Examine the file contents | 12,000 | 2,000 |
| Interpret the test output | 15,000 | 3,000 |
| Across the three calls | 37,000 | 15,000 |
The final call has a 15,000-token input. Across the task, however, we have presented 37,000 input tokens because earlier context appears repeatedly. The appended amounts include intervening model messages and tool results.
Without reuse across requests, the server processes each input again. This repeated work is the opportunity for prefix caching.
Reusing the work of reading the prompt
Before a transformer generates an answer, it processes the prompt in a phase called prefill. Attention computes numerical keys and values for token positions at each layer. The serving engine can keep them in a KV cache so generated tokens can use the earlier context without rebuilding all of that state. The PagedAttention post explains this mechanism in more detail.
Prefix caching carries that opportunity across requests. When a new input begins with tokens the model has already processed, compatible cached KV can supply their state. The server then processes the remaining suffix. It still generates a response to the new request. vLLM’s introduction to prefix caching describes this reuse.
Apply that idea to our three calls. Call 1 starts with an empty cache. Each later call finds its earlier input cached and unchanged. To keep the arithmetic simple, count only reuse of previous input prefixes and ignore block rounding:
| Model call | Input length | Reused from cache | Fresh prefill |
|---|---|---|---|
| Call 1 | 10,000 | 0 | 10,000 |
| Call 2 | 12,000 | 10,000 | 2,000 |
| Call 3 | 15,000 | 12,000 | 3,000 |
| Sum across all three calls | 37,000 | 22,000 | 15,000 |
Looking at Call 3 alone, the input contains 15,000 tokens: 12,000 reuse cached state and 3,000 need fresh prefill. After Call 1 has populated the cache, Calls 2 and 3 together require only 5,000 additional tokens of prefill: 2,000 + 3,000.
The totals row includes the initial 10,000-token prefill as well. It counts work across separate calls: 37,000 input-token occurrences, of which 22,000 reuse earlier state. It does not describe a single 37,000-token prompt or 22,000 distinct cached tokens. A runtime may also reuse state computed during an earlier generation; the example leaves that out.
The distinction matters: prefix caching reduces repeated computation. It does not remove the earlier text from the model’s context window, and it does not make all input charges disappear.
Token usage has more than one meaning
When a developer says an agent “used 15,000 tokens,” we need to know which number they mean. It could be the input length of one call, the total input across many calls, or the amount billed at a particular rate.
For an API with separate cache pricing, a token bill can be organized as:
token cost =
ordinary input tokens × ordinary input rate
+ cache-write tokens × cache-write rate
+ cache-read tokens × cache-read rate
+ output tokens × output rate
Use consistent units, such as millions of tokens when prices are per million. Each input token occurrence belongs to one input category in this accounting. If writes have different retention periods and prices, split them into separate terms. Tool-service fees, when applicable, are additional.
For example, Anthropic exposes input_tokens, cache_creation_input_tokens, and cache_read_input_tokens. In that API, input_tokens alone excludes the cached portions; adding all three gives the full input length. Other providers can use different conventions. The usage-field documentation explains that breakdown, and the pricing documentation separates reads, writes, and ordinary input.
This is why I would log usage for every iteration of the agent loop. The final answer does not show how many tokens came back from tools, how often the history was repeated, or how much of it qualified for a cache hit.
Why an identical file can still miss the cache
A familiar cache stores an object under a key. It is tempting to imagine caching each file independently: if invoice.py is unchanged, surely the model can reuse its previous processing.
For ordinary prefix caching, the earlier context is part of that key. The model’s representation of the file depends on the instructions and conversation before it. Change that beginning, and the same file can have different KV state.
vLLM makes the dependency explicit by identifying a block using its tokens and the preceding prefix, along with other relevant inputs such as adapter identity. Its documented full-block scheme reuses complete blocks. The prefix-caching design describes this structure.
In this toy example, appending a tool result preserves 24 matching tokens. Replacing the history preserves eight. Editing the third token leaves only two, even if the later text stays identical. With complete four-token cache blocks, those cases have 24, 8, and 0 tokens eligible for reuse, assuming their state is available.
A changing timestamp near the beginning can therefore have a much larger effect than its token count suggests. Reordering unchanged tool definitions can also change the input prefix. Anthropic’s tool-caching documentation describes how changes to tools affect later cached content in its request hierarchy.
Compaction trades reusable history for a smaller context
Long conversations accumulate failed attempts, old tool results, and details the agent no longer needs. Compaction replaces some of that history with a shorter summary. Anthropic’s context-engineering article describes this technique for long-running tasks.
Before: instructions | tools | original conversation ...
After: instructions | tools | summary | latest message
If the instructions and tools remain unchanged at the beginning, their prefix may still be reusable. The summary introduces different tokens, even when it preserves the meaning of the old conversation. Reuse stops where the inputs diverge.
That makes compaction a tradeoff. It can reduce future input length and remove distracting material, while requiring fresh processing of the replacement summary and what follows it. Keeping obsolete history solely to preserve a cache hit can make the agent worse at its task. I would decide what context the agent needs first, then preserve stable ordering wherever it fits that decision.
A cheaper model can make an iteration more expensive
The same reasoning applies to model routing. Suppose model A has already processed a long conversation. We decide that the next step looks easy, so we send it to lower-priced model B and plan to return to A afterward.
The transcript can be sent to B, but A’s KV state was produced by A’s weights and computation. Ordinary prefix caching does not make that state interchangeable between different models. If B has no compatible cached prefix, it needs to process the context for itself.
Let’s isolate the first switched call with an illustrative rate card. These are hypothetical prices for the calculation, not a current provider quote. Assume both models use the same token counts and complete the task equally well:
| Rate per million tokens | Model A | Model B |
|---|---|---|
| Ordinary input | $5.00 | $3.00 |
| Cache reads | $0.50 | $0.30 |
| Output | $25.00 | $15.00 |
The next call contains 100,000 tokens of existing context, 1,000 new input tokens, and produces 2,000 output tokens. A has the entire old prefix cached; B has none. We retain the existing cache boundary and bill the new suffix as ordinary input, so this particular call has no cache writes. The earlier cost of establishing A’s cache has already been paid in either path.
| Charge for this call | Stay on warm A | Switch to cold B |
|---|---|---|
| Existing 100,000-token context | $0.050 | $0.300 |
| New 1,000-token input | $0.005 | $0.003 |
| 2,000 output tokens | $0.050 | $0.030 |
| Total | $0.105 | $0.333 |
B saves $0.020 on output. Processing the old context costs $0.250 more. The lower output rate loses before we even account for a return to A.
Now shrink the old context to 2,000 tokens, keeping everything else the same. A costs $0.056 and B costs $0.039. Routing wins in that case. The amount of context and its cache state change the result.
Returning to A needs another ledger entry. A’s original prefix may still be cached; switching models does not automatically erase it. But B’s new response and any intervening tool results must become input to A, which needs its own state for the added tokens. How those tokens are billed depends on A’s cache policy and the actual hit. If the old prefix has expired or been evicted, processing it again adds further cost.
This makes “route easy work to a smaller model” a conditional optimization. Sending B a bounded task with only the relevant file or test output may be a better design than handing it the entire session. Passing back a concise result can also limit the context added to A. Both choices need a quality check: a cheaper call is useful only if it performs the work we needed.
What the cache encourages us to build
A useful thought experiment is to give every model call a cold prompt: no prefix reuse between calls, while keeping normal KV reuse during each response. We would feel the cost of resending long histories on every iteration and have a stronger reason to construct a smaller input for each task.
With prefix caching, leaving a large, stable beginning in place can be relatively inexpensive to process again. That encourages append-only conversations. Editing an early instruction, compacting history, or changing models then has a cost that is easy to miss when looking only at the new user message.
The cache is still temporary. A conversation can remain in application storage after the server reclaims its KV blocks. The next request can reconstruct state from the input; a cache miss changes the work required, rather than deleting the conversation. vLLM’s allocation and eviction workflow shows how cached blocks can give way to new requests.
For an agent implementation, I would make a few consequences visible:
- Record full input, cache reads, cache writes, and output separately for each model call.
- Treat tool results as part of the input budget. A one-line command can return pages of text.
- Serialize unchanged instructions, tools, and messages consistently. Put volatile content later where the prompt format and instruction semantics allow it.
- Evaluate routing with the actual context and cache state at the handoff, including the cost of returning results to the original model.
- Compare cost per successfully completed task, including retries, rather than judging the system by the price of one output token.
The agent loop can remain small. What it carries from one iteration to the next is an engineering decision, and prefix caching changes the consequences of that decision.