Sub topic 5
Truncating with a Sliding Window
This chapter assumes you can read Python, know the system, user and assistant message roles, and have a rough idea of what a token is. Earlier chapters covered why every request carries the whole conversation and how to set an input budget. Here you will turn that budget into code that drops old messages.
The idea
A sliding window keeps only the newest part of the conversation. Each time you build a request, you start from the latest message and walk backward, adding messages until the next one would not fit in the budget. Everything older is left out of that request.
The window "slides" because the cut point moves forward as the conversation grows. The full history can still live in your database. You only decide what to send.
A working implementation
The function below follows that flow. It uses a rough token estimate of about four characters per token. That is good enough to learn the logic. For production, swap in your model's real tokenizer, because estimates can drift by 10 to 30 percent, especially for code or non-English text.
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 + keptWalk through the steps.
- Split off system messages. They are handled separately so they are never dropped. The next chapter covers pinning in more detail.
- Compute the remaining budget. The system messages are paid for first. What is left is the room for conversation.
- Walk backward.
reversed(rest)yields the newest message first. Each message that fits is kept, and its cost is subtracted. - Stop at the first miss. The
breakmatters. Without it, the loop could skip a large message and keep a smaller, older one. That would leave a gap in the middle of the conversation, which confuses the model more than a clean cut does. - Restore order. Messages were collected newest first, so
kept.reverse()puts them back in chronological order. - Repair the front. If the window now begins with an assistant message, its question is gone. The
whileloop removes it so the window starts on a user turn.
A worked example
Suppose the budget is 60 tokens. The system prompt costs 12, leaving 48 for conversation.
history = [
{"role": "system", "content": "You are a concise travel assistant."},
{"role": "user", "content": "I want to visit Lisbon in May. What should I pack?"},
{"role": "assistant", "content": "Light layers, a rain jacket, and comfortable walking shoes."},
{"role": "user", "content": "My budget is 1200 euros for the whole trip."},
{"role": "assistant", "content": "That works for a week if you stay in a hostel or guesthouse."},
{"role": "user", "content": "Which neighborhood should I stay in?"},
]
window = truncate_history(history, max_input_tokens=60)
for m in window:
print(m["role"], "->", m["content"])With this budget, the newest messages fit and the oldest are dropped. The loop keeps the final user question and the assistant reply before it. It may also keep the budget message, depending on the estimates. Once a message does not fit, the loop stops and everything older is gone.
Notice what this can lose. If the Lisbon-in-May message falls outside the window, the model no longer knows the destination. The answer to "Which neighborhood?" will be generic or wrong. This is the central weakness of truncation, and it is why the later chapters add summaries.
Edge cases
The newest message alone is too large
If the latest user message costs more than the whole budget, the loop breaks immediately and kept is empty. The function then returns only the system messages, and the model never sees the user's question. Decide what your application should do. Reasonable choices are to reject the input with a clear error, to truncate that single message, or to ask the user to shorten it. Do not silently send a request with no user turn.
Windows that start with assistant messages
The cleanup loop removes assistant messages at the front, but it can remove more than one. If the window is [assistant, assistant, user, ...], both leading assistant messages are dropped. This is usually what you want. Some APIs reject a conversation that does not begin with a user message, and others merely answer worse.
Overhead differs by provider
The + 4 per message is a guess. Real APIs add tokens for role markers and message separators, and the amount varies by model. Leave a safety margin. A common approach is to set max_input_tokens to 90 to 95 percent of the true limit, after reserving space for the reply.
Estimation errors compound
Because the estimate is applied per message, errors add up across a long window. A budget that is correct on average can still overflow on one unlucky request. If the provider returns a context-length error, a defensive pattern is to shrink the budget by a fixed fraction and retry once.
Choosing the window by tokens or by message count
Some applications keep the last N messages instead of fitting a token budget.
| Approach | Strength | Weakness |
|---|---|---|
| Last N messages | Trivial to write and predict | One long paste can overflow the limit, and short chats waste capacity |
| Token budget | Uses the available space and respects the limit | Needs a token counter and a safety margin |
Token-based windows are the safer default. Message counts are acceptable for prototypes where messages are short and uniform.
What sliding windows are good and bad at
Strengths:
- Cost and latency stay bounded, since the input never exceeds the budget.
- No extra model call is needed, so there is no added latency or cost for compression.
- The behavior is deterministic. The same history and budget always give the same window, which makes bugs easy to reproduce.
- The recent verbatim text is exact, with no paraphrasing errors.
Weaknesses:
- Anything older than the window is forgotten completely, including goals, names and decisions stated early.
- The user can notice. They refer to something said twenty turns ago and the assistant has no idea what they mean.
- Early messages often hold the most important setup, which is the part truncation removes first.
You can reduce the damage in two ways, which later chapters cover. Pin messages that must always stay, and replace the dropped messages with a summary instead of discarding them.
Testing your window
Write small tests before trusting the function. These checks catch the most common mistakes.
def test_truncate_history():
system = {"role": "system", "content": "Be brief."}
msgs = [system]
for i in range(20):
msgs.append({"role": "user", "content": f"question {i} " * 10})
msgs.append({"role": "assistant", "content": f"answer {i} " * 10})
window = truncate_history(msgs, max_input_tokens=200)
# System prompt survives and stays first.
assert window[0] == system
# Stays within budget.
assert sum(estimate_tokens(m) for m in window) <= 200
# Starts on a user turn after the system messages.
assert window[1]["role"] == "user"
# Keeps the newest message.
assert window[-1] == msgs[-1]
# Order is preserved.
assert window[1:] == [m for m in msgs if m in window[1:]]
test_truncate_history()
print("ok")If your history may contain tool calls, add a test for those too. The cut must never separate a tool call from its result. That rule is the subject of a later chapter.
Exercise
In truncate_history, why does the loop use break when a message does not fit, instead of continue to try older, smaller messages?
Show answer
With continue, the loop could skip one large message and then keep smaller messages from before it. The window would then have a hole in the middle, and the model would see replies without the questions or context that produced them. Using break guarantees the kept messages form one unbroken run ending at the newest message.
Exercise
A user pastes a document that costs more than maxinputtokens on its own. What does truncate_history return, and why is that a problem?
Show answer
It returns only the system messages. The loop breaks on the first (newest) message because it exceeds the budget, so kept is empty. The model then receives no user turn. Your application should handle this case explicitly, for example by rejecting the input, truncating the single message, or asking the user to shorten it.