Sub topic 10
Choosing when to compact
This chapter assumes you can write basic Python, know the system, user, and assistant message roles, and have a rough idea of what a token is. It also assumes you have read the earlier chapters on token budgets and rolling summaries. Here the question is timing. You already know how to compact a conversation. This chapter covers when to do it.
Why timing matters
Compaction costs something every time it runs. A summary call takes model time and money, and the summary is lossy. Detail that goes into it may not come back out. If you compact too early, you pay that cost and lose detail while you still had plenty of room. If you compact too late, a request can exceed the input limit and fail, or the model can work with a prompt that is almost full.
A good trigger fires late enough to avoid pointless summaries and early enough to leave a safety margin.
The signals you can trigger on
You can decide to compact based on several measurements. Each has trade-offs.
| Trigger | How it works | Strength | Weakness |
|---|---|---|---|
| Token threshold | Compact when estimated tokens pass a limit | Tracks the real constraint | Needs a token estimate |
| Message count | Compact after N messages | Trivial to implement | Messages vary widely in size |
| Fraction of window | Compact at, for example, 75% of the input budget | Scales when you change models | Needs a known budget |
| Time or idle gap | Compact when the user has been away | Hides latency from the user | Does not protect against a sudden large paste |
| Manual | The user or developer asks for it | Full control | Easy to forget, so it needs a fallback |
Token-based triggers are the best default, because the limit you must respect is a token limit. Message counts are a poor proxy. Ten short chat messages cost little, while one pasted log file can cost more than all of them together.
You can combine signals. A common pattern is a token threshold as the main rule, plus a hard message-count cap as a backstop when your token estimate might be wrong.
Setting the threshold below the budget
Recall the input budget: the model's context window, minus the space you reserve for the reply. The compaction trigger should sit below that budget, not at it. Three things need room under the trigger.
- The new user message that is about to arrive. It may be large.
- The summary call itself. If you summarize with the same model, the summarization prompt and the old messages must also fit in the window.
- Estimation error. A heuristic such as four characters per token can be off by a noticeable margin, especially for code, non-English text, or JSON.
A starting point is to trigger at 70 to 80 percent of the input budget. Then adjust using measured data from your own conversations. If your estimate is rough, use a lower fraction.
Here is a small helper that turns a budget into a trigger and a target size.
def compaction_thresholds(max_input_tokens, trigger_fraction=0.75, target_fraction=0.4):
# trigger: start compacting once the prompt reaches this size.
# target: aim to be at or below this size after compacting.
if not 0 < target_fraction < trigger_fraction <= 1:
raise ValueError("need 0 < target_fraction < trigger_fraction <= 1")
trigger = int(max_input_tokens * trigger_fraction)
target = int(max_input_tokens * target_fraction)
return trigger, target
trigger, target = compaction_thresholds(16000)
print(trigger, target) # 12000 6400The gap between the trigger and the target is deliberate. If you compact down to just under the trigger, the very next turn pushes you over it again and you summarize on every message. A lower target gives you several turns of room before the next compaction.
Hysteresis: avoiding compaction on every turn
The pattern above is called hysteresis. You start at one level and stop at a lower one. Without it, a conversation hovering near the threshold compacts constantly. Each compaction folds a tiny amount of text into the summary, and you pay for a model call to do it.
The compact function from the previous chapter keeps a fixed number of recent messages through keep_recent. That is a simple way to create the gap. Compacting down to the last few messages leaves a lot of room. If you want a token-based target, you can choose how many messages to keep by walking backward until you reach the target size.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def choose_keep_recent(history, target_tokens):
# Count how many of the newest messages fit within target_tokens.
used = 0
count = 0
for message in reversed(history):
cost = estimate_tokens(message)
if used + cost > target_tokens:
break
used += cost
count += 1
return count
history = [
{"role": "user", "content": "x" * 400},
{"role": "assistant", "content": "y" * 400},
{"role": "user", "content": "z" * 400},
{"role": "assistant", "content": "w" * 400},
]
print(choose_keep_recent(history, 220)) # 2Each message here costs 104 tokens (400 characters divided by 4, plus 4). Two messages cost 208, which fits under 220, and a third would not. The compact function still moves the start of the recent window forward to a user turn, so the final count can be slightly smaller.
Before or after the model call
You also choose where in the request cycle the check runs.
Check before sending
Run the check just before each request, after adding the new user message. This is the safest option. You know the exact size of what you are about to send, so you never exceed the limit because of an unexpected large message. The cost is latency. When compaction fires, the user waits for the summary call and then the reply call, one after the other.
Check after replying
Run the check after the reply has been delivered, using the updated history. The user does not wait, because the summary is computed while they read the answer. This hides latency, but it has a gap. If the next user message is huge, you still need a pre-send check, because the history was under the threshold at the time of the last check.
Combine both
A practical design uses both.
- After each reply, check the threshold and compact in the background if needed.
- Before each request, verify the prompt fits. If it does not, compact synchronously or fall back to truncation.
The second step is a safety net. It should be rare if the first step works.
Handling concurrent updates
Background compaction creates a race. While the summary is being computed, the user may send another message. The history has changed since the summarizer read it.
The safe approach is to summarize a fixed snapshot of the old messages and then apply the result by replacing only those messages. Anything that arrived in the meantime stays in the recent window.
def apply_compaction(history, old_count, new_summary):
# old_count: how many messages from the front of history were summarized.
# Messages added after the snapshot remain untouched.
remaining = history[old_count:]
return new_summary, remaining
history = [
{"role": "user", "content": "a"},
{"role": "assistant", "content": "b"},
{"role": "user", "content": "c"},
{"role": "assistant", "content": "d"},
]
snapshot_count = 2 # summarizer was given history[:2]
history.append({"role": "user", "content": "e"}) # arrives during summarization
summary, history = apply_compaction(history, snapshot_count, "Summary of a and b")
print(summary)
print([m["content"] for m in history]) # ['c', 'd', 'e']Also make sure two compactions cannot run at once. A simple flag or lock per conversation prevents a second summary from starting on stale data and overwriting the first.
When the summary call fails
Summarization is a model call, and it can fail. It can time out, hit a rate limit, or return an empty string. Your trigger logic should say what happens next.
- Keep the old history and retry on the next turn, if there is still room.
- If there is no room, fall back to sliding-window truncation so the request can still succeed.
- Never replace the history with an empty or very short summary without checking it. A cheap check is that the summary is non-empty and shorter than the text it replaces.
Truncation is the fallback of last resort, because it loses information silently. Log when it happens so you can see how often your summaries fail.
Common errors
- Triggering at the limit. Compacting at 100 percent of the budget leaves no room for the new message or the summary call.
- No gap between trigger and target. The conversation compacts on nearly every turn.
- Counting messages instead of tokens. One large paste breaks the assumption that messages are similar in size.
- Forgetting the summary's own size. The summary and the system prompt count against the budget. Include them in the total, as the
compactfunction does. - Compacting a snapshot that changes. Without a snapshot, a message can be summarized and also kept verbatim, or lost.
- Summarizing short conversations. If the history is small, a summary may be longer than what it replaces. Skip compaction when
len(history) <= keep_recent.
Decision criteria
Use these questions to choose a policy.
- Is latency visible to the user? If yes, prefer background compaction after the reply, with a pre-send check as a safety net.
- Is your token estimate exact? If it comes from the model's real tokenizer, you can trigger closer to the limit. If it is a heuristic, leave a larger margin.
- Do messages vary a lot in size? If yes, use token thresholds, not message counts.
- Is a summary call expensive for you? If yes, use a lower target so each compaction buys more turns.
- Is detail loss costly? If yes, compact later and keep more recent messages, accepting a higher token cost per request.
Exercise
Your input budget is 20,000 tokens. You trigger compaction at 18,000 tokens and compact down to 17,000. Users report slow replies, and logs show a summary call on almost every turn. What is the problem, and what values would you try instead?
Show answer
The gap between the trigger and the target is only 1,000 tokens, so a few normal turns push the prompt back over the trigger. Add hysteresis by lowering the trigger and widening the gap. For example, trigger at 15,000 tokens (75 percent) and compact down to about 8,000 tokens (40 percent). The lower trigger also leaves room for a large new message and for the summary call.
Exercise
A user pastes a large document while the background summary for the previous turns is still running. How do you avoid losing or duplicating messages when the summary finishes?
Show answer
Summarize a snapshot of the old messages and remember how many there were. When the summary finishes, replace only that many messages from the front of the history with the new summary. Messages that arrived during summarization, including the pasted document, stay in the recent window. Also hold a per-conversation lock so a second compaction cannot start from stale data. Because the pasted document may not fit, run the pre-send budget check before the next request.