Sub topic 4
Keeping the buffer inside the token budget
This chapter assumes you can read basic Python, have called a chat-style LLM API, and know that a prompt is a list of role-tagged messages. It builds on the previous chapter on the conversation buffer. That buffer grows every turn, and the model's context window does not.
The budget is smaller than the window
The context window is the maximum number of tokens the model accepts in one call. Your usable history budget is smaller, because several things share the window with the conversation.
| Item | Counts against the window? | Notes |
|---|---|---|
| System prompt | Yes | Sent on every call, so it is a fixed cost. |
| Retrieved long-term memories | Yes | Added each turn, so the size varies. |
| Tool definitions | Yes | Often hundreds to thousands of tokens. |
| Conversation history | Yes | The part you trim. |
| Current user input | Yes | Never trim this away. |
| Model output | Yes | You must reserve room for it. |
Many providers return an error when input plus the requested maximum output exceeds the window. Others silently truncate. Either outcome is bad, so compute the budget before every call:
history_budget = context_window - reserved_output - system - tools - memories - current_inputA budget is useful only if you can count against it. The word-count function in this chapter is a stand-in. In production, use the tokenizer that matches your model, or the token counts the provider reports in its API responses.
The trimming algorithm
The simplest policy is a sliding window. Keep the system message, then walk backward from the newest message and keep messages until the budget runs out. The oldest turns are dropped first, because recent turns usually matter most for the next reply.
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))Tracing the example
With the word-count tokenizer, the costs are:
- The system message costs 5, so the remaining budget is 14 - 5 = 9.
- The newest message, "What is a context window?", costs 5. It fits, and the budget drops to 4.
- The assistant reply costs 5, which is more than 4. The loop stops.
The result is the system message plus the final question. The model no longer sees "My name is Priya." This is the core limitation of a sliding window: a fact stated early is lost once it scrolls out, even if it would have mattered. Summarization (next chapter) and long-term memory exist to address this.
Edge cases
The function above is correct for plain text turns. Real agents hit these cases.
Why `break` and not `continue`
When a message does not fit, the code stops. If it skipped that message and continued, a small older message could be kept while a larger newer one was dropped. The prompt would then have gaps, such as an answer without its question.
The system message alone is too large
If the system messages cost more than max_tokens, budget starts negative and no history is kept, with no warning. Treat that as a configuration error and raise one.
A single message exceeds the whole budget
A pasted document or a large tool result can exceed the budget on its own. The loop then keeps no history at all, including the current user input. Handle this before trimming: truncate the content, store it elsewhere and pass a reference, or summarize it.
Per-message overhead
Chat APIs add formatting tokens for each message, such as role markers. Counting only content underestimates the real cost. Add a small constant per message, or use the provider's own counting method.
Orphaned replies and tool results
Trimming can leave a history that begins with an assistant reply, or with a tool result whose tool call was dropped. Some APIs reject such histories, and models can be confused by them. A common fix is to remove leading messages until the history starts with a user message. For tool calls, drop the call and its result together, as one unit.
A more careful version
This version reserves room for the output, counts per-message overhead, fails loudly when the system messages are too large, and removes orphaned leading replies.
def trim_to_budget(messages, context_window, reserve_output, count_tokens,
per_message_overhead=4):
limit = context_window - reserve_output
def cost(m):
return count_tokens(m["content"]) + per_message_overhead
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = limit - sum(cost(m) for m in system)
if budget < 0:
raise ValueError("System messages alone exceed the token budget")
kept = []
for m in reversed(rest):
c = cost(m)
if c > budget:
break
kept.append(m)
budget -= c
kept.reverse()
# Do not start the history with an assistant or tool message
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system + kept
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?"},
]
result = trim_to_budget(history, context_window=30, reserve_output=10,
count_tokens=count, per_message_overhead=1)
for m in result:
print(m["role"], "->", m["content"])Here the limit is 20, and each message costs its word count plus 1. The system message costs 6, leaving 14. The question costs 6, leaving 8. The assistant reply costs 6, leaving 2. The first user message costs 5 and does not fit, so the loop stops. The kept list starts with the assistant reply, so the cleanup loop removes it. The final prompt is the system message plus the question. The assistant reply fit within the budget but is dropped anyway, because a history that starts with an assistant turn is malformed.
Choosing a policy
A sliding window is not the only option. Pick based on what the agent needs to preserve.
| Policy | Keeps | Main risk |
|---|---|---|
| Sliding window by tokens | Newest turns | Early facts vanish. |
| Fixed number of messages | Last N turns | Cost varies widely, so long messages can still overflow. |
| Drop large tool outputs first | More turns of dialogue | The agent loses evidence it may need later. |
| Summarize old turns | A compressed form of everything | Extra model call, and details can be lost. |
A fixed message count is simple but unsafe as the only control, because ten messages can be 200 tokens or 20,000. A token budget is the safer limit. You can combine both: apply a message cap, then enforce the token budget as the final check.
Common errors
- Trimming after the call fails. Trim before sending, every turn.
- Forgetting to reserve output tokens, which causes truncated replies or API errors.
- Using a different tokenizer from the model's, such as word count or a counter for another model family. Leave a safety margin, for example 5 to 10 percent, when the count is only an estimate.
- Recomputing the trim and mutating the stored history. Trim a copy for the prompt, and keep the full log elsewhere. You may want it for summarization or for long-term memory writes later.
- Trimming away the current user input because retrieved memories were added first. Reserve space for the input before filling the rest.
Exercise
Using the word-count tokenizer and the trim_messages function from this chapter with the four-message history, which messages are kept when max_tokens=19? Why would continue instead of break change the result when max_tokens=11?
Show answer
With maxtokens=19, the system message costs 5, leaving 14. The question costs 5 (budget 9), the assistant reply costs 5 (budget 4), and "My name is Priya." costs 4 (budget 0), so all four messages are kept. With maxtokens=11, the budget after the system message is 6. The question costs 5, leaving 1. The assistant reply costs 5 and does not fit. With break, the loop stops and only the question is kept. With continue, the loop skips the reply, then the user message "My name is Priya." costs 4, which also does not fit in 1. So the result is the same here. The difference appears when an older message is small enough to fit after a larger one is skipped, which would leave a gap in the conversation.
Exercise
Why should the cleanup step in trim_to_budget remove leading assistant messages, and what unit should be dropped together when the history contains tool calls?
Show answer
A history that begins with an assistant reply has no user message it answers, which some APIs reject and which can confuse the model. A tool call and its tool result should be dropped together, because a result with no matching call (or a call with no result) is an invalid or misleading history.