Sub topic 5
Summarizing older turns
Trimming drops the oldest messages completely. If the user said "My name is Priya" in turn one, a trimmed buffer forgets it once that turn falls out of the budget. Summarizing keeps a compressed version of those turns instead. This chapter assumes you know the token-budgeted trim_messages buffer from the earlier chapters and can call a chat LLM API.
The working model
A summary buffer holds three things:
- A summary: a short text describing everything that has been evicted so far.
- A recent window: the last few messages, kept word for word.
- A budget: the maximum number of tokens that the summary plus the recent window may use.
When the budget is exceeded, the code takes the oldest messages in the window. It sends them, together with the current summary, to an LLM and asks for an updated summary. The old messages are then removed. This is a rolling summary: each pass folds new material into the previous summary instead of starting over.
Implementation
The class below takes the summarizer and the token counter as arguments, so you can test it without an API key. The summary is injected into the system message, which keeps the message list alternating normally between user and assistant roles.
class SummaryBuffer:
def __init__(self, summarize, count_tokens, max_tokens, keep_recent=4):
self.summarize = summarize # (old_summary, old_messages) -> str
self.count_tokens = count_tokens
self.max_tokens = max_tokens
self.keep_recent = keep_recent
self.summary = ""
self.messages = []
def _used(self):
return self.count_tokens(self.summary) + sum(
self.count_tokens(m["content"]) for m in self.messages
)
def add(self, message):
self.messages.append(message)
self._compact()
def _compact(self):
if self._used() <= self.max_tokens:
return
cut = len(self.messages) - self.keep_recent
# Never separate a tool result from the assistant message that requested it.
while cut > 0 and self.messages[cut]["role"] == "tool":
cut -= 1
if cut <= 0:
return
old, self.messages = self.messages[:cut], self.messages[cut:]
self.summary = self.summarize(self.summary, old)
def prompt_messages(self, system_prompt):
system = system_prompt
if self.summary:
system += "\n\nSummary of the earlier conversation:\n" + self.summary
return [{"role": "system", "content": system}] + self.messages
def toy_summarize(old_summary, old_messages):
# Stand-in for an LLM call: keeps the first six words of each old message.
parts = [old_summary] if old_summary else []
for m in old_messages:
parts.append(m["role"] + ": " + " ".join(m["content"].split()[:6]))
return " | ".join(parts)
buf = SummaryBuffer(toy_summarize, lambda t: len(t.split()), max_tokens=25, keep_recent=2)
turns = [
("user", "My name is Priya and I work on a billing service."),
("assistant", "Nice to meet you, Priya. How can I help with billing?"),
("user", "Invoices over 10000 dollars fail validation with error E42."),
("assistant", "E42 usually means a missing tax id on large invoices."),
("user", "What is a context window?"),
]
for role, content in turns:
buf.add({"role": role, "content": content})
for m in buf.prompt_messages("You are a helpful assistant."):
print(m["role"], "->", m["content"])Run it and check three things. The oldest messages are gone from the list. The summary text appears in the system message. The summary is counted in the budget, because _used includes it.
The real summarizer
In production, summarize calls an LLM. The prompt decides most of the quality.
SUMMARY_PROMPT = """You maintain a running summary of a conversation.
Merge the new messages into the existing summary.
Keep: names, numbers, identifiers, decisions, user preferences, open tasks.
Drop: greetings and wording that carries no facts.
Do not add anything that is not in the text. Use at most 120 words.
Existing summary:
{summary}
New messages:
{messages}
Updated summary:"""
def make_summarizer(call_llm):
# call_llm: str -> str, a thin wrapper around your chat API
def summarize(old_summary, old_messages):
text = "\n".join(f"{m['role']}: {m['content']}" for m in old_messages)
return call_llm(
SUMMARY_PROMPT.format(summary=old_summary or "(none)", messages=text)
).strip()
return summarizeUse a low temperature for this call. A smaller, cheaper model is often enough, because the task is compression and not reasoning.
Choosing the trigger and the window
| Choice | Effect of a low value | Effect of a high value |
|---|---|---|
| Token threshold | Frequent summarizer calls, more cost | Long prompts, higher latency per turn |
| `keep_recent` | Less verbatim detail, more reliance on the summary | Fewer tokens left for the summary and retrieved memories |
| Summary length cap | Loses details | Summary grows until it needs summarizing itself |
Set the threshold below the hard context limit. The system prompt, retrieved memories, tool schemas, and the model's reply all need room too. A common rule is to compact at 60 to 70 percent of the window.
Also decide whether to compact by message count or by tokens. Tokens are the more reliable choice, because one pasted log file can outweigh twenty chat turns.
Common errors
- Compounding loss. Each pass summarizes a summary, so details fade like a photocopy of a photocopy. Ask for identifiers and numbers to be kept verbatim. For facts that must survive, write them to long-term memory (a later chapter) as well.
- Hallucinated facts. The summarizer may state something the user never said, and the agent will then treat it as true. The "do not add anything" instruction helps but does not guarantee anything. Spot-check summaries in your logs.
- Splitting tool calls from their results. Many APIs reject a
toolmessage whose matching assistant tool call is missing. Thewhileloop in_compactguards against this. - Forgetting to count the summary. If only raw messages are counted, the prompt creeps past the limit as the summary grows.
- Blocking the user. The summarizer call adds a full LLM round trip. Run it after sending the reply, or in a background task, when latency matters.
- Summarizing large tool outputs. A 5,000-token search result is better truncated or stored elsewhere than carried inside a summary.
- Persisting injected instructions. Text from web pages or emails can say "ignore your rules". If it is summarized, it may become part of the trusted-looking summary. Tell the summarizer to describe such content, not to follow it, and keep the summary in a clearly labeled section.
Trim, summarize, or store?
| Approach | Keeps | Cost | Best for |
|---|---|---|---|
| Trim | Exact recent turns | None | Short chats, tasks where old turns do not matter |
| Summarize | Gist of old turns | One LLM call per compaction | Long single sessions with a continuing thread |
| Long-term memory | Selected facts, across sessions | Writes and retrieval | Preferences and facts needed in future sessions |
These approaches combine well. The summary covers the thread of the current session, and long-term memory covers facts that outlive it.
Exercise
A user pastes a 3,000-token error log in turn 2, and your buffer then compacts. Why might the summary still be a poor place to keep the exact error code, and what two changes would help?
Show answer
Each compaction rewrites the summary, so an exact string such as an error code can be paraphrased or dropped, and the agent cannot tell that it is missing. Two changes: instruct the summarizer to copy identifiers and codes verbatim, and write the code to long-term memory (or keep the raw log in a separate store) so it can be retrieved by similarity when needed.
Exercise
In SummaryBuffer, keep_recent=4 but the last four messages already exceed max_tokens by themselves. What does _compact do, and what problem remains?
Show answer
The cut index is computed as len(messages) - 4, so older messages (if any) are summarized, but the four recent messages stay in the window regardless of size. If nothing is older than the window, cut <= 0 and the method returns without changes. The prompt can still exceed the budget, so you need a second safeguard such as lowering keep_recent dynamically or truncating oversized messages.