Sub topic 11
Combining a Summary with Recent Verbatim Messages
This chapter covers the hybrid strategy: a rolling summary of older turns followed by the most recent messages kept word for word. It assumes you can write basic Python, know the system, user, and assistant message roles, and have a rough idea of what tokens are. It also assumes you have seen sliding-window truncation and rolling summaries from earlier chapters. Here you combine them.
Why combine the two approaches
Each approach alone has a weakness.
- A sliding window keeps exact wording, but anything that falls off the front is gone. If the user gave a file path in message 3 and the window now starts at message 40, the model cannot see it.
- A summary keeps the gist of the whole conversation, but it is lossy. It can drop exact values, and the model cannot quote what the user actually said.
The hybrid strategy uses each where it is strong. Recent turns are the ones the model most likely needs word for word, so they stay verbatim. Older turns are less likely to matter in detail, so they become a short summary. The summary is bounded in size, so total cost stays predictable.
| Part of the request | Form | Why |
|---|---|---|
| System prompt | Verbatim, pinned | Defines behavior, must never be dropped |
| Rolling summary | Compressed | Carries goals, decisions, and exact values from old turns |
| Recent messages | Verbatim | Preserves exact wording and the current task state |
The request layout
The model receives the messages in a fixed order: the system prompt, then the summary, then the recent window. The summary comes before the recent messages because it describes events that happened earlier in time.
The function below builds that layout. It adds the summary as a second system message only when a summary exists.
def build_request(system_prompt, summary, recent):
messages = [{"role": "system", "content": system_prompt}]
if summary:
messages.append({
"role": "system",
"content": "Summary of the earlier conversation:\n" + summary,
})
messages.extend(recent)
return messagesThe label "Summary of the earlier conversation:" matters. It tells the model that the text is background, not a new instruction from the user.
A note on provider differences
Some chat APIs accept only one system message, or require it at the start. If yours does, merge the summary into the single system message instead of adding a second one. Another option is to send the summary as the first user message, followed by a short assistant acknowledgement. This keeps roles alternating, but it uses a few more tokens. Check your provider's rules before choosing.
The compaction step
Compaction is the step that moves messages from the verbatim window into the summary. The function below does it. It runs the model-backed summarize function only when the total size passes a threshold.
def estimate_tokens(message):
# Rough heuristic: about 4 characters per token, plus a small per-message overhead.
# Replace with your model's real tokenizer when exact counts matter.
return len(message["content"]) // 4 + 4
def compact(history, summary, trigger_tokens, keep_recent, summarize):
# history: list of {"role", "content"} messages without the system prompt.
# summary: the current summary string, or "" if none exists yet.
# summarize(previous_summary, old_messages) -> new summary string (a model call).
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:])
# Keep the recent window starting on a user turn; fold the rest into the summary input.
while recent and recent[0]["role"] != "user":
old.append(recent.pop(0))
new_summary = summarize(summary, old)
return new_summary, recentWalk through what it does:
- It estimates the cost of the current summary plus all history messages.
- If the total is under
trigger_tokens, or there are too few messages to split, it returns everything unchanged. - Otherwise it splits history into
oldandrecent, whererecentis the lastkeep_recentmessages. - If
recentbegins with an assistant message, that message is moved toold. This keeps the window starting on a user turn. - It calls
summarizewith the previous summary and the old messages, and returns the new summary with the trimmed history.
The caller stores both return values and uses them on the next turn. The old messages can be discarded from the live history, though you may want to log them elsewhere.
Step by step example
Suppose keep_recent is 4 and the history holds these roles: user, assistant, user, assistant, user, assistant, user, assistant, user, assistant. That is 10 messages.
- The last 4 messages are user, assistant, user, assistant. The first of them is a user message, so the split is clean.
- The first 6 messages go to
summarize. - The recent window keeps 4 messages.
Now suppose the history holds 9 messages starting with a user message: the last 4 are assistant, user, assistant, user. The first recent message is an assistant reply. The loop moves it into old, so recent has 3 messages and old has 6. The window now starts on a user turn.
The summarization prompt
The quality of the summary depends heavily on the instructions. This prompt names what to keep, forbids invented facts, and caps the length.
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 300 words.Passing the previous summary as input is what makes the summary rolling. Each pass rewrites one document. It does not append a new document each time.
Tuning the three numbers
The hybrid strategy has three main settings. They interact, so set them together.
trigger_tokens: when compaction starts. Set it below your input budget with some headroom, so a long next message does not push the request over the limit before you can compact.keep_recent: how many messages stay verbatim. Larger values preserve more exact wording but leave less room for everything else.- Summary cap: the maximum summary length, here 300 words, or roughly 400 tokens.
A worked budget makes this concrete. Assume an 8,000-token input budget.
| Component | Tokens |
|---|---|
| System prompt | 500 |
| Summary cap | 400 |
| Headroom for the next user message | 1,000 |
| Left for recent messages | 6,100 |
If a typical exchange is about 300 tokens, keep_recent of 10 messages costs roughly 1,500 tokens, well within what is available. A trigger around 6,500 tokens for summary plus history would then fire before the budget is under pressure.
Compacting less often is cheaper in model calls, since each compaction is an extra request. Compacting too late risks hitting the limit. A common compromise is to compact when history crosses the trigger, and to fold in a batch of messages at once rather than one message per turn.
Failure modes and edge cases
- Summary drift. Every pass rewrites the summary, so a detail can be lost in one pass and never come back. Exact values such as IDs are most at risk. The prompt's instruction to keep exact values reduces this but does not remove it.
- Summary growth. If the length cap is ignored, the summary can grow until it eats the budget. Measure it. If it exceeds your cap, run another pass that asks for a shorter version.
- Estimate error. The 4-characters-per-token rule is rough. Code, non-English text, and numbers often use more tokens per character. Leave headroom, or use the real tokenizer.
- Failed summarization. The
summarizecall can fail or time out. In that case, keep the old messages and the old summary, and try again on the next turn. Do not drop the messages until the new summary exists. - Tool calls. If
oldandrecentare split between a tool call and its result, the request can be rejected by the API. Make sure the cut never separates an assistant tool call from its tool result. The earlier chapter on turn boundaries covers this. - Summary injected as instructions. If the summary contains text copied from the user, such as "ignore previous rules", the model may treat it as a command. The framing label and a note in the prompt help, but treat summaries as untrusted text.
A complete turn
This short sketch shows how the pieces fit together in a chat loop. The call_model and summarize functions stand in for your own model calls.
def chat_turn(user_text, state, system_prompt, call_model, summarize,
trigger_tokens=6500, keep_recent=10):
# state: {"summary": str, "history": list of messages}
state["history"].append({"role": "user", "content": user_text})
state["summary"], state["history"] = compact(
state["history"], state["summary"],
trigger_tokens, keep_recent, summarize,
)
request = build_request(system_prompt, state["summary"], state["history"])
reply = call_model(request)
state["history"].append({"role": "assistant", "content": reply})
return replyCompaction runs after the new user message is added and before the request is sent. That way the request always reflects the compacted state.
Exercises
Exercise
Why does build_request place the summary before the recent messages and label it "Summary of the earlier conversation"?
Show answer
The summary describes events that happened before the recent messages, so putting it first keeps the order chronological. The label tells the model the text is background context and not a new instruction from the user.
Exercise
compact is called with a history of 12 messages, keep_recent of 5, and a total size over the trigger. The history starts with a user message and alternates user, assistant. Which messages go into old, and how many stay in recent?
Show answer
The last 5 messages are indices 7 to 11. Index 7 is an assistant message (odd indices are assistant). The loop moves it to old, so old holds the first 8 messages (indices 0 to 7) and recent holds 4 messages (indices 8 to 11), starting on a user turn.
Exercise
The summarize call raises an error during compaction. What should the application do with the history and the summary, and why?
Show answer
Keep the existing summary and all existing history, and retry compaction on a later turn. The old messages must not be dropped until a new summary has been created and saved, or their content is lost. Because the request may now exceed the budget, also consider temporarily falling back to sliding-window truncation so the next call still fits.