Sub topic 11
Combining a Summary with Recent Verbatim Messages
This chapter assumes you know Python, chat message roles, and the sliding-window and rolling-summary ideas from earlier chapters. Here you will combine them into one strategy.
Why combine the two
Each approach fails in a different way on its own.
- A sliding window keeps exact wording, but it forgets everything outside the window.
- A summary remembers the whole conversation, but it loses detail and can contain mistakes.
The hybrid strategy uses each where it is strongest. Old turns become a short summary. The newest turns stay word for word, because the next reply usually depends on them most. The model sees the exact text of "what did I just say?" and a compressed memory of everything before it.
The request layout
Every request has three parts in a fixed order: the system prompt, the summary, and the recent messages.
The build_request function assembles this layout:
def build_request(system_prompt, summary, recent):
messages = [{"role": "system", "content": system_prompt}]
if summary:
messages.append({
"role": "system",
"content": "Summary of the earlier conversation:\n" + summary,
})
messages.extend(recent)
return messagesThe summary gets its own labeled message. That keeps the model from treating it as something the user said. It also keeps the system prompt unchanged, so you can pin it exactly as before.
Running the compaction step
The compact function checks whether the history has outgrown a threshold. If so, it folds the older messages into the summary and keeps only the newest ones.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def compact(history, summary, trigger_tokens, keep_recent, summarize):
summary_cost = estimate_tokens({"content": summary}) if summary else 0
total = summary_cost + sum(estimate_tokens(m) for m in history)
if total <= trigger_tokens or len(history) <= keep_recent:
return summary, history
old = list(history[:-keep_recent])
recent = list(history[-keep_recent:])
while recent and recent[0]["role"] != "user":
old.append(recent.pop(0))
new_summary = summarize(summary, old)
return new_summary, recent
def fake_summarize(previous, old):
return (previous + " " if previous else "") + f"[{len(old)} messages folded in]"
history = [
{"role": "user" if i % 2 == 0 else "assistant", "content": "x" * 200}
for i in range(10)
]
summary, history = compact(history, "", 300, 4, fake_summarize)
print(summary, len(history))This prints [6 messages folded in] 4. In production, summarize makes a model call with the prompt from the summarization chapter.
Two details matter here.
- The trigger counts the summary as well as the history. Otherwise a growing summary would slowly crowd out the budget.
- The
whileloop moves a leading assistant message out of the recent window and into the text to be summarized. The window then starts on a user turn, and no reply loses its question.
Choosing the numbers
Tune two values together.
| Setting | Too low | Too high |
|---|---|---|
| `keep_recent` | The model loses the immediate context | Compaction runs rarely but removes little |
| `trigger_tokens` | You pay for summaries too often | You risk hitting the limit |
A reasonable start is a trigger at about 70 percent of the input budget. Keep enough recent messages to cover the last few exchanges. Then test with real conversations.
Common errors
- Sending the summary as a user message. The model may answer it as a question.
- Summarizing the recent window as well. The summary then repeats what the verbatim messages already say, which wastes tokens.
- Forgetting to store the new summary. If you keep only
history, the folded messages are lost for good. - Splitting a tool call from its result when choosing the cut point. Treat the pair as one unit.
Exercise
Your app compacts when the history reaches 8,000 tokens, but the model's input limit is 8,200 tokens. Requests sometimes fail right when compaction runs. What is wrong, and what is the fix?
Show answer
The trigger sits too close to the limit. The prompt can exceed the limit before compaction finishes, and the summary adds tokens of its own. Lower the trigger to leave headroom, for example about 70 percent of the budget, and keep room for the reply.