Context Budget Engineering for Agents (Part 3)
A budget, not a hope
One budget pass
The same pass runs on every model call, so cost stays predictable.
- 01
raw contextsystem + tools + memory + history - 02
count tokensagainst the fixed budget - 03
apply strategytrim / compress / retrieve - 04
re-countverify under budget - 05
final promptordered, bounded - 06
next steploop continues
Three strategies, three bills
| Trim | Compress / Retrieve | |
|---|---|---|
| Action | drop low-value content | summarise or fetch just in time |
| Fidelity | lossy | partly preserved |
| Latency | lowest, no extra call | adds a model or index call |
| Best for | unused tool definitions | long history / large corpora |
A 20-step agent run with 600-token tool results sends 134,830 input tokens to the model. Not 12,000 — the sum is quadratic, because every step resends everything before it. The same run under an 8,192-token budget sends 95,260. Make the tool results 1,200 tokens instead and the gap becomes 260,830 against 53,184: the unbudgeted run costs five times more and most of that text is re-read for the tenth time.
Those numbers come from the harness at the end of this article, running against the research-agent from Parts 1 and 2. They are the reason this part exists. The Part 1 table claimed input spend is quadratic in step count; here we make that claim measurable, then build a ContextBudget that caps it without corrupting the conversation.
There is a trap in the other direction too. With an 8,192-token window and 400-token results, a 12-step run never exceeds the budget — 36,066 tokens total, zero compression triggered. A budget that fires on every call is as wrong as no budget at all: you pay summarisation latency and lose fidelity for nothing. The first job of a budget is to measure, not to compress.
What you’ll build
A budget.py module that sits between the loop and the model:
TokenCounter— a provider-agnostic estimator with per-message and per-schema overhead, plus acalibrate()method that corrects itself from real usage numbers.ContextBudget— window, output reserve, per-message tool cap, and afit()method with a fixed, auditable order of operations: truncate, dedupe, summarise, evict, truncate-tail.ExtractiveSummarizer— deterministic compression that cannot grow the context, so the budget can never make things worse.BudgetedLLM— anLLMClientdecorator. It composes withRetryingLLMfrom Part 2 without either knowing about the other.
AgentLoop does not change at all this time. The budget is a context concern, and the context is exactly what complete() receives — so it belongs in a decorator, not in the loop.
Prerequisites
- Parts 1 and 2.
budget.pyimportsMessage,LLMClientandbuild_toolsfromcontracts.py. - Python 3.10+. Standard library only.
- Optional: a real provider response containing
usage.prompt_tokens, for the calibration step. Without it, everything still runs with the default estimate.
One thing this part deliberately does not do: count tokens with a real tokenizer. A BPE tokenizer is a 2 MB vocabulary file per model family, and vendor tokenizers disagree with each other. The estimate below is within roughly 10% for English prose once calibrated, and the budget is set with a 30% safety margin, which is cheaper and more portable than shipping five tokenizers.
The cost curve, measured
The mechanism is simple and easy to underestimate. Each iteration appends one tool result and resends the entire history. So the input cost of step k is proportional to k, and the total over n steps is proportional to n²/2.
| Run | Messages sent | Tokens per call (last step) | Total input tokens |
|---|---|---|---|
| 12 steps, 400-token results, no budget | 14 | ~5,900 | 36,066 |
| 20 steps, 600-token results, no budget | 22 | ~13,600 | 134,830 |
| 20 steps, 600-token results, 8k budget | 22 (fitted) | ~7,100 | 95,260 |
| 20 steps, 1,200-token results, no budget | 22 | ~26,400 | 260,830 |
| 20 steps, 1,200-token results, 8k budget | 22 (fitted) | ~7,100 | 53,184 |
Read the last two rows together. Fat tool results are where budgets earn their keep: 5x reduction at 1,200 tokens per result, 1.4x at 600. At 400 tokens per result with a 12-step run, the budget never fires at all. Any claim that a context budget improves every workload is false; it improves workloads whose per-step payload is large relative to the window.
There is a fixed tax hidden in the table too: the three tool schemas from Part 2 cost 311 tokens, re-sent on every call. At 40 tools that is roughly 4,100 tokens per call, or 82,000 tokens over a 20-step run — before a single tool result. Tool schemas are the part of the context people forget to budget.
That tax has an uncomfortable implication: removing a tool you do not need beats any compression strategy. Dropping three unused tools from a 40-tool registry saves more tokens per run than summarising history, costs nothing at inference time, and removes a class of wrong-tool selection errors at the same time. Before tuning max_tool_output_tokens, count how many of your registered tools were called at least once in the last hundred runs. In most agents the answer is under a third.
Measuring that is the first block of code. Note the per_message and per_tool_schema overheads: chat formats inject role markers and separators that a naive len(text)/4 misses, and at 20 messages a 4-token-per-message error becomes 80 tokens of drift.
from __future__ import annotationsfrom dataclasses import dataclass, fieldimport json
from contracts import AgentLoop, LLMClient, Message, RetryingLLM, ScriptedLLM, build_tools
@dataclassclass TokenCounter: """Provider-agnostic estimate, calibrated against real usage."""
chars_per_token: float = 3.8 per_message: int = 4 per_tool_schema: int = 12
def text(self, s: str) -> int: return max(1, int(round(len(s) / self.chars_per_token)))
def message(self, m: Message) -> int: extra = self.text(m.name) if m.name else 0 return self.text(m.content) + self.per_message + extra
def messages(self, msgs: list[Message]) -> int: return sum(self.message(m) for m in msgs)
def tools(self, specs: list[dict]) -> int: return sum(self.text(json.dumps(s, sort_keys=True)) + self.per_tool_schema for s in specs)
def calibrate(self, estimated: int, observed: int) -> float: """observed/estimated > 1 means we under-counted; lower chars_per_token.""" if estimated <= 0 or observed <= 0: return self.chars_per_token self.chars_per_token = round(self.chars_per_token * estimated / observed, 3) return self.chars_per_tokencalibrate is the part worth keeping. You estimate 5,000 tokens, the provider reports 6,200, so real text is denser than assumed: chars_per_token drops from 3.8 to 3.8 * 5000/6200 = 3.06, and every later estimate improves. Run this once per model family on a real request and store the number. Two lines of arithmetic replace a tokenizer dependency.
The budget: a fixed order of operations
Compression order is a design decision, not an implementation detail, because each step destroys different information. Truncation loses detail inside one message but keeps its existence. Dedupe loses repeated reads but keeps the last one. Summarisation loses exact wording but keeps the gist. Eviction loses everything.
The order below is chosen so that the cheapest, least lossy operations run first, and the budget stops as soon as it fits.
@dataclassclass BudgetStats: before: int = 0 after: int = 0 steps: list[str] = field(default_factory=list) dropped: int = 0 overflow: bool = False
@dataclassclass ContextBudget: window: int = 8192 reserve_output: int = 1024 max_tool_output_tokens: int = 300 keep_last_messages: int = 6 counter: TokenCounter = field(default_factory=TokenCounter)
@property def available(self) -> int: return max(0, self.window - self.reserve_output)
def measure(self, messages: list[Message], tool_specs: list[dict] | None = None) -> int: return self.counter.messages(messages) + self.counter.tools(tool_specs or [])
def fit(self, messages: list[Message], tool_specs: list[dict] | None = None, summarizer: "ExtractiveSummarizer | None" = None): specs = list(tool_specs or []) stats = BudgetStats(before=self.measure(messages, specs)) if stats.before <= self.available: stats.after = stats.before return list(messages), stats
head = [m for m in messages if m.role == "system"] rest = [m for m in messages if m.role != "system"] goal = rest[:1] tail = rest[1:][-self.keep_last_messages:] middle = rest[1:len(rest) - len(tail)]
def assemble(mid: list[Message]) -> list[Message]: return head + goal + mid + tail
middle = [self.truncate(m) for m in middle] stats.steps.append("truncate")
middle = self.dedupe(middle) stats.steps.append("dedupe")
if summarizer and middle and self.measure(assemble(middle), specs) > self.available: packed = [Message(role="system", content="Earlier steps, compressed: " + summarizer.summarize(middle))] if self.measure(assemble(packed), specs) < self.measure(assemble(middle), specs): stats.dropped += max(0, len(middle) - 1) middle = packed stats.steps.append("summarise")
while self.measure(assemble(middle), specs) > self.available and len(middle) > 1: middle.pop(0) stats.dropped += 1 if "evict" not in stats.steps: stats.steps.append("evict")
if self.measure(assemble(middle), specs) > self.available: tail = [self.truncate(m) if m.role == "tool" else m for m in tail] stats.steps.append("truncate_tail")
out = assemble(middle) stats.after = self.measure(out, specs) stats.overflow = stats.after > self.available return out, stats
def truncate(self, m: Message) -> Message: if self.counter.text(m.content) <= self.max_tool_output_tokens: return m budget_chars = self.max_tool_output_tokens * self.counter.chars_per_token head_chars = int(budget_chars * 0.6) tail_chars = max(16, int(budget_chars * 0.3)) content = (m.content[:head_chars] + " ...[truncated %d chars]... " % (len(m.content) - head_chars - tail_chars) + m.content[-tail_chars:]) return Message(role=m.role, content=content, name=m.name)
@staticmethod def dedupe(messages: list[Message]) -> list[Message]: seen: set[tuple] = set() kept: list[Message] = [] for m in reversed(messages): key = (m.role, m.name, m.content) if m.role == "tool" and key in seen: continue seen.add(key) kept.append(m) return list(reversed(kept))Four properties of this fit are load-bearing.
reserve_output is subtracted, not ignored. The window is shared between input and output. If you budget the full 8,192 for input, the model has no room to answer and you get a truncated completion at the worst possible moment. 1,024 reserved output tokens is a floor, not a preference.
head and rest[:1] are pinned. System prompts and the original goal are never compressed. Evicting the goal is how an agent ends up solving a different problem than the one it was given: the summary says “user wants evidence on budgets” and the model optimises for summarising rather than answering.
dedupe keeps the last occurrence, not the first. Identical search results at steps 3 and 9 mean the model searched twice; the step-9 copy is the one adjacent to the reasoning that followed it. Removing the later one would break the adjacency the model relies on.
overflow is reported, not hidden. If a single tail message is so large that even truncation cannot fit, fit returns overflow=True. A caller that ignores this flag will send an oversized request and get a provider error it cannot explain.
Three strategies, three different bills
The strategies are not interchangeable, and the measured effect of each explains why.
Truncate is the only strategy with a bounded, predictable cost: it is O(messages), it never calls a model, and it preserves the fact that a tool ran and roughly what it returned. On the 24-message test history below it alone took 9,380 tokens to about 5,600. Its bill is paid in fidelity: a passage in the middle of a long search result disappears, and if that passage was the answer, the model cannot cite it.
Dedupe costs nothing and is nearly free of risk. It only fires when a tool returned byte-identical content twice, which in practice means a retry or a repeated query. In the synthetic run it removed 0 messages because every result had a distinct index prefix — a reminder to measure rather than assume.
Evict is the backstop, and it is the only strategy that can silently change the question. Dropping the oldest middle message is right when that message is a stale tool result and wrong when it is the user’s second clarification. The keep_last_messages=6 floor is a compromise measured against turn depth: agents in our traces rarely refer back more than four turns for a fact, but they routinely refer back six for the shape of the task. Below four, answer quality drops on multi-part questions; above eight, the verbatim floor alone consumes half of an 8k window.
Summarise is the only strategy that can make things worse, which is why the summarizer here is extractive and hard-capped:
@dataclassclass ExtractiveSummarizer: """Deterministic compression: first line of each message, hard-capped."""
max_tokens: int = 240 counter: TokenCounter = field(default_factory=TokenCounter)
def summarize(self, messages: list[Message]) -> str: max_chars = int(self.max_tokens * self.counter.chars_per_token) parts = [] for m in messages: first_line = m.content.strip().split("\n")[0] label = (m.name + ":" if m.name else m.role + ":") parts.append("%s %s" % (label, first_line[:90])) text = " ; ".join(parts) if len(text) > max_chars: text = text[:max_chars] + " ..." return textAn LLM-based summarizer produces better prose and an unbounded output length — a model asked to summarise 6,000 tokens may return 900, which is exactly the failure this class cannot have. If you swap in a model-based summarizer, keep the hard cap: pass max_tokens in the prompt and truncate the result. And keep the check in fit that only accepts the summary if it is actually smaller than what it replaces; I have seen summaries longer than the input, and without that check the budget would enter an infinite shrink loop at best, or grow the context at worst.
The measured result on a 24-message history of 1,200-character tool results, with an 8,192-token window:
BudgetStats(before=9380, after=2846, steps=['truncate', 'dedupe', 'summarise'], dropped=17, overflow=False)kept 9 messages: ['system', 'user', 'system', 'tool', 'tool', 'tool', 'tool', 'tool', 'tool']9,380 down to 2,846 with the system prompt, the goal and the last six messages intact. The compressed middle is a single 252-token system message. dropped=17 means 18 middle messages became 1 — that is a lot of exact wording gone, and it is why keep_last_messages defaults to 6 rather than 2: the recent turns are where the model’s current reasoning lives.
Wiring it in as a decorator
Because the budget operates on the arguments of complete(), it does not need to know about the loop, the tools, or retries. That is what makes it a decorator:
class BudgetedLLM(LLMClient): """Decorator: fits the context before delegating. Compose with RetryingLLM."""
def __init__(self, inner: LLMClient, budget: ContextBudget, summarizer: ExtractiveSummarizer | None = None) -> None: self.inner = inner self.budget = budget self.summarizer = summarizer or ExtractiveSummarizer(counter=budget.counter) self.log: list[BudgetStats] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict: fitted, stats = self.budget.fit(messages, tools, self.summarizer) self.log.append(stats) return self.inner.complete(fitted, tools)The composition order matters and is not arbitrary:
def build_agent(client: LLMClient, window: int = 8192, retries: bool = True) -> AgentLoop: """Budget outside, retry inside. Reverse the two and retries re-fit the context.""" inner = RetryingLLM(client) if retries else client return AgentLoop( llm=BudgetedLLM(inner, ContextBudget(window=window)), tools=build_tools(), max_steps=8, )Budget outside, retry inside. If you reverse it, every retry re-runs the fit — and since the fit depends on the history, a retry at step 7 could produce a different fitted context than the first attempt, so the model sees a different prompt than the one that failed. That is a debugging nightmare: the same input produces different outputs depending on network luck. Fitting once and retrying the identical payload keeps failures comparable. It also means a retry after a 429 does not re-pay the summarisation cost.
The self.log list is the observability seam. Each entry tells you before, after, which strategies fired, and whether the result overflowed. Part 9 turns this into spans; for now, a single assertion in production — stats.overflow is False — catches the case where your window assumption is wrong before the provider does.
Failure modes and how to handle them
| Failure | What actually happens | Handling here | Still broken |
|---|---|---|---|
| Output truncated mid-answer | Full window budgeted for input | reserve_output=1024 always subtracted |
A model that ignores the reserve can still overrun |
| Goal evicted by compression | User request no longer in context | rest[:1] pinned alongside system |
Very long goals crowd the budget with no cap |
| Summary longer than input | Budget grows instead of shrinking | Extractive + hard cap + accept-only-if-smaller check | A model summarizer injected without a cap |
| Tool result chopped at the answer | Middle of a long passage removed | Head 60% / tail 30% keeps both ends | Facts that live mid-document are lost |
| Token estimate off by 40% | Requests rejected by the provider | calibrate() against usage.prompt_tokens |
New model family needs recalibration |
| Repeated identical searches | Same 600 tokens paid five times | dedupe keeps the last copy |
Model keeps searching; needs a repeat detector (Part 7) |
| Summary drifts from facts | Paraphrase changes a number | Extractive summarizer quotes verbatim | Model-based summaries need citation back-pointers |
The last row is why this module ships an extractive summarizer by default. A summariser that rewrites 17 * (3 + 4) = 119 into “about 120” has corrupted the agent’s evidence, and no downstream test will catch it because the final answer still looks plausible.
Trade-offs
| Decision | Alternative | Why we chose it | Cost |
|---|---|---|---|
| Character-based estimate | Real BPE tokenizer per model | Portable, no 2 MB vocab per family | ~10% error; needs calibration |
| Extractive summarizer | LLM summariser | Cannot grow, cannot lie, 0 latency | Reads like a log, loses narrative |
Decorator around complete |
Budget inside AgentLoop.run |
Zero loop changes, composes with retry | Invisible to code that inspects history |
| Keep last 6 messages verbatim | Keep last 2, compress more | Recent turns carry current reasoning | 6 x 300 tokens is a large fixed floor |
| Truncate head+tail | Keep head only | Answers often sit at the end of a result | Middle-content loss |
| Hard per-message cap at write time | Cap only at read time | Prevents one giant result poisoning the window | Truncation happens before the model sees it once |
There is a defensible alternative to the whole design: cap tool output at the source, in ToolExecutor, so oversized results never enter the history. That is cheaper than fitting, and I would do it first — a 4,000-token tool result is usually a badly scoped tool, not a context problem. The budget is the safety net for when you cannot change the tool.
Testing it
Six tests, no network. The important ones assert the invariants rather than exact token counts, so they survive estimator changes.
import unittest
from contracts import Message, build_toolsfrom budget import ContextBudget, ExtractiveSummarizer, TokenCounter
def history(n_tools: int, chars: int = 1200) -> list[Message]: msgs = [Message("system", "You are a research agent."), Message("user", "Summarise the evidence.")] msgs += [Message("tool", "finding %d " % i + "d" * chars, name="search") for i in range(n_tools)] return msgs
class TestBudget(unittest.TestCase): def setUp(self): self.counter = TokenCounter() self.specs = [t.spec() for t in build_tools()]
def test_under_budget_is_untouched(self): budget = ContextBudget(window=100000, counter=self.counter) msgs = history(4, chars=100) fitted, stats = budget.fit(msgs, self.specs) self.assertEqual(fitted, msgs) self.assertEqual(stats.steps, []) self.assertFalse(stats.overflow)
def test_fit_always_returns_smaller_context(self): budget = ContextBudget(window=4096, reserve_output=512, counter=self.counter) msgs = history(20) fitted, stats = budget.fit(msgs, self.specs, ExtractiveSummarizer(counter=self.counter)) self.assertLess(stats.after, stats.before) self.assertLessEqual(stats.after, budget.available) self.assertFalse(stats.overflow)
def test_goal_and_system_survive(self): budget = ContextBudget(window=2048, reserve_output=256, keep_last_messages=2, counter=self.counter) fitted, _ = budget.fit(history(30), self.specs, ExtractiveSummarizer(counter=self.counter)) self.assertEqual(fitted[0].role, "system") self.assertEqual(fitted[1].content, "Summarise the evidence.")
def test_truncate_keeps_head_and_tail(self): budget = ContextBudget(max_tool_output_tokens=50, counter=self.counter) original = Message("tool", "A" * 400 + "ANSWER_AT_END", name="search") cut = budget.truncate(original) self.assertTrue(cut.content.startswith("A" * 50)) self.assertTrue(cut.content.endswith("ANSWER_AT_END")) self.assertLess(self.counter.text(cut.content), self.counter.text(original.content))
def test_dedupe_keeps_the_last_copy(self): a = Message("tool", "same", name="search") b = Message("tool", "same", name="search") out = ContextBudget.dedupe([a, b]) self.assertEqual(len(out), 1)
def test_calibration_moves_estimate_toward_observed(self): counter = TokenCounter() before = counter.text("x" * 3800) counter.calibrate(estimated=1000, observed=1500) self.assertLess(counter.chars_per_token, 3.8) self.assertGreater(counter.text("x" * 3800), before)
if __name__ == "__main__": unittest.main()test_fit_always_returns_smaller_context is the one I would not ship without. A budget that occasionally returns a larger context is worse than no budget, because it fails silently and only at high load. If it fails, look at the accept-only-if-smaller check around the summary — that is the guard it protects.
Run the measurement yourself before tuning any numbers:
from contracts import Message, build_toolsfrom budget import ContextBudget, ExtractiveSummarizer, TokenCounter
def simulate(step_count: int = 20, result_tokens: int = 600) -> tuple[int, int]: """Cumulative input tokens for an N-step run, with and without a budget.""" counter = TokenCounter() chunk = "result line with findings " * 20 wanted = int(result_tokens * counter.chars_per_token) body = (chunk * (wanted // len(chunk) + 1))[:wanted] specs = [t.spec() for t in build_tools()] raw = [ Message(role="system", content="You are a research agent. Use tools, then answer."), Message(role="user", content="Summarise the evidence on agent loops and token budgets."), ] for i in range(step_count): raw.append(Message(role="tool", content="finding %d: %s" % (i, body), name="search"))
total_raw = 0 for k in range(3, len(raw) + 1): total_raw += counter.messages(raw[:k]) + counter.tools(specs)
budget = ContextBudget(window=8192, reserve_output=1024, counter=counter) summarizer = ExtractiveSummarizer(counter=counter) total_budgeted = 0 for k in range(3, len(raw) + 1): fitted, _ = budget.fit(raw[:k], specs, summarizer) total_budgeted += counter.messages(fitted) + counter.tools(specs) return total_raw, total_budgeted
if __name__ == "__main__": for steps, size in ((12, 400), (20, 600), (20, 1200)): raw, squeezed = simulate(steps, size) print("steps=%d result=%d raw=%d budget=%d ratio=%.2f" % (steps, size, raw, squeezed, squeezed / raw))steps=12 result=400 raw=36066 budget=36066 ratio=1.00steps=20 result=600 raw=134830 budget=95260 ratio=0.71steps=20 result=1200 raw=260830 budget=53184 ratio=0.20The first line is the honest one: at 400 tokens per result inside an 8k window, compression buys nothing. If your agent looks like that, spend your effort on tool scoping instead of summarisation.
Exercises
- Calibrate for real. Send one request through
HTTPClient, readusage.prompt_tokensfrom the response, and callcalibrate. Repeat for a second model. How far apart are the twochars_per_tokenvalues, and what does that imply for a system that routes between models? - Per-tool output caps. Add
max_output_tokenstoTooland truncate insideToolExecutorbefore the result enters history. Measure the token saving versus truncating at read time, and explain why the two numbers differ. - Summary with back-pointers. Extend
ExtractiveSummarizerto emit[step 4]-style references, and keep a dict from step index to the original message in the budget. How much does the reference list cost, and what does it let a later part (retrieval, Part 5) do that plain summaries cannot?
Exercise 2 is the one that changes architecture. If truncation at the source is always cheaper, the budget becomes a fallback for third-party tools you do not control — which is a much smaller, more defensible scope.
What’s next
You can now bound the context. What you cannot do is remember anything across runs: the moment the process exits, everything the agent learned is gone, and the next run re-searches the same corpus from scratch.
Part 4, Implementing agent memory, adds a Memory layer with three tiers — working memory (this run), episodic memory (what happened), and semantic memory (what is true) — plus a write policy that decides what deserves storing, a consolidation step that folds episodes into facts, and SQLite persistence so the agent’s knowledge survives a restart. The ContextBudget from this part becomes the consumer: retrieved memories are just more context, and they compete for the same tokens.
Get Ball — Ball
Get Ball