Sub topic 9
Trimming and managing conversation history
Conversation history is the part of the context that grows on every turn. The system prompt and tool definitions stay about the same size. History gets longer with each exchange, so it is usually the first part to push a long session past its token budget. This chapter covers how to decide what history to keep, how to cut the rest without breaking the conversation, and which errors to watch for.
It assumes you have read the earlier chapters on tokens and budgets and on the parts of a context. You should be comfortable reading short Python.
Why history needs management
Most chat APIs are stateless. The model keeps no memory between calls, so your application resends the conversation each time. The cost of turn N therefore includes every earlier turn, and total tokens processed over a session grow roughly with the square of the number of turns.
Three problems follow from this:
- Budget. Old turns take up space that retrieved documents or the output reserve may need.
- Cost and latency. Every resent token is billed and has to be processed.
- Quality. Old, off-topic turns act as distractors. Early mistakes or outdated facts can stay in the context and keep influencing answers (see the chapter on context failures).
The aim is not the shortest history. The aim is the history that the next step needs.
The working model: history as a ranked store
Treat each past message as an item with a token cost and a value for the current step. Three signals estimate value:
- Recency. Recent turns usually matter most, because the user's current request often refers to them ("make that shorter").
- Role in the task. The original task statement, standing user preferences, and decisions the user has confirmed matter more than casual exchanges.
- Information density. A 3,000-token tool result that produced a one-line conclusion has low value once the conclusion is recorded.
The simplest policies use only recency. Better policies add the other two signals.
Common trimming strategies
| Strategy | What it does | Strength | Main risk |
|---|---|---|---|
| Sliding window by turns | Keep the last N turns | Simple, predictable | Forgets the original task and early decisions |
| Sliding window by tokens | Keep the newest turns that fit a budget | Respects the budget exactly | Same as above, and a single huge turn can evict everything else |
| Pinned head plus window | Always keep the first turn(s), then fill with recent turns | Preserves the task statement | Pinned content may become outdated |
| Tool-result clearing | Replace old tool outputs with a short stub | Removes the largest, lowest-value items | The model may need the raw output again |
| Summarization (compaction) | Replace old turns with a summary | Keeps the gist of a long session | Summaries lose details and can add errors |
Compaction gets its own chapter. Here the focus is on the first four, which need no extra model call.
Trimming by turns, not by messages
A common error is to cut history by message count or by characters, in the middle of an exchange. Two things then go wrong:
- You can keep an assistant reply but drop the user question it answers. The reply becomes confusing.
- You can keep a tool result but drop the tool call that produced it. Many APIs reject this and return a validation error, because every tool result must match a preceding tool call.
To avoid both, group messages into turns and keep or drop each turn as a whole. A turn here starts at a user message and includes everything up to the next user message: assistant replies, tool calls, and tool results.
The function below builds on the estimate_tokens heuristic from the budgeting chapter. It pins the first turns, then keeps the newest turns that fit.
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def group_turns(messages):
# A new turn starts at each user message.
turns = []
for message in messages:
if message["role"] == "user" or not turns:
turns.append([message])
else:
turns[-1].append(message)
return turns
def turn_cost(turn):
return sum(estimate_tokens(m["content"]) for m in turn)
def trim_history(messages, budget, pinned_turns=0):
turns = group_turns(messages)
pinned = turns[:pinned_turns]
rest = turns[pinned_turns:]
remaining = budget - sum(turn_cost(t) for t in pinned)
kept = []
for turn in reversed(rest):
cost = turn_cost(turn)
if cost > remaining:
break # stop at the first turn that does not fit
kept.append(turn)
remaining -= cost
kept.reverse()
return [m for turn in pinned + kept for m in turn]
history = []
for i in range(5):
history.append({"role": "user", "content": f"q{i} ".ljust(40, "-")})
history.append({"role": "assistant", "content": f"a{i} ".ljust(40, "-")})
kept = trim_history(history, budget=50, pinned_turns=1)
print([m["content"][:2] for m in kept])Each message is 40 characters, or 10 tokens, so each turn costs 20 tokens. The pinned first turn uses 20 of the 50-token budget. Of the 30 tokens left, one turn fits, and a second would need 40. The script prints:
['q0', 'a0', 'q4', 'a4']Note the break. If you used continue instead, a small old turn could be kept after a larger newer turn was skipped. The kept history would then have a gap, and the order of events would be misleading. Stopping at the first turn that does not fit keeps the recent history contiguous.
Where trimming fits in the budget
History is the flexible part of the budget. The fixed parts are the output reserve, the system prompt, the tool definitions, and the current user message. Retrieved documents compete with history for what is left. The build_context function from the budgeting chapter gives documents their share first and history the remainder. Other splits are possible. A coding agent might give history more room than documents, and a question-answering bot over a knowledge base might do the opposite.
The order in the diagram goes from the least lossy step to the most lossy. Clearing tool results discards bulk but keeps the conversation's structure. Dropping turns discards whole exchanges. Summarizing costs an extra model call and can introduce errors.
Clearing old tool results
In agent sessions, tool results are often the largest items in the history. A file read, a search result, or a log dump can be thousands of tokens. After the model has used the result, the later turns mostly need the conclusion, not the raw text.
A common technique is to keep the tool call and replace the result's content with a stub such as [result omitted: 4,200 tokens, re-run the tool if needed]. The stub has three useful properties:
- The call and result pair stays valid for APIs that require it.
- The model knows something was there and how to get it back.
- The token cost drops from thousands to a few dozen.
This works best when the tool is cheap and repeatable. It works poorly when the result is hard to reproduce, such as a one-time output or data that changes, in which case save the important parts first (see the chapter on external memory).
What to pin
Pinned content survives trimming. Good candidates are:
- The original task statement, when the session is a long task with one goal.
- Constraints the user stated once and expects to hold ("use metric units", "do not modify the tests").
- Decisions that later work depends on.
Pinning has a cost. Each pinned item permanently uses part of the budget, and a pinned fact can become wrong. If a user changes a constraint on turn 30, the pinned original on turn 1 now conflicts with it. That is the context clash described in the failures chapter. A pinned item needs an update path: replace the old text rather than adding a correction after it.
Common errors
- Trimming by characters or message count. This splits turns and orphans tool results. Group by turn.
- Using the same trimming for every task. A casual chat can lose its early turns safely. A debugging session cannot lose the error message from turn 2.
- Trimming silently. If the model does not know that earlier turns were removed, it may answer as if it remembers them, and it can invent details. Insert a short marker such as
[earlier conversation omitted]so the gap is visible. - Dropping the system prompt or pinned content during trimming. Apply trimming only to the history section, never to the fixed parts.
- Trusting the heuristic count. The 4-characters-per-token rule is rough. Code, non-English text, and JSON often tokenize at a different rate. Use your provider's tokenizer, or leave a safety margin of 10 to 20 percent.
- Never measuring. A trimming policy that looks sensible can hurt answers on tasks that depend on early details. Compare policies on a fixed test set, as described in the evaluation chapter.
Exercise
A session has a user message asking for a refactor, an assistant message with a tool call that reads a 6,000-token file, a tool message with the file contents, and an assistant reply. Your history budget is 2,000 tokens and the session just started. Which of these would you do: (a) drop the tool message and keep the rest, (b) replace the tool message's content with a short stub and keep the rest, or (c) drop the whole turn? Explain why.
Show answer
Option (b). Dropping only the tool message (a) leaves a tool call with no matching result, which many APIs reject and which confuses the model. Dropping the whole turn (c) removes the user's refactor request, which is the task itself. Replacing the result with a stub keeps the call and result pair valid and keeps the request and the assistant's conclusion, while cutting about 6,000 tokens. The stub should say the result was omitted so the model can re-read the file if it needs the details.
Exercise
In trim_history, why does the loop use break rather than continue when a turn does not fit?
Show answer
With continue, the loop would skip a large recent turn but could still keep smaller, older turns before it. The kept history would then have a gap, with a newer exchange missing while older ones remain, which misrepresents the order of events. With break, the kept turns are always an unbroken run ending at the newest turn.