Sub topic 13
Compressing old turns into a summary
A sliding window keeps requests inside the context window, but it throws away everything it drops. If the user told the bot their project name in message 3 and the window has moved on, the bot no longer knows it. Summarization is the next step. Instead of deleting old turns, you ask the model to compress them into a short note and keep that note at the start of the history.
This chapter assumes you have the chat loop, the trim_history function, and a complete(messages) function that sends a message list to a model and returns the reply text. You should be comfortable with Python lists, dictionaries, and exceptions.
What summarization changes
Trimming and summarizing both reduce the number of messages you send. They differ in what survives.
| Approach | What is kept | Extra model call | Main risk |
|---|---|---|---|
| Sliding window | Last N messages, verbatim | No | Early facts vanish completely |
| Summary plus window | Last N messages, plus a short note about everything before | Yes, once per compression | The note can omit or distort details |
The extra call costs time and tokens. For that reason you do not summarize on every turn. You wait until the history is large enough to be worth compressing, then compress many turns at once.
The shape of the history
After compression, the history has three parts, in this order:
- The original system message that sets the bot's behavior.
- A second system message holding the summary.
- The most recent messages, verbatim, starting with a user message.
The summary lives in the history as an ordinary message, so saving it to JSON and loading it again needs no new code. It also survives trim_history, because that function keeps every system message.
Writing the compression function
The function below does the work. It takes the history, the model function, and the number of recent messages to keep verbatim. It returns a new list and leaves the input list unchanged.
SUMMARY_MARKER = "Summary of the earlier conversation:\n"
SUMMARIZER_PROMPT = (
"You compress chat transcripts. Write a short summary that keeps "
"names, decisions, preferences, open questions, and facts the user "
"stated. Do not add anything that is not in the text. "
"Reply with the summary only."
)
def compress_history(history, complete, keep_recent=6):
"""Replace old turns with a model-written summary.
Returns a new list. Raises whatever complete() raises, so the caller
can decide how to fall back.
"""
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
if len(rest) <= keep_recent:
return list(history)
# Start of the verbatim part: move forward until it is a user message.
cut = len(rest) - keep_recent
while cut < len(rest) and rest[cut]["role"] != "user":
cut += 1
old, recent = rest[:cut], rest[cut:]
if not old:
return list(history)
base = [m for m in system if not m["content"].startswith(SUMMARY_MARKER)]
previous = [m for m in system if m["content"].startswith(SUMMARY_MARKER)]
prior_text = previous[0]["content"][len(SUMMARY_MARKER):] if previous else "(none)"
transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old)
request = [
{"role": "system", "content": SUMMARIZER_PROMPT},
{
"role": "user",
"content": (
f"Existing summary:\n{prior_text}\n\n"
f"New messages:\n{transcript}\n\n"
"Write the updated summary."
),
},
]
summary = complete(request).strip()
summary_message = {"role": "system", "content": SUMMARY_MARKER + summary}
return base + [summary_message] + recentSeveral choices in this code are worth explaining.
Recent messages stay verbatim
The last few turns usually contain the thing the user is asking about right now. A summary of them would lose wording the model needs. Keeping them intact also means the reply to the current question is based on exact text.
The cut moves forward to a user message
The loop that advances cut guarantees the verbatim part starts with a user message, the same rule trim_history enforces. Some providers reject a conversation that begins with an assistant message. Moving forward, rather than backward, means you may keep slightly fewer than keep_recent messages. You never split a question from its answer.
The old summary is folded in
Each compression sends the previous summary along with the new old messages, and asks for an updated summary. This is called rolling summarization. The summary stays one note of roughly constant size instead of growing a new paragraph every time.
A marker identifies the summary
The SUMMARY_MARKER prefix lets the function find and replace the earlier summary without a separate data structure. It also means the summary survives a save and load cycle with nothing extra stored.
Deciding when to compress
You need a trigger. The simplest is a message count. A better one is an estimate of tokens, since messages vary in length. A rough estimate is the character count divided by four, which is close enough for English text.
def estimate_tokens(history):
return sum(len(m["content"]) for m in history) // 4
def maybe_compress(history, complete, max_tokens=3000, keep_recent=6):
"""Compress when the history looks too large; otherwise return it as is.
If the summarizing call fails, fall back to the history unchanged.
"""
if estimate_tokens(history) <= max_tokens:
return history
try:
return compress_history(history, complete, keep_recent)
except Exception:
return historySet max_tokens well below the model's real limit, for example half of it. Compression needs room for the transcript you are summarizing, and the reply needs room too. If you wait until you are at the limit, the summarizing request itself may not fit.
Call maybe_compress at the start of each turn, before you append the new user message:
history = maybe_compress(history, complete)
history.append({"role": "user", "content": user_text})
reply = complete(history)Returning the original history on failure is deliberate. A failed summary is not a reason to refuse the user's question. The next turn will try again, and trim_history remains available as a last resort if the history becomes too large.
Testing it with a fake model
The complete parameter makes this function easy to test, as in the earlier testing chapter. The fake model returns a fixed string, and the test checks the structure of the result.
def test_compress_replaces_old_turns_with_summary():
history = [{"role": "system", "content": "Be concise."}]
for i in range(5):
history.append({"role": "user", "content": f"question {i}"})
history.append({"role": "assistant", "content": f"answer {i}"})
fake = lambda messages: "short summary"
result = compress_history(history, fake, keep_recent=4)
assert result[0]["content"] == "Be concise."
assert result[1]["content"] == SUMMARY_MARKER + "short summary"
assert [m["content"] for m in result[2:]] == [
"question 3", "answer 3", "question 4", "answer 4",
]
assert len(history) == 11 # the input list is unchanged
def test_second_compression_replaces_the_first_summary():
history = [
{"role": "system", "content": "Be concise."},
{"role": "system", "content": SUMMARY_MARKER + "old note"},
]
for i in range(4):
history.append({"role": "user", "content": f"q{i}"})
history.append({"role": "assistant", "content": f"a{i}"})
seen = {}
def fake(messages):
seen["prompt"] = messages[-1]["content"]
return "new note"
result = compress_history(history, fake, keep_recent=2)
summaries = [m for m in result if m["content"].startswith(SUMMARY_MARKER)]
assert len(summaries) == 1
assert "old note" in seen["prompt"]
assert summaries[0]["content"].endswith("new note")The second test checks the property that is easiest to break: after two compressions you must still have exactly one summary, and the earlier one must have been given to the model.
Common errors
- Summarizing the summary away. If you filter all system messages into
basewithout separating the summary, you end up with a growing stack of summaries. The marker check prevents this. - Providers that allow one system message. Some APIs accept only a single system message, or require it to come first. If yours does, merge the summary into the first system message's text when building the request, and keep the stored history in the form shown here.
- Summarizing too eagerly. Compressing every few turns costs an extra call each time and loses detail for little benefit. Keep
max_tokenshigh enough that compression is occasional. - Letting the summary grow. A summarizer prompt that does not ask for brevity can produce a note that is itself thousands of tokens. State a target length in the prompt, such as "under 150 words".
Exercises
Exercise
Why does compress_history send the existing summary to the model along with the old messages, instead of summarizing only the old messages and appending a second summary message?
Show answer
Sending the existing summary lets the model produce one updated note, so the summary stays about the same size. Appending a new summary each time would make the history grow by one message per compression, and the earlier summaries would still take space and repeat information. Folding them together also lets the model drop details that are no longer relevant.
Exercise
In maybe_compress, what happens to the user's turn if the summarizing call raises a network error, and why is that the right behavior?
Show answer
The function catches the exception and returns the history unchanged, so the turn continues with the full history. A failed summary should not block the user's question. The history is still valid, and compression is attempted again on the next turn.