Sub topic 9
Trimming and Managing Conversation History
This chapter assumes you know what tokens are, can call a chat model through an API, and can read short Python. It covers the history part of the context: what to keep, what to drop, and how to avoid common mistakes.
Why history needs management
A chat API is stateless. The model remembers nothing between calls, so your application resends the earlier messages every time. History grows with each turn, and every resent message costs tokens again. Left alone, history crowds out documents and tool results, raises cost and latency, and eventually exceeds the window.
History also carries risk. An old wrong answer or an outdated instruction stays in the context and can keep influencing the model. Managing history is about both size and quality.
Common strategies
| Strategy | What it does | Main risk |
|---|---|---|
| Keep everything | Resends all messages | Exceeds the window, costs more |
| Sliding window | Keeps the last N messages or tokens | Forgets early goals and facts |
| Selective keep | Drops low-value messages such as greetings and failed attempts | Needs a rule for "low value" |
| Summarize | Replaces old messages with a short summary | Summaries lose detail |
The next chapter covers summarizing in depth. Here we focus on trimming by budget.
Trimming by budget
Count in tokens, not messages. Ten short messages and ten long ones differ greatly in cost. The pick_within_budget function below walks the history from newest to oldest and stops when the budget is used up. It uses a rough estimate of four characters per token. Use your provider's tokenizer when you need exact numbers.
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def trim_history(history, budget):
# history is a list of message strings, oldest first.
kept, used = [], 0
for message in reversed(history):
cost = estimate_tokens(message)
if used + cost > budget:
break
kept.append(message)
used += cost
kept.reverse()
return kept
history = [
"User: I am planning a trip to Lisbon in May.",
"Assistant: Great. How many days will you stay?",
"User: Five days. I prefer museums over beaches.",
"Assistant: I suggest the Gulbenkian and the Tile Museum.",
"User: What about food?",
]
print(trim_history(history, budget=30))The loop stops at the first message that does not fit. It does not skip it and continue. This keeps the kept messages contiguous, so the conversation never has a gap in the middle.
Pitfalls
- Losing the original goal. A plain sliding window drops the first message, which often states the task. Keep the task statement outside the history, for example in the system prompt, or pin it so trimming never removes it.
- Splitting a tool exchange. A tool call and its result belong together. If you trim one and keep the other, many APIs reject the request or the model misreads it. Trim in whole units.
- Keeping errors. Failed attempts and corrected mistakes can mislead the model later. Drop them once they are resolved, or note the correction.
- Trimming at the wrong time. Changing the start of the history on every call also breaks prompt caching. Trim in larger steps, for example when you pass a threshold, so the prefix stays the same for many calls.
- Counting only history. The history budget is what remains after the system prompt, tools, documents, and the output reserve. Compute it from the whole window, as in the budgeting chapter.
Practical rules
- Set an explicit token budget for history before you trim.
- Trim oldest first, in whole turns.
- Pin the goal and key constraints.
- Log what you removed so you can debug odd answers later.
Exercise
A user's first message says "Answer only in French." After 40 turns, a sliding window drops it and the model starts answering in English. Give two ways to fix this.
Show answer
Move the instruction into the system prompt, which is never trimmed, or pin the message so the trimming function always keeps it. Summarizing older turns while preserving the stated constraints would also work.
Exercise
In trim_history, why does the loop break instead of skipping a message that is too large and continuing to older ones?
Show answer
Skipping would keep older messages while dropping a newer one, leaving a gap in the conversation. Breaking keeps a contiguous run of the most recent messages.