Sub topic 5
Truncating with a Sliding Window
This chapter assumes you can write basic Python and know the chat message roles (system, user, assistant). It also assumes you know that models count input in tokens. Earlier chapters covered why history is resent on every request and how to set an input budget. Here you apply that budget.
The idea
A sliding window keeps only the newest messages that fit in the input budget. Older messages fall off the front as new ones arrive. It needs no extra model call, it is fast, and its result is easy to predict. The cost is that anything outside the window is gone.
The algorithm
The code below follows the diagram.
- Separate the system messages. They are always sent, so their cost comes off the budget first.
- Walk the remaining messages from newest to oldest. Keep each one while it fits.
- Stop at the first message that does not fit. Do not skip it and keep older ones, because that would leave a gap in the conversation.
- Reverse the kept messages back into chronological order.
- If the window starts with an assistant message, drop it. That reply answers a question the model can no longer see.
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 truncate_history(messages, max_input_tokens):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_input_tokens - sum(estimate_tokens(m) for m in system)
kept = []
for message in reversed(rest):
cost = estimate_tokens(message)
if cost > budget:
break
kept.append(message)
budget -= cost
kept.reverse()
# Do not start the window with an orphaned assistant reply.
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system + keptA worked run
Suppose the budget is 40 tokens and the system prompt costs 10. That leaves 30 for conversation. Each message below costs about 12 tokens.
| Position | Role | Cost | Outcome |
|---|---|---|---|
| 1 (oldest) | user | 12 | Dropped, budget already spent |
| 2 | assistant | 12 | Kept, then removed as a leading assistant message |
| 3 | user | 12 | Kept |
| 4 (newest) | user | 12 | Kept |
Walking backward, messages 4 and 3 fit (24 of 30 tokens used). Message 2 does not fit, since only 6 tokens remain, so the loop stops. The window starts on a user message and needs no further trimming. The request is the system prompt, message 3, and message 4.
Common errors
- Forgetting the system prompt. If you truncate the whole list, the instructions go first, because they are the oldest messages. Always separate them, as the code does.
- Using the full context window as the budget. The reply also needs room. Set
max_input_tokensto the window size minus the output you reserve. - Skipping instead of stopping. Using
continuewhere the code usesbreakcan keep a small old message while dropping a larger newer one, which scrambles the story. - Trusting the estimate near the limit. The four-characters-per-token rule varies by language and content. Leave a safety margin, or use the real tokenizer.
- Breaking tool call pairs. This function treats messages independently. If your history includes tool calls, a cut can separate a call from its result. A later chapter covers that.
What you lose
The window forgets. If the user stated their name or a constraint 50 messages ago, the model no longer knows it. Pinning important messages and summarizing old turns address this, and later chapters cover both.
Exercise
A history has a system prompt of 100 tokens, and maxinputtokens is 1,000. The newest user message costs 300 tokens, the assistant reply before it costs 500, and the user message before that costs 200. Which messages does truncate_history return?
Show answer
The budget for conversation is 1,000 - 100 = 900. The newest user message (300) fits, leaving 600. The assistant reply (500) fits, leaving 100. The earlier user message (200) does not fit, so the loop stops. The kept list is the assistant reply followed by the newest user message. It starts with an assistant message, so that reply is removed. The result is the system prompt and the newest user message only.
Exercise
Why does the loop use break rather than continue when a message does not fit?
Show answer
Continuing would let older, smaller messages into the window after a larger one was dropped. The model would then see a conversation with a hole in the middle, which can make replies refer to things out of order or without context.