Sub topic 7
Keeping context small: scoped reads, truncation and compaction
Every token in the context is billed again on each turn of an agent loop. This chapter covers three ways to keep the context small: scoped reads, truncation and compaction. It assumes you have read the chapters on input and output pricing, agent loop cost and context growth. It also assumes you can read basic Python.
Why context size is the lever
An earlier chapter showed that a 20-turn loop with a 5,000-token system prompt and 2,000 tokens added per turn bills 480,000 input tokens. The final context is only 45,000 tokens. The cost comes from resending, so any token you keep out of the context is saved on every later turn, not just once.
Three techniques act at different points in the loop:
- Scoped reads limit what enters the context in the first place.
- Truncation limits the size of a result that is already produced.
- Compaction shrinks the history that has already accumulated.
Scoped reads
A scoped read asks for the part of a file or system that matters instead of the whole thing. Reading a 3,000-line file to change one function puts perhaps 30,000 tokens into the context. Those tokens are then resent on every later turn.
Common scoping tools:
- Search first, read second. A
grep -nfor a symbol returns a few lines with line numbers. The agent can then read a range around the match. - Read by line range. Most agent tools accept a start and end line.
- List before reading. A directory listing or a symbol outline costs far less than file contents.
- Narrow commands. Use
git diff --statbefore a fullgit diff. Usepytest -x -qandpytest path::test_nameinstead of a full verbose run.
Here is a minimal line-range reader. It numbers the lines it returns, so the agent can refer to them in later edits.
import os
import tempfile
from itertools import islice
def read_lines(path, start, end):
"""Return lines start..end (1-based, inclusive) with line numbers."""
with open(path, encoding="utf-8") as f:
chunk = islice(f, start - 1, end)
return "".join(f"{n}: {line}" for n, line in enumerate(chunk, start=start))
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "big.txt")
with open(path, "w", encoding="utf-8") as f:
f.writelines(f"line {i}\n" for i in range(1, 3001))
print(read_lines(path, 1500, 1502))
# 1500: line 1500
# 1501: line 1501
# 1502: line 1502islice skips earlier lines without keeping them in memory, so the read stays cheap on large files.
Scoping has a cost in extra turns. If the agent guesses the wrong range, it needs another call. A good habit is to read a little more than the match: the whole function, not the matching line.
Truncation
Some output cannot be scoped in advance. A test run, build log or find command can print thousands of lines. Truncation caps the size of a tool result before it reaches the model.
Keep the beginning and the end. Command output usually has the invocation and first errors at the top, and the summary line and final traceback at the bottom. Cutting the middle loses the least. Always leave a marker that says content was removed and how much. Without one, the model may treat partial output as complete.
def truncate_output(text, max_chars=2000, tail_chars=800):
"""Keep the head and tail of text, replacing the middle with a marker."""
if len(text) <= max_chars:
return text
head_chars = max_chars - tail_chars
omitted = len(text) - max_chars
marker = f"\n[... {omitted} characters omitted ...]\n"
return text[:head_chars] + marker + text[-tail_chars:]
log = "x" * 10_000
out = truncate_output(log)
print("omitted" in out) # True
print(len(out) < len(log)) # TrueThe marker should also tell the agent how to get more, for example "rerun with | grep ERROR" or "read lines 400-500 of build.log". Write the full output to a file and return its path. Then the agent can scope into it later instead of rerunning the command.
Truncation has a failure mode. If the important line is in the middle, the agent sees a clean-looking result and draws the wrong conclusion. Pick caps by output type: tighter for logs and directory listings, looser for source code, where cutting a function in half is harmful.
Compaction
Compaction replaces older history with a short summary when the context passes a threshold. It is the only technique of the three that reduces content the agent has already seen. A typical summary keeps:
- the task and any constraints from the user
- decisions made and why
- files changed, with paths
- the current state of tests
- open questions and next steps
It drops raw tool output, abandoned approaches and repeated file contents.
The simulation below extends the loop cost function from earlier. When the context exceeds limit, it resets to the system prompt plus a summary.
def loop_with_compaction(system_tokens, step_tokens, turns, limit, summary_tokens):
"""Total input tokens billed when history is compacted past a limit."""
total = 0
context = system_tokens
for _ in range(turns):
total += context
context += step_tokens
if context > limit:
context = system_tokens + summary_tokens
return total
print(loop_with_compaction(5_000, 2_000, 20, limit=25_000, summary_tokens=3_000)) # 309000That is 309,000 billed input tokens against 480,000 without compaction, a 36% reduction. The number leaves out the cost of the compaction call itself. That call reads roughly the full context and writes the summary as output tokens. Output tokens carry the higher rate. At 20 turns the saving is clear. In a short session, compaction may cost more than it saves.
Compaction and caching
Compaction interacts with prompt caching. A cached prefix is only read cheaply while it stays byte-identical. Compaction rewrites the history, so the cache for everything after the system prompt is lost. The next turn pays full price for the new summary-based context, then caches it.
- Compact rarely and well past the point where it helps, not on every turn.
- Keep the system prompt and tool definitions first and unchanged, so that part of the prefix survives.
- Avoid inserting timestamps or other changing text early in the context.
Compaction also loses information. A summary that omits a constraint the user stated ten turns ago can lead the agent to undo earlier work. Put user instructions into the summary verbatim where you can.
Choosing between them
| Technique | Acts on | Saves most when | Main risk |
|---|---|---|---|
| Scoped read | Input to the context | Files are large and the target is small | Wrong range, extra turns |
| Truncation | One tool result | Output is verbose and unpredictable | Key line cut from the middle |
| Compaction | Accumulated history | Sessions run many turns | Lost detail, broken cache |
Apply them in that order. Prevention at the source costs nothing per turn. Compaction is a fallback for what gets through.
Common errors
- No marker on truncated output. The model assumes it saw everything.
- Reading whole files "to be safe". One full read of a large file at turn 3 is resent 17 more times in a 20-turn loop.
- Truncating at the wrong end. Keeping only the head of a test log drops the failure summary.
- Compacting on a fixed turn count. Use a token threshold. A turn count ignores how large the context actually is.
- Measuring only the saving. Count the extra turns and the compaction call too. Judge the result by cost per resolved task, not by tokens in one turn.
Exercise
A test command prints 60,000 characters. Assume 4 characters per token. You cap tool output at 2,000 characters, and the capped result stays in the context for the next 10 turns. How many input tokens does the cap avoid across those 10 turns, ignoring the few tokens of the omission marker?
Show answer
Uncapped, the output is about 15,000 tokens (60,000 / 4). Capped, it is about 500 tokens (2,000 / 4). The difference is 14,500 tokens per turn. Over 10 turns that is 145,000 avoided input tokens.
Exercise
In loopwithcompaction, a compaction call reads the full context (about 25,000 tokens) and writes a 3,000-token summary. Using the placeholder prices of 3.0 USD input and 15.0 USD output per million tokens, what does one compaction call cost? Is it small relative to the roughly 171,000 input tokens saved in the example?
Show answer
Input: 25,000 x 3.0 / 1,000,000 = 0.075 USD. Output: 3,000 x 15.0 / 1,000,000 = 0.045 USD. One call costs 0.12 USD. The loop makes one compaction call at turn 11 and another at turn 20, so about 0.24 USD in total. The saved 171,000 input tokens are worth 0.513 USD at the input rate, so compaction still wins, but the margin is smaller than the token counts alone suggest.