Sub topic 7
Keeping Recent Turns with a Sliding Window
This chapter assumes you can write Python functions, work with lists and dictionaries, and have a chat loop that keeps a list of role-tagged messages. If you need a refresher, see the earlier chapters on the chat loop and message history.
The problem: history grows every turn
The chat loop sends the whole history on every request. Each successful turn adds two messages, so the request gets larger each time. A model can only read a limited number of tokens at once, which is its context window. When the history passes that limit, the provider rejects the request or cuts content you wanted to keep.
A sliding window is the simplest fix. You keep the system message and only the most recent messages. Older turns fall off the front.
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 + restThe function does four things:
- It separates system messages from everything else, so the bot's instructions are never dropped.
- It slices the last
max_messagesentries from the rest withrest[-max_messages:]. - It removes leading messages until the first one has the role
user. - It returns the system messages followed by the trimmed conversation.
The third step matters because many providers expect a conversation to start with a user message. A cut in the middle of a turn can leave an assistant reply at the front. The loop removes it.
Worked example
Suppose the history holds a system message and six conversation messages.
history = [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
{"role": "user", "content": "u2"},
{"role": "assistant", "content": "a2"},
{"role": "user", "content": "u3"},
{"role": "assistant", "content": "a3"},
]
print([m["content"] for m in trim_history(history, 4)])
print([m["content"] for m in trim_history(history, 3)])The first call prints ['You are concise.', 'u2', 'a2', 'u3', 'a3']. Four messages fit, and the window starts on a user message.
The second call prints ['You are concise.', 'u3', 'a3']. A window of three would start at a2, so the loop drops it and the result has only two conversation messages.
Where to call it
Trim a copy for the request and keep the full list for saving, or trim the list itself if you do not need old turns. Both work. This version trims only what you send:
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 replyHere history keeps everything, so a later /save stores the whole conversation. The model sees only the window.
Common errors
- Counting messages, not tokens. Twenty short messages and twenty long ones use very different amounts of context. A message count is a rough guide. If your messages vary a lot, measure tokens with your provider's tokenizer.
- Choosing an odd
max_messages. An odd limit often lands on an assistant reply, so the loop drops one more message than you expected. An even number keeps whole user and assistant pairs. - Forgetting the system message. If you slice the whole list, the instructions disappear and the bot's behavior changes without any error.
- Losing facts. A fact stated in turn one is gone once it leaves the window. The bot will not know it. Summarization, covered in a later chapter, addresses this.
Exercise
A history has one system message and eight conversation messages that alternate user, assistant, starting with a user. You call trim_history(history, 5). How many conversation messages does the result contain, and why?
Show answer
Four. The last five messages start with an assistant reply, because the eight messages end on an assistant and counting back five lands on one. The loop drops that reply, leaving the final two user and assistant pairs, which is four messages.