Sub topic 13
Compressing old turns into a summary
This chapter assumes you have the chat loop, the trim_history sliding window, and the complete(messages) function from earlier chapters. You should also be comfortable with lists of role-tagged dictionaries.
What trimming loses
A sliding window discards the oldest turns completely. If the user said "my name is Priya and I'm deploying to AWS" in turn 2, the bot forgets it once turn 2 leaves the window.
Summarization keeps the meaning of those turns and drops the wording. You ask the model to compress the old messages into a short note, then replace them with that note. The history stays small, and the facts survive.
Compacting the history
The function below keeps ordinary system messages, folds any earlier summary into the new one, and keeps the last few messages verbatim. It reuses the complete function, so the summary request goes through the same model call as everything else.
SUMMARY_PREFIX = "Summary of the earlier conversation:\n"
SUMMARIZER_PROMPT = (
"You compress conversations. Write a short summary that keeps facts, "
"names, decisions, and open questions. Reply with the summary only."
)
def compact_history(history, complete, keep_recent=6):
base = []
prior = []
for m in history:
if m["role"] != "system":
continue
if m["content"].startswith(SUMMARY_PREFIX):
prior.append(m["content"][len(SUMMARY_PREFIX):])
else:
base.append(m)
rest = [m for m in history if m["role"] != "system"]
cut = len(rest) - keep_recent
while 0 < cut < len(rest) and rest[cut]["role"] != "user":
cut += 1
if cut <= 0 or cut >= len(rest):
return history
old, recent = rest[:cut], rest[cut:]
transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old)
if prior:
transcript = "Earlier summary:\n" + "\n".join(prior) + "\n\n" + transcript
request = [
{"role": "system", "content": SUMMARIZER_PROMPT},
{"role": "user", "content": transcript},
]
try:
summary = complete(request)
except Exception:
return history
return base + [{"role": "system", "content": SUMMARY_PREFIX + summary}] + recent
if __name__ == "__main__":
fake = lambda messages: "User is Priya, deploying to AWS."
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}"})
compacted = compact_history(history, fake, keep_recent=4)
for m in compacted:
print(m["role"], "|", m["content"])Running it prints the original system message, the summary message, and the last four messages, starting with a user message.
Design choices
- The summary is a system message. It is background information, not something the user said. The prefix lets the next compaction find it and merge it instead of stacking summaries.
- The cut moves forward to a user message. This is the same rule
trim_historyuses. The recent part must start with a user turn. - Failure leaves history unchanged. If the summary call raises, you return the original list. The next normal call may fail on size, but you have not lost data.
- Summaries are lossy. Exact numbers, code, and wording can drift. Keep recent turns verbatim and treat the summary as a hint.
When to compact
Check before each model call. A simple trigger is a message count, such as 20. A better one is a rough token estimate, for example total characters divided by four. Compact when you cross the threshold, and compact down to a size well below it. Otherwise you pay for a summary call on nearly every turn.
if len(history) > 20:
history = compact_history(history, complete, keep_recent=6)The summary call costs time and tokens. It also sends the old messages to the model once more, so the call itself must fit in the context window. If you wait too long to compact, the summary request can fail for the same reason you are trying to avoid.
Save the compacted history with save_history. After a restart, the bot then loads the summary and the recent turns, not the full transcript.
Exercise
After two compactions, how many summary messages should the history contain, and why?
Show answer
One. Each compaction finds the previous summary by its prefix, includes it in the text to summarize, and replaces it with a new combined summary. Without that step, summaries would pile up and defeat the purpose of compacting.