Sub topic 9
Maintaining a Rolling Summary Over Time
This chapter assumes you can read 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 seen one-shot summarization of older turns. Here the question is what changes when you summarize repeatedly, as a conversation keeps growing.
What a rolling summary is
A one-shot summary compresses a block of old messages once. A rolling summary (also called an incremental summary) is one string that you update each time more messages age out of the recent window. You never re-read the whole transcript. Each update takes two inputs: the current summary and the batch of messages that just left the window. It produces a new summary.
This keeps the cost of each update roughly constant. The summarizer sees the previous summary plus a bounded batch of old messages, not the full history. The price is that every update rewrites text that an earlier update already rewrote.
The state you maintain
A rolling summary needs two pieces of state, kept next to each other:
summary: a string, empty at the start.history: the verbatim messages that have not been folded in yet.
The system prompt stays outside both. It is pinned and is never summarized. On each request you send the system prompt, then the summary as its own message, then history.
A working implementation
The code below is self-contained. estimate_tokens is the rough four-characters-per-token heuristic, so swap in your model's real tokenizer when exact counts matter. call_model is any function that takes a prompt string and returns text. Here it is a stub, so the example runs without an API key.
SUMMARY_PROMPT = """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 {word_limit} words."""
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def make_capped_summarizer(call_model, max_summary_tokens, word_limit=300):
def summarize(previous_summary, old_messages):
transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old_messages)
words = word_limit
new = previous_summary
for _ in range(3):
prompt = SUMMARY_PROMPT.format(
previous_summary=previous_summary or "(none yet)",
old_messages=transcript,
word_limit=words,
)
new = call_model(prompt).strip()
if estimate_tokens({"content": new}) <= max_summary_tokens:
return new
words //= 2 # ask again with a tighter limit
# Last resort: hard cut. This can end mid-sentence.
return new[: max_summary_tokens * 4]
return summarize
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))
return summarize(summary, old), recent
class RollingMemory:
def __init__(self, system_prompt, trigger_tokens, keep_recent, summarize):
self.system_prompt = system_prompt
self.trigger_tokens = trigger_tokens
self.keep_recent = keep_recent
self.summarize = summarize
self.summary = ""
self.history = []
def add(self, role, content):
self.history.append({"role": role, "content": content})
# If summarize raises, neither field has been reassigned yet,
# so no messages are lost and the next add() retries.
self.summary, self.history = compact(
self.history, self.summary, self.trigger_tokens,
self.keep_recent, self.summarize,
)
def request(self):
messages = [{"role": "system", "content": self.system_prompt}]
if self.summary:
messages.append({
"role": "system",
"content": "Summary of the earlier conversation:\n" + self.summary,
})
return messages + self.history
def stub_model(prompt):
# Stands in for a real model call.
return "User is planning a trip to Lisbon in May. Budget: 1200 EUR."
memory = RollingMemory(
system_prompt="You are a travel assistant.",
trigger_tokens=120,
keep_recent=2,
summarize=make_capped_summarizer(stub_model, max_summary_tokens=80),
)
for i in range(8):
memory.add("user", f"Question {i}: " + "details " * 20)
memory.add("assistant", f"Answer {i}: " + "more details " * 20)
print("summary:", memory.summary)
print("verbatim messages kept:", len(memory.history))
print("request size:", len(memory.request()))The first call that crosses the trigger moves everything except the last two messages into the summary. Later compactions pass the previous summary back in, so old facts survive only if the summarizer chooses to carry them forward.
Where rolling summaries go wrong
A rolling summary has failure modes that a single summary does not.
Compounding loss
Each update paraphrases the previous summary. A detail lost in update 2 cannot come back in update 5, because the summarizer never sees the original message again. Small losses add up. A file path may shrink to "a config file", and then to nothing.
The loss is uneven. Exact values (paths, IDs, amounts, dates) are the first to blur, because paraphrasing treats them as wording rather than data.
Unbounded growth
If the summary prompt does not limit length, each pass tends to add more than it removes. A summary that grows by 50 tokens per update will eventually crowd out the verbatim window it was meant to protect. The word limit in the prompt is a request, and models miss it. That is why the code above checks the length itself and retries with a tighter limit. Always enforce the cap in code.
Drift and stale facts
The user says "budget is 1200 EUR" in turn 4 and "make it 1500" in turn 30. A careless update may keep both numbers, or keep the old one. Tell the summarizer to prefer newer statements and to replace superseded values. Better, give it a place to put them (see below).
Hallucination that persists
If the summarizer invents a detail, the invention is now in the summary. Later updates treat it as established, because they only see the summary. The prompt line "Do not add facts that are not in the conversation" reduces this but does not eliminate it. Rolling summaries make errors durable.
Attribution errors
Summaries often blur who said what. "The assistant recommended option B" and "the user chose option B" are different facts. Ask for attributed statements when the distinction matters.
Reducing the damage
- Use a fixed structure. A free-form paragraph is rewritten wholesale on every pass. A structured summary with sections makes each update an edit instead of a rewrite.
Goals:
- Plan a 5-day trip to Lisbon in May.
Decisions:
- Hotel: Alfama district (chosen turn 12).
Exact values:
- Budget: 1500 EUR (was 1200, updated turn 30)
- Booking reference: LX-4471-B
Open items:
- Compare flight times from Porto.
Preferences:
- No early-morning departures.- Keep exact values out of the paraphrase path. Maintain a separate list of "must-keep" values, such as IDs, paths and amounts. Merge new ones in as code rather than asking the model to rewrite them. Send this list with the summary. It is a form of pinning, and the next chapters build on it.
- Fold in small batches. Compact when you are modestly over the trigger. Large batches force the summarizer to drop more per pass.
- Keep a raw log outside the prompt. Store every message in your database even after it leaves the window. You can then rebuild the summary from the original messages if it goes bad, or run a periodic full re-summary from the raw log. This costs one larger model call and resets the compounded loss.
Cost and latency
Each compaction is an extra model call, and it blocks the next reply if you run it inline. Two options:
- Inline. Compact before sending the user's next request. This is simple, but that turn is slower.
- After the reply. Compact once the assistant has answered, while the user reads and types. The next request finds the state ready. If the user sends a message before the job finishes, use the old state for that request and apply the result later. Be careful to fold in exactly the messages the job saw, not whatever
historyholds when it finishes.
Summarization input is also bounded. It is the previous summary (capped) plus one batch of old messages, so the cost per compaction stays flat however long the conversation runs. A cheaper, faster model is often enough for this step. Test it on your own conversations first, since weaker models drop exact values more often.
Exercise
A conversation has been compacted four times. In turn 3 the user gave the path /srv/app/config.yaml. The latest request asks the assistant to edit "that config file", but the assistant asks which file. Give two causes in the rolling-summary process and two changes that would prevent them.
Show answer
Causes: (1) The path was paraphrased away in an early update, for example to "a config file", and later passes could not restore it because the summarizer never saw the original message again. (2) The summary prompt did not tell the model to preserve exact values, or the length cap forced it to drop them. Changes: (1) Keep a separate must-keep list of exact values (paths, IDs, amounts) that code merges in and sends alongside the summary. (2) Use a structured summary with an "Exact values" section, and keep the raw log so you can rebuild the summary from the original messages.
Exercise
In RollingMemory.add, why is it safe that compact returns new values that are assigned only after summarize finishes? What would break if the code removed messages from self.history before calling summarize?
Show answer
If summarize raises an exception (network error, timeout), the assignment never runs, so self.summary and self.history keep their old values and no messages are lost. The next add() call tries the compaction again. If messages were removed from history first, a failed summarize call would leave them in neither the history nor the summary, and that information would be gone.