Sub topic 5
Where the Context Grows: Tool Output, File Reads and History
This chapter assumes you have read the earlier chapters on tokens, the context window, input and output pricing, and the cost structure of an agent loop. You should be comfortable reading short Python programs and JSON. Here we look at what actually fills the context of a coding agent, so you can predict growth and spot the largest contributors before they show up on a bill.
The context is an append-only log
A coding agent calls the model in a loop. Each call sends the full conversation so far: the system prompt, tool definitions, the user's request, and every earlier assistant message, tool call and tool result. Nothing leaves the context unless the agent deliberately removes or summarizes it.
This means the context only ever grows by appending. Every item you add is paid for again on every later turn, as input tokens. An item added on turn 3 of a 20-turn session is billed 18 times.
The previous chapter showed the total for a loop with fixed-size steps. This chapter asks a different question: what are the steps made of, and which parts are large?
The sources of growth
Context in a coding session comes from five places. They differ a lot in size and in how predictable they are.
| Source | Typical size | Predictable? | Notes |
|---|---|---|---|
| System prompt and tool definitions | 2,000 to 10,000 tokens | Yes | Fixed per session. Grows with the number of tools. |
| User messages | 50 to 1,000 tokens | Mostly | Pasted logs or stack traces can be much larger. |
| Assistant messages and tool calls | 100 to 1,500 tokens | Mostly | Includes the arguments of each call, such as a file edit. |
| Tool results | 100 to 50,000+ tokens | No | The main source of surprises. |
| Reasoning content kept in history | 0 to several thousand tokens per turn | Depends on provider | Some providers drop earlier reasoning, others keep it. |
The sizes are rough and vary by tool set and model. The point is the spread. Tool results span more than two orders of magnitude, so they dominate the variance.
Tool results
Every tool result goes into the context in full unless the agent or its harness limits it. Common large results:
- File reads. Reading a 1,200-line source file can cost 10,000 to 15,000 tokens. The agent often needs 40 lines of it.
- Search output. A broad
grepover a repository can return hundreds of matching lines, including generated files and vendored dependencies. - Command output. A test run can print thousands of lines. Build logs, package installs and verbose linters are similar.
- Directory listings. A recursive listing that includes
node_modulesor a build directory is large and mostly useless. - Diffs. A large diff after an edit may be returned to the agent, which already knows what it wrote.
A useful habit is to ask of any tool: what is the worst-case output size, and who limits it? If nobody does, the tool can add 100,000 tokens in one call.
Repeated reads
Agents often read the same file more than once. They read it to understand it, edit it, and then read it again to check the edit. Each read appends another full copy. The older copy is now stale, since the file has changed, but it stays in the context and keeps being billed.
Repeated reads cost twice: the tokens themselves, and the risk that the model gets confused by two versions of one file.
History
History is the sum of everything else that has accumulated. Even when each message is small, 60 turns of short messages add up. History also contains dead ends: an approach the agent tried, abandoned and replaced. Those tokens still ride along on every later turn.
Long sessions have a second problem beyond cost. As the context fills, the model has more irrelevant material to ignore, and the session approaches the context window limit, where the harness must compact or stop.
Modeling growth from its parts
The earlier loop function used one fixed step_tokens value. Real steps are uneven, so a better model takes a list of per-step sizes. The following code computes the billed input tokens and the final context size for a session with a few large tool results.
def session_input_tokens(system_tokens, step_sizes):
"""Return (total billed input tokens, final context size).
step_sizes is a list with the tokens added by each turn
(assistant message, tool call and tool result together).
No caching is applied.
"""
total = 0
context = system_tokens
for added in step_sizes:
total += context # the whole context is sent on this turn
context += added
return total, context
# A 10-turn session. Two turns read large files, one runs a noisy test suite.
steps = [800, 12_000, 600, 700, 14_000, 500, 900, 25_000, 600, 700]
total, final = session_input_tokens(5_000, steps)
print(total, final) # 285400 60800The final context is 60,800 tokens, but 285,400 input tokens are billed. Now compare the same session if the three large results had been limited to 2,000 tokens each.
def session_input_tokens(system_tokens, step_sizes):
total = 0
context = system_tokens
for added in step_sizes:
total += context
context += added
return total, context
original = [800, 12_000, 600, 700, 14_000, 500, 900, 25_000, 600, 700]
capped = [min(s, 2_000) for s in original]
print(session_input_tokens(5_000, original)) # (285400, 60800)
print(session_input_tokens(5_000, capped)) # (110000, 18800)Capping the three large results reduces billed input from 285,400 to 110,000 tokens, a drop of about 61 percent. Notice that the biggest saving comes from the early large results. A big read on turn 2 is paid for on 8 later turns. A big result on turn 9 is paid for on only 1.
When in the session the tokens arrive
The cost of a block of tokens is its size times the number of turns remaining after it arrives. Early large reads are therefore the most expensive.
def carrying_cost(size, turn_added, total_turns):
"""Input tokens billed for one block of context.
Turns are numbered from 1. A block added on turn t is first sent on turn t + 1.
"""
return size * (total_turns - turn_added)
# The same 10,000-token file read, added at different points in a 20-turn session.
for turn in (2, 10, 19):
print(turn, carrying_cost(10_000, turn, 20))
# 2 180000
# 10 100000
# 19 10000This gives a practical rule: read broadly and cheaply early, then read narrowly. Any step that finds the right file, such as a search for a function name, should return a small result. Opening the whole file belongs after that, and only the relevant range should be read.
Measuring where your context goes
You do not need to guess. Most harnesses can log the messages they send. If you have the message list as JSON, you can attribute tokens to each source. Exact counts require the provider's tokenizer, but a characters-per-token estimate is enough to find the largest contributors.
import json
from collections import Counter
def estimate_tokens(text):
# Rough rule for English and code: about 4 characters per token.
# Replace with the provider's token counter for exact numbers.
return max(1, len(text) // 4)
def tokens_by_role(messages):
"""Sum estimated tokens by message role, e.g. user, assistant, tool."""
totals = Counter()
for message in messages:
content = message["content"]
text = content if isinstance(content, str) else json.dumps(content)
totals[message["role"]] += estimate_tokens(text)
return totals
messages = [
{"role": "system", "content": "You are a coding agent. " * 100},
{"role": "user", "content": "Fix the failing test in billing."},
{"role": "assistant", "content": "I will run the tests."},
{"role": "tool", "content": "FAILED test_invoice " + "traceback line\n" * 2000},
{"role": "assistant", "content": "The bug is in invoice.py."},
]
for role, count in tokens_by_role(messages).most_common():
print(role, count)
# tool 7504
# system 600
# user 8
# assistant 5
# assistant ... (combined into one total: 10 for the two assistant messages)Run it yourself before relying on the comment at the end. The exact output is a single line per role, with assistant showing the combined total of its two messages. The shape of the result is what matters: one tool result outweighs everything else by an order of magnitude.
Once you have a breakdown like this from real sessions, sort tool results by size and look at the top ten. They usually come from two or three tools or commands, and fixing those gives most of the benefit.
Edge cases and common mistakes
- Counting only the final context. A final context of 60,000 tokens can correspond to hundreds of thousands of billed tokens. Always compute the sum over turns.
- Assuming a read is free after the first time. Without caching, each turn resends everything. Caching reduces the price of resending, but the tokens are still in the context and still count against the window.
- Truncating from the wrong end. For command output, the useful part is often the end, such as the failing assertion and summary line. For logs, the first error is often what matters. A blind "keep the first N characters" rule can cut off the answer. Keep both the head and the tail where possible.
- Letting pasted content bypass limits. Limits on tool output do not apply to what a user pastes into a message.
- Ignoring tool definitions. Each additional tool adds its description and schema to every request. Dozens of tools can add thousands of tokens to every turn before any work happens.
- Stale copies. After an edit, the pre-edit file contents remain. A model can quote the old version. Prefer returning only the changed range after an edit.
- Parallel tool calls. When the model requests several reads in one turn, all results arrive together. Three 10,000-token files add 30,000 tokens at once.
Summary of what drives growth
- The context is append-only, so every token is billed on every later turn.
- Tool results are the largest and least predictable source, especially file reads, searches and command output.
- Early large results cost the most, because they are carried for the most turns.
- Repeated reads and abandoned approaches add tokens that carry no new information.
- You find the real contributors by logging messages and sorting by size, not by guessing.
Exercise
A 25-turn session starts with a 4,000-token system prompt. On turn 3, the agent reads a file that adds 16,000 tokens to the context. On turn 20, it reads another file of the same size. Using the rule that a block added on turn t is billed on every turn after t, how many input tokens does each read cost in total, and why do they differ?
Show answer
The turn 3 read is billed on turns 4 through 25, which is 22 turns, so it costs 16,000 × 22 = 352,000 input tokens. The turn 20 read is billed on turns 21 through 25, which is 5 turns, so it costs 16,000 × 5 = 80,000 input tokens. The blocks are the same size, but the earlier one is carried for more turns. This is why you should keep early tool results small, and why a narrow read after a search is cheaper than reading a whole file first.
Exercise
Your agent's test command prints 3,000 lines. You want to limit the output that goes into the context. Why is keeping only the first 200 lines a poor policy, and what would you do instead?
Show answer
Test runners usually print the failures and the summary at the end, so keeping only the first 200 lines can drop the information the agent needs. A better policy keeps both the head and the tail, for example the first 50 lines and the last 150, and marks the omitted middle with a note giving the number of lines removed. Even better, run the tests in a mode that prints only failures, or filter the output for failing test names before it reaches the context.