Calculate a context budget
Calculate Pi's documented reserve-token threshold and distinguish it from a real compaction run.
The compaction reference pinned to Pi 1.0.4 documents the trigger as
contextTokens > contextWindow - reserveTokens; the default reserve is 16,384.
The Chapter 4 tests use a scripted model with a 100,000-token window. These are
the inputs below: the window is a test model’s capacity, not every provider’s.
Copy the calculation
Save this educational calculation as budget.py and run python budget.py.
It evaluates the documented inequality; it does not call or imitate Pi’s
compaction implementation.
context_window = 100_000
reserve_tokens = 16_384
threshold = context_window - reserve_tokens
print(f"threshold={threshold}")
for context_tokens in (80_000, threshold, 84_000):
headroom = context_window - context_tokens
over_threshold = context_tokens > threshold
print(f"input={context_tokens} headroom={headroom} over_threshold={over_threshold}")Expected outcome
threshold=83616
input=80000 headroom=20000 over_threshold=False
input=83616 headroom=16384 over_threshold=False
input=84000 headroom=16000 over_threshold=TrueThe boundary is strict: equality does not cross the documented threshold. This setting fragment uses that reserve; merge it into your project settings rather than replacing your other settings:
{
"compaction": {
"enabled": true,
"reserveTokens": 16384
}
}What enters a request
| Included context | Effect on the budget |
|---|---|
| System prompt and active tool declarations | Initial request overhead |
| Active branch’s projected messages | Conversation input |
| New tool results | Can increase the next request’s size |
| Compaction summary and retained messages | Replace a summarized span |
The canonical ch04-budget/budget.test.ts checks growing context usage, reserve
thresholds, active-branch history and active tools through a real AgentSession.
It uses a scripted provider and custom summary. This Python calculation is
proposed educational material; its output is arithmetic, not evidence that
an actual session compacted at a particular turn. Token estimates, timing and
provider accounting matter in a live session.
Canonical verification
.
Pinned authority: docs/compaction.md and exported compaction declarations.
Understand this example
Copy this prompt into your AI tool. No code runs here.
Apply this example
Copy this prompt into your AI tool. No code runs here.