Sub topic 5
Summarizing older turns
This chapter assumes you know the trimming buffer from the previous chapter, can call a chat-style LLM API, and are comfortable with basic Python.
Why trimming alone loses information
Trimming drops the oldest messages once the token budget is full. If the user gave their name or a constraint ten turns ago, trimming deletes it. Summarization is the alternative. Instead of discarding old turns, you replace them with a short text that keeps the important points.
The result is a prompt with three parts: the system message, one summary message, and the most recent turns word for word.
A summarizing buffer
The function below leaves the history alone while it fits. When it does not fit, it summarizes everything except the last keep_recent messages. The summarize argument is any function that takes a list of messages and returns a string.
def compress_history(messages, max_tokens, count_tokens, summarize, keep_recent=2):
total = sum(count_tokens(m["content"]) for m in messages)
if total <= max_tokens:
return messages
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
split = max(len(rest) - keep_recent, 0)
old, recent = rest[:split], rest[split:]
if not old:
return messages
summary = summarize(old)
summary_msg = {
"role": "system",
"content": "Summary of earlier conversation: " + summary,
}
return system + [summary_msg] + recent
# Stand-ins so the example runs without an API key
count = lambda text: len(text.split())
fake_summarize = lambda old: "The user's name is Priya."
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "My name is Priya."},
{"role": "assistant", "content": "Nice to meet you, Priya."},
{"role": "user", "content": "What is a context window?"},
]
print(compress_history(history, 14, count, fake_summarize, keep_recent=1))The output keeps the system message, adds the summary, and keeps only the last user question. The name survives even though the original turns are gone.
Writing the summarizer
In a real agent, summarize calls the model. The prompt matters more than the code around it. Tell the model what to keep:
- Facts about the user, such as names, preferences, and constraints.
- Decisions made and tasks still open.
- Results from tools that later steps depend on.
Ask it to drop greetings and repeated detail, and to stay under a word limit. Use a low temperature so the summary is stable.
Common errors
- Summary larger than the budget saves. A summary costs tokens too. Cap its length, and check the total again after compressing.
- Summarizing on every turn. Each call adds latency and cost. Trigger it only when the history crosses a threshold, for example 80 percent of the budget.
- Summary of a summary. Repeated compression blurs details. Pass the previous summary into the next call as part of the text to update, so the model revises it instead of rewriting it from nothing.
- Invented facts. The model can add details that were never said. Tell it to include only what appears in the conversation.
- Lost exact values. Order numbers, file paths, and code do not survive paraphrasing. Keep these in the recent turns or write them to long-term memory.
Trimming or summarizing
| Approach | Cost | Keeps old facts | Risk |
|---|---|---|---|
| Trimming | None | No | Forgets early details |
| Summarizing | One extra model call | Partly | Drift and invented details |
Exercise
In compresshistory, why is keeprecent used instead of summarizing the whole conversation?
Show answer
The newest turns usually hold the user's current request and the wording the model must answer. Summarizing them would lose exact text and could change the meaning of the question. Keeping them verbatim and summarizing only older turns gives the best balance of detail and token savings.