Sub topic 4
Keeping the buffer inside the token budget
This chapter assumes you know basic Python and have called a chat-style LLM API. You should also know that the context window is the maximum number of tokens a model can read in one call.
Why the buffer needs a limit
The conversation buffer is the list of messages you send on every call. It grows with each turn. The window is fixed, so a long chat eventually fails or becomes expensive. You need a rule for what to drop.
The simplest rule is to keep the system message and the newest messages, and drop the oldest turns first. Recent turns usually matter most for the next reply.
A token-budgeted trimmer
def trim_messages(messages, max_tokens, count_tokens):
"""Keep system messages plus the most recent messages that fit the budget."""
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_tokens - sum(count_tokens(m["content"]) for m in system)
kept = []
for m in reversed(rest):
cost = count_tokens(m["content"])
if cost > budget:
break
kept.append(m)
budget -= cost
return system + list(reversed(kept))
# Rough stand-in for a real tokenizer
count = lambda text: len(text.split())
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "My name is Priya."},
{"role": "assistant", "content": "Nice to meet you, Priya."},
{"role": "user", "content": "What is a context window?"},
]
print(trim_messages(history, max_tokens=14, count_tokens=count))Walk through the numbers. The system message costs 5, leaving a budget of 9. The newest message costs 5, leaving 4. The assistant reply costs 5, which is more than 4, so the loop stops. The output holds the system message and the final question. Priya's name is gone from the prompt.
Details that cause bugs
- Use
break, notcontinue. If you skip a large message and keep an older small one, the history has a hole. The model sees replies without the questions they answered. - Count with the real tokenizer. The word count above is only a stand-in. Words and tokens differ, and each message also carries a few tokens of formatting overhead.
- Reserve room for the answer. The window holds the prompt and the model's output together. Pass
max_tokensas the window size minus the output you want to allow. - Watch the system message. If it alone exceeds the budget,
budgetgoes negative and every other message is dropped. Check for this and fail loudly. - Keep tool calls paired. If your messages include tool calls and tool results, dropping one without the other usually causes an API error. Trim them as a unit.
Choosing a budget
A budget smaller than the full window is often better. A smaller prompt costs less and responds faster. It also leaves space for retrieved memories, which you will add to the system message later. Start with about half the window and adjust after testing.
Exercise
In trim_messages, what goes wrong if you replace break with continue, and why does it matter?
Show answer
A large recent message that does not fit would be skipped, but older smaller messages would still be kept. The prompt then contains older turns without the newer turns that follow from them, so the conversation is out of order and incomplete. break guarantees the kept messages form one unbroken run ending at the newest message.