Sub topic 7
Keeping context small: scoped reads, truncation and compaction
This chapter assumes you know that an agent loop resends its whole context on every turn, and that input tokens are billed each time. You should also be able to read short Python functions. Here you will look at three ways to keep that context small.
Why size matters on every turn
In the earlier loop example, a 5,000-token system prompt and 2,000 tokens added per turn produced 480,000 billed input tokens over 20 turns. The final context was only 45,000 tokens. Any token you add early is billed again on every later turn. A 10,000-token file read on turn 3 is paid for on all of the remaining turns.
You can shrink the context in three places: what enters it, how much of a large result is kept, and what stays once history gets long.
Scoped reads
A scoped read returns only what the step needs. Search first, then read the matching lines. Don't open the whole file.
def read_lines(path, start, end):
"""Return lines start..end (1-based, inclusive) of a text file."""
with open(path, encoding="utf-8") as f:
lines = f.readlines()
return "".join(lines[start - 1:end])Other scoped options are listing a directory instead of reading its files, and running a search that returns file names and line numbers. If the agent gets a tool that reads 40 lines around a match, it will rarely ask for 2,000.
Truncation
Some output cannot be scoped in advance, such as test logs and build output. Cap it before it enters the history. Keep the start and the end, because errors and summaries usually appear there. Say that text was removed so the model knows it can ask for more.
def truncate_output(text, max_chars=4000):
if len(text) <= max_chars:
return text
half = max_chars // 2
omitted = len(text) - 2 * half
return text[:half] + f"\n... [{omitted} characters omitted] ...\n" + text[-half:]
log = "line\n" * 5000
short = truncate_output(log)
print(len(log), len(short)) # 25000 4035Truncation loses information. If the failing line sits in the omitted middle, the agent must re-run the command with a narrower filter. Tell the agent in its instructions that this is expected.
Compaction
Scoping and truncation slow the growth of the context. Compaction shrinks it. When the history passes a threshold, the agent summarizes older turns and replaces them with that summary. The summary should keep decisions made, files changed, open problems, and the next step. It should drop raw tool output.
def should_compact(context_tokens, window_tokens, threshold=0.7):
return context_tokens >= window_tokens * threshold
print(should_compact(150_000, 200_000)) # TrueCompaction has a cost. The summary is produced by a model call, so you pay for one large input. It also changes the start of the prompt, so cached prefixes after that point are lost. Compact too often and you pay more than you save. A summary can also drop a detail the agent needed later.
Measuring the effect
Rerun the earlier loop model with scoped reads that add 500 tokens per turn instead of 2,000:
def loop_input_tokens(system_tokens, step_tokens, turns):
total = 0
context = system_tokens
for _ in range(turns):
total += context
context += step_tokens
return total
print(loop_input_tokens(5_000, 2_000, 20)) # 480000
print(loop_input_tokens(5_000, 500, 20)) # 195000A fourfold cut in per-turn growth cut billed input by about 60%. The saving comes from the growth term, not the starting prompt.
Exercise
A tool returns a 30,000-token test log on turn 2 of a 20-turn loop with no caching. Roughly how many extra input tokens are billed if you keep it in full, compared with truncating it to 1,000 tokens?
Show answer
The log stays in the context for 19 later calls, plus the call right after it is added. Counting from turn 3 through turn 20, that is 18 calls. The difference is 29,000 tokens per call, so about 29,000 × 18 = 522,000 extra input tokens. Truncation prevents most of this cost.