Sub topic 3
Maintaining a Rolling Summary Over Time
Assume you know Python, chat message roles, and approximate token counting. A rolling summary compresses older messages into one shorter record. The application keeps that summary and a recent verbatim window.
Maintaining the Summary
When the conversation reaches a threshold, split the history into older and recent messages. Send the older messages, plus the existing summary, to a summarization step. Replace the old summary with the result.
def compact(history, summary, trigger_tokens, keep_recent, summarize):
total = estimate_tokens({"content": summary}) if summary else 0
total += sum(estimate_tokens(message) for message in history)
if total <= trigger_tokens or len(history) <= keep_recent:
return summary, history
old = history[:-keep_recent]
recent = 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 estimate_tokens(message):
return len(message["content"]) // 4 + 4The summarizer should preserve goals, decisions, exact values, file paths, constraints, and unfinished work. It should remove greetings and repetition. Set a maximum length so the summary does not grow forever.
Choosing When to Compact
Compact before the model rejects the request. Reserve space for the expected reply, tool calls, and token-counting error. For example, if the context limit is 16,000 tokens and a reply may need 2,000, compact when input reaches about 13,000 tokens.
A threshold prevents repeated compaction on every request. Triggering too late risks failure. Triggering too early causes unnecessary summary calls and information loss.
> callout warning > Do not compact in the middle of a tool interaction. Keep each tool call with its matching tool result, and begin the retained window with a user message when possible.
Combining Summary and Recent Messages
Build requests in this order:
- The system prompt.
- The rolling summary, marked as historical context.
- Recent messages unchanged.
Recent turns retain exact wording and details. The summary supplies older decisions that no longer fit in the window.
What Summaries Lose
Summaries can omit a small constraint, change a number, or present an uncertain idea as a decision. They can also preserve an outdated requirement after the user changes it. Treat summaries as compressed data, not authoritative memory.
Testing Compaction
Create conversations containing facts that must survive, such as a name, deadline, file path, and explicit prohibition. Compact them at different points, then ask whether each fact remains available. Compare the model's answers with the original facts. Also test conversations ending in tool calls, corrections, and changed decisions.
When to Use External Memory
Move information out of the prompt when it must survive indefinitely or be searched across conversations. Store durable facts in a database or retrieval system, then fetch only relevant records. Keep the rolling summary for conversation state and use external memory for durable knowledge.
Exercise
Why combine a summary with recent verbatim messages instead of using only one of them?
Show answer
The summary preserves older context cheaply, while recent messages preserve exact wording and the latest corrections.