Sub topic 7
Keeping recent turns with a sliding window
This chapter assumes you have the chat loop from earlier chapters. You should know that the history is a list of dictionaries with role and content keys. You should also know that the whole list is sent on every request, and that the model has a limited context window. Here you will build the function that keeps that list inside the limit.
The problem a window solves
Every turn adds two messages to the history, one from the user and one from the assistant. The next request sends all of them again, so each request is larger than the last. Two things go wrong over a long session:
- The request eventually exceeds the model's context window, and the API rejects it.
- Before that point, cost and latency grow, because you pay for every input token on every turn.
A sliding window is the simplest fix. You keep the system message and only the most recent messages, and you drop the oldest ones. The window moves forward as the conversation grows, which is where the name comes from.
The trimming function
def trim_history(history, max_messages):
"""Keep system messages plus the most recent max_messages other messages."""
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
rest = rest[-max_messages:]
while rest and rest[0]["role"] != "user":
rest.pop(0)
return system + rest
if __name__ == "__main__":
history = [
{"role": "system", "content": "s"},
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
{"role": "user", "content": "u2"},
{"role": "assistant", "content": "a2"},
{"role": "user", "content": "u3"},
]
trimmed = trim_history(history, 4)
print([m["content"] for m in trimmed])
assert [m["content"] for m in trimmed] == ["s", "u2", "a2", "u3"]The function does four things:
- It separates system messages from everything else. The system message sets the bot's behavior, so it must never be dropped.
- It slices the remaining messages with
rest[-max_messages:], which keeps the newest ones. - It removes leading messages until the first one is from the user.
- It puts the system messages back in front.
In the demo, max_messages is 4. The slice keeps a1, u2, a2, u3. The first of those is an assistant message, so the loop drops it and the result is s, u2, a2, u3. The window shrank from 4 to 3 messages to keep the conversation well formed.
Why the first message must be a user message
Most chat APIs expect the conversation to start with a user message after the system message. Some reject a request that begins with an assistant message. Even where they accept it, a reply with no question before it confuses the model. An odd max_messages is the usual cause, because it cuts a user and assistant pair in half.
Choosing an even number does not fully prevent this. A failed turn that was never repaired, or a history loaded from a file, can leave the roles out of order. The while loop makes the function safe whatever the input.
Gotchas and edge cases
Zero is not "keep nothing"
In Python, rest[-0:] is the same as rest[0:], so it returns the whole list. If max_messages is 0, the function trims nothing. Reject invalid values instead of letting them through:
def trim_history(history, max_messages):
if max_messages < 1:
raise ValueError("max_messages must be at least 1")
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
rest = rest[-max_messages:]
while rest and rest[0]["role"] != "user":
rest.pop(0)
return system + restThe newest message must survive
With max_messages=1, the window holds only the latest message. During a request that message is the user's new input, so it survives. The bot then answers with no memory of earlier turns. A window this small is legal but rarely useful.
Trimming a copy versus trimming the original
You have two choices about where to apply the window.
| Approach | What it does | Trade-off |
|---|---|---|
| Trim the stored history | `history = trim_history(history, n)` | Uses little memory, and the saved file stays small. Dropped turns are gone for good. |
| Trim a copy for each request | `complete(trim_history(history, n))` | Keeps the full transcript for saving, display, or later summarization. The list grows without bound in memory. |
For a terminal chatbot, trimming a copy is usually the better default. Memory is cheap, and a full transcript lets you change the window size later or summarize old turns. The cost is that you must remember to trim on every request. Put the call in one place, such as run_turn, so it cannot be forgotten.
def run_turn(history, user_text, complete, max_messages=20):
history.append({"role": "user", "content": user_text})
try:
reply = complete(trim_history(history, max_messages))
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyPut this below trim_history in the same file. The model sees at most 20 non-system messages. The stored history keeps everything, and a failed call still removes the user message it added.
Counting tokens instead of messages
Message count is a rough proxy. A pasted log file can be a single message that fills the whole context window, while twenty short replies might use very little. The real limit is measured in tokens, which are the chunks of text the model processes.
A token-based window walks backward from the newest message and stops when the budget runs out. A real tokenizer from your provider gives exact counts. The sketch below uses a rule of thumb of about four characters per token for English text, which is good enough to stay safely under the limit.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def trim_to_budget(history, max_tokens):
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
budget = max_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()
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system + kept
if __name__ == "__main__":
history = [
{"role": "system", "content": "Be brief."},
{"role": "user", "content": "x" * 400},
{"role": "assistant", "content": "y" * 400},
{"role": "user", "content": "short question"},
]
result = trim_to_budget(history, 120)
print([m["role"] for m in result])
assert [m["role"] for m in result] == ["system", "user"]The + 4 in estimate_tokens approximates the per-message overhead that APIs add for role markers. The loop uses break, not continue, when a message does not fit. Skipping a large message and keeping older small ones would leave a hole in the conversation, so the window must stay contiguous.
In the demo, the budget is 120 tokens. The system message costs 6, and the newest user message costs 7. The 400-character assistant message costs 104, which exceeds the 107 tokens left after the first two, so the loop stops there. The remaining list starts with the user message, as required.
Testing the window
The window is pure logic, so it needs no model to test. Check the properties you care about instead of exact output:
def check_window(history, max_messages):
trimmed = trim_history(history, max_messages)
non_system = [m for m in trimmed if m["role"] != "system"]
assert trimmed[0]["role"] == "system"
assert len(non_system) <= max_messages
assert not non_system or non_system[0]["role"] == "user"
def build(n_turns):
history = [{"role": "system", "content": "s"}]
for i in range(n_turns):
history.append({"role": "user", "content": f"u{i}"})
history.append({"role": "assistant", "content": f"a{i}"})
return history
if __name__ == "__main__":
for turns in range(0, 8):
for limit in range(1, 12):
check_window(build(turns), limit)
print("all windows ok")Again, add these below trim_history. The loops cover odd and even limits and histories shorter than the limit. If you ever change the function, these checks tell you quickly whether it still keeps the system message, respects the limit, and starts on a user message.
Limits of a sliding window
A sliding window forgets abruptly. If the user states their name in the first message and the window has since moved past it, the bot no longer knows it. The window cannot tell important old facts from filler.
Two techniques address this, and later chapters cover them. Summarization compresses dropped turns into a short note that stays in the history. Long-term memory stores facts outside the conversation and retrieves them when relevant. The window remains the base layer under both, because it guarantees the request fits.
Exercise
A history has one system message and 7 other messages in the order user, assistant, user, assistant, user, assistant, user. You call trim_history(history, 4). How many messages are returned in total, and what is the role of the first non-system message?
Show answer
The slice rest[-4:] keeps assistant, user, assistant, user. The first is an assistant message, so the loop drops it, leaving user, assistant, user. The result is 4 messages in total: 1 system plus 3 others. The first non-system message has the role user.
Exercise
Why does trim_history(history, 0) need a guard, and what would it do without one?
Show answer
In Python, rest[-0:] equals rest[0:], so it returns the entire list. Without a guard, a limit of 0 would silently keep every message instead of none, and the history would never be trimmed.