Sub topic 10
Choosing when to compact
This chapter assumes you have read the earlier chapters on token budgets, sliding windows, and rolling summaries. It also assumes you have the estimate_tokens and compact functions from those chapters. Here you decide when compact should run.
Why timing matters
Compaction costs a model call, adds latency, and loses detail. If you compact too early, you pay that cost and discard detail the model could have kept. If you compact too late, the request exceeds the limit and fails, or the summarization call itself no longer fits.
The trigger needs a threshold, a place in the request cycle to check it, and a target to compact down to.
Set the threshold below the budget
Your input budget is the context window minus the space reserved for the reply. Do not wait until the history reaches the budget. Summarizing also takes input: the old messages, the current summary, and the prompt all go into that call. A common starting point is 70 to 80 percent of the input budget.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def should_compact(history, summary, input_budget, ratio=0.75):
summary_cost = estimate_tokens({"content": summary}) if summary else 0
total = summary_cost + sum(estimate_tokens(m) for m in history)
return total > input_budget * ratio
history = [{"role": "user", "content": "x" * 4000}] * 7
print(should_compact(history, "", input_budget=8000)) # True: about 7,028 > 6,000The estimate is rough, so the margin also absorbs estimation error. The threshold counts tokens and not messages. Ten messages might hold 200 tokens or 20,000.
Choose where to check
Two places work well.
| Timing | How it works | Trade-off |
|---|---|---|
| Before sending a request | Check the history, compact if needed, then call the model | Simple and always safe, but the user waits for the summary call |
| After receiving a reply | Compact in the background while the user reads and types | Hides the latency, but you must handle a new message arriving mid-compaction |
Checking before the request is the safer default. Add the after-reply check when latency matters. In both designs, keep a hard check just before the main call as a safety net.
Compact down to a target, not just under the line
Suppose compaction brings you to 74 percent of the budget, just under a 75 percent trigger. The next message pushes you over, and you compact again. Each pass costs a model call and folds a little more detail into the summary.
Avoid this by leaving a gap between the trigger and the target. Trigger at 75 percent and compact until the total is near 40 to 50 percent. In the compact function, keep_recent controls the target. Pick a value so that the summary plus the recent messages land well below the trigger. Then compaction runs rarely, in larger steps.
Fewer, larger compactions also help with prompt caching. If your provider caches a stable prompt prefix, every change to the summary invalidates that cache. Compacting every turn gives up the cache savings.
Common errors
- Counting messages, not tokens. A message-count trigger fires too early on short chats and too late on long pasted documents.
- Ignoring the summary's own size. The summary is part of the input. Include it in the total, as
should_compactdoes. - No fallback. If the summarization call fails or returns something too long, the request still has to fit. Keep sliding-window truncation as the last resort.
- Compacting a message that is still in flight. In background compaction, take a snapshot of the history first. Merge any messages that arrived during the call into the recent window afterward.
Exercise
Your input budget is 20,000 tokens and the trigger ratio is 0.75. The summary is 600 tokens and the recent history is 14,500 tokens. Should you compact? If you do, why should the target be well below 15,000 tokens?
Show answer
The total is 15,100 tokens, which is above the 15,000 threshold, so compact. The target should be well below the threshold because otherwise a single new message pushes the total over again and triggers another compaction right away. A lower target spaces compactions out, which reduces model calls, information loss, and cache invalidation.