Sub topic 10
Compacting and Summarizing Long Sessions
This chapter assumes you know what a token budget is, how the parts of a context fit together, and how to trim conversation history. It also assumes you can read short Python functions. Trimming drops old messages. Compaction replaces them with something shorter that keeps what matters. Done well, it lets a session run far past the size of the window. Done badly, it quietly deletes the facts the task depends on.
What compaction is
Compaction means replacing a long stretch of older context with a shorter version, then continuing the session from that version. The most common form is summarization. The model, or a cheaper model, reads the older messages and writes a short summary. That summary takes the place of the messages it covers.
Trimming and compaction solve the same problem in different ways:
| Technique | What happens to old content | Risk |
|---|---|---|
| Trimming | Dropped entirely | Loses facts the task still needs |
| Compaction | Replaced by a summary | Summary may omit or distort facts |
| External memory | Moved outside the window | Must be retrieved again later |
Compaction suits sessions where the early turns contain decisions and findings that later turns depend on. Examples are a long coding session, a research task, and a support conversation that spans many steps.
The basic shape
The core operation has three steps. Split the history into an older part and a recent part. Summarize the older part. Put the summary in front of the recent part, which stays word for word.
def compact(history, keep_last, summarize):
# history is a list of message strings, oldest first.
# summarize is a function that takes a list of messages and returns a short string.
split = max(0, len(history) - keep_last)
older, recent = history[:split], history[split:]
if not older:
return history
summary = summarize(older)
return ["Summary of earlier conversation: " + summary] + recentThe recent messages stay verbatim because the next reply usually depends on their exact wording. A summary of the last two turns would lose the details the model needs right now. The keep_last value sets how much exact detail you keep against how much space you free.
You can test the function without a model by passing a stand-in summarizer:
history = [f"message {i}" for i in range(10)]
result = compact(history, keep_last=3, summarize=lambda msgs: f"{len(msgs)} earlier messages")
print(result)
# ['Summary of earlier conversation: 7 earlier messages', 'message 7', 'message 8', 'message 9']When to compact
Compaction needs a trigger. There are three common ones.
- Threshold trigger: compact when the context reaches a fraction of the window, such as 70 to 80 percent. This is the most common choice.
- Event trigger: compact at a natural boundary, such as the end of a subtask or after a long tool result has been used.
- Manual trigger: the user or developer requests it.
The threshold must leave room for two things. The summarization call itself needs input space, and the model needs output space for its next reply. Reusing the budget idea from earlier chapters, compute the trigger from the window minus the output reserve:
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def should_compact(history, window, output_reserve, threshold=0.75):
used = sum(estimate_tokens(m) for m in history)
usable = window - output_reserve
return used > usable * thresholdTriggering too late is the common error. If you wait until the window is nearly full, the summarization request may not fit, and the call fails at the moment you most need it.
What a good summary keeps
A generic instruction such as "summarize this conversation" produces prose that sounds complete but drops specifics. A compaction summary should be written for the task, not for a reader who wants an overview. Tell the summarizer what to preserve.
Keep these:
- The user's goal and any constraints they stated.
- Decisions made and the reasons for them.
- Current state: what is done, what is in progress, what is next.
- Exact identifiers that must not drift, such as file paths, function names, IDs, and error messages.
- Open questions and unresolved problems.
- Corrections the user made, so the model does not repeat a rejected approach.
Drop these:
- Pleasantries and acknowledgements.
- Tool output that has been used and is no longer needed.
- Dead ends, except a one-line note that the approach failed and why.
- Duplicate information.
A structured prompt for the summarizer gives more consistent results than a free-form request:
SUMMARY_INSTRUCTIONS = """Summarize the conversation below for an assistant that will continue the task.
Use these sections, and write "none" for any that are empty:
Goal: what the user wants and any constraints.
Decisions: choices made, each with a short reason.
State: what is finished, in progress, and next.
Exact details: file paths, names, IDs, numbers, and error messages, copied verbatim.
Open issues: unresolved questions or failures.
Do not add information that is not in the conversation."""
def make_summarizer(call_model):
# call_model takes a prompt string and returns the model's reply as a string.
def summarize(messages):
prompt = SUMMARY_INSTRUCTIONS + "\n\n" + "\n".join(messages)
return call_model(prompt)
return summarizeNote the last line of the instructions. A summarizer that fills gaps with plausible details creates false facts, and the main model will treat them as true.
How compaction fails
Compaction is lossy. Every failure comes from what the summary loses or changes.
Lost details
A summary says "the user chose the second database option" but omits which option that was. Later turns cannot recover the information, because the original messages are gone. Copying exact identifiers verbatim is the main defense.
Distorted facts
Summarizers can state a tentative idea as a decision, or merge two similar items into one. This connects to context poisoning: a wrong claim in a summary persists and is repeated in every later call. Because the summary is always in the context, the model often treats it as more reliable than it deserves.
Compounding loss
If you summarize a summary, each pass loses a little more. After several rounds the early parts of the session are reduced to vague statements. Two practices reduce this. Keep the previous summary as a separate block and ask the summarizer to update it with the new material, instead of re-summarizing everything. Also store the full original history outside the window, so a mistake can be corrected by going back to the source.
Stale state
A summary freezes the state at the time it was written. If a file changed after that, or the user reversed a decision, the summary may now conflict with newer messages. This is a context clash. The usual fix is to put corrections in the summary's state section and to re-read live sources, such as files, instead of trusting a remembered description.
Cost and latency
Compaction is an extra model call on a large input. It also changes the start of the prompt, which can invalidate a prompt cache. Compact in batches, not on every turn, so you pay this cost rarely.
A compaction flow
The flow below shows one pass through a long session.
Putting it together
This function combines the trigger and the compaction, and archives the originals before replacing them.
def maybe_compact(history, archive, window, output_reserve, keep_last, summarize):
# archive is a list that receives the messages removed from the window.
if not should_compact(history, window, output_reserve):
return history
split = max(0, len(history) - keep_last)
if split == 0:
return history
archive.extend(history[:split])
return compact(history, keep_last, summarize)This code relies on should_compact, estimate_tokens, and compact defined earlier in the chapter. Run them together in one file.
If the history is short but a single message is huge, such as a large tool result, compaction by message count will not help. In that case, handle the large item directly. Replace the tool result with a short note of what it showed, or load it again later when needed.
Choosing what to keep verbatim
Not every old message should be summarized. Some content should stay exact even when it is old.
- The system prompt and tool descriptions, which are not part of the history.
- Instructions the user gave that govern the whole session.
- Short, high-value items such as a specification the user pasted in.
- Recent tool results the model is still working from.
Pin these outside the compactable region. A simple way is to keep them in a separate list that the compaction function never touches.
Checking a compaction
A compaction change is a context change, so test it as one. Pick a set of tasks that need information from early in a long session. Run each task with the full history, with trimming, and with compaction. Compare accuracy and token use. If compaction answers questions about early decisions as well as the full history does, at a lower token cost, it helps. If answers about exact details get worse, the summary instructions need to preserve more.
Exercise
A session reaches 90 percent of the window. Your code then calls the summarizer, but the call fails because the request is too large. What went wrong in the design, and what would you change?
Show answer
The compaction trigger was set too late. The summarization request needs its own input space plus room for the model's output, so compaction must start earlier, for example at 70 to 80 percent of the usable window (window minus output reserve). You could also summarize the history in chunks so each request stays small.
Exercise
After three rounds of re-summarizing the whole summary, the model no longer remembers the exact file path the user specified in turn 4. Name the failure and give two fixes.
Show answer
This is compounding loss. Fixes: keep the previous summary as a separate block and update it with new material instead of re-summarizing it, copy exact identifiers such as file paths verbatim into an "Exact details" section, and archive the original messages outside the window so the path can be recovered.