Sub topic 9
Maintaining a rolling summary over time
This chapter assumes you can call a chat-style LLM API and know the system, user, and assistant roles. It also assumes you can estimate token counts. It builds on sliding-window truncation and on the idea of summarizing older turns with a model.
What a rolling summary is
A rolling summary is one summary string that you update as the conversation grows. You don't summarize the whole history from scratch each time. You give the model the current summary and the newest batch of old messages, and it returns a revised summary.
This keeps each summarization call small. It also keeps the summary at a roughly constant size, because the prompt asks the model to merge new information into the existing text instead of appending to it.
The update prompt
The prompt names what to keep, forbids invented facts, and caps the length. The cap matters. Without it, each update tends to grow, and the summary slowly becomes the history you were trying to remove.
You maintain a running summary of a conversation between a user and an assistant.
Current summary:
{previous_summary}
New messages to fold in:
{old_messages}
Write an updated summary. Keep:
- the user's goals and any decisions made
- names, numbers, file paths, and other exact values the user gave
- open questions and unfinished tasks
- constraints and preferences the user stated
Drop greetings and repeated content. Do not add facts that are not in the conversation. Keep the summary under 300 words.The compaction function
The function below does the work. It reuses estimate_tokens from the truncation chapter. The caller supplies summarize, which wraps the model call and fills in the prompt above.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def compact(history, summary, trigger_tokens, keep_recent, summarize):
# history: messages without the system prompt.
# summary: the current summary string, or "" if none exists yet.
# summarize(previous_summary, old_messages) -> new summary string.
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:])
# Keep the recent window starting on a user turn.
while recent and recent[0]["role"] != "user":
old.append(recent.pop(0))
new_summary = summarize(summary, old)
return new_summary, recentThree details are worth noting:
- The trigger counts the summary as well as the history. A large summary leaves less room for messages.
- The function returns both the new summary and the trimmed history. The caller must store both, or the old messages are lost without being summarized.
- The
whileloop moves a leading assistant message into theoldlist. That way the recent window never begins with an orphaned reply.
Running it over several turns
Here is a stub summarize that shows the data flow without a model call. In real use, replace it with a call that sends the prompt above.
def fake_summarize(previous, old_messages):
folded = " | ".join(m["content"][:20] for m in old_messages)
return (previous + " || " + folded).strip(" |")
history = []
summary = ""
for i in range(1, 9):
history.append({"role": "user", "content": f"question {i} " + "x" * 80})
history.append({"role": "assistant", "content": f"answer {i} " + "y" * 80})
summary, history = compact(history, summary, 200, 4, fake_summarize)
print(i, len(history), len(summary))After the trigger first fires, history stays near four messages. Only summary carries the older content. With a real model, the length cap would also keep summary from growing every turn. The stub has no cap, so its length keeps rising.
Common errors
- Dropping messages without saving the summary. If you discard
history[:-keep_recent]but ignore the return value, the summary never updates. - Summarizing the summary repeatedly. Each pass can blur details. Exact values such as file paths and numbers are the first to degrade, so the prompt asks for them by name.
- A trigger set equal to the hard limit. Compaction needs room for the summary call itself. Set the trigger well below your input budget.
- Blocking the user. A summary call adds latency. Run it after a reply is sent, or in the background, when you can.
Exercise
Your rolling summary keeps growing by about 100 tokens on each compaction, even though the prompt asks for a short summary. Name two changes that would fix this.
Show answer
State an explicit length cap in the prompt, such as "under 300 words", and tell the model to merge new facts into the existing text instead of appending. You can also check the returned summary's token count in code and re-run the summarize call with a stricter limit when it is over budget.
Exercise
In compact, why does the check len(history) <= keep_recent return early even when the token total is over the trigger?
Show answer
There are no older messages to fold in, because every message is in the recent window. Summarizing would produce an empty old list, and the oversized messages would still need to be kept verbatim.