Sub topic 2
Truncating with a Sliding Window
This chapter assumes basic Python, chat API message roles, and the idea that tokens measure text size. A model sees only the messages sent in the current request. Your application must therefore choose which messages fit inside the model's context window.
Truncating with a Sliding Window
A sliding window keeps the newest messages that fit within an input-token budget. New messages enter the window while older messages leave it. Reserve part of the model's context window for the reply.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def truncate_history(messages, max_input_tokens):
pinned = [m for m in messages if m["role"] == "system"]
conversation = [m for m in messages if m["role"] != "system"]
budget = max_input_tokens - sum(estimate_tokens(m) for m in pinned)
kept = []
for message in reversed(conversation):
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 pinned + kept
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain caching."},
{"role": "assistant", "content": "Caching stores reusable results."},
{"role": "user", "content": "Give me an example."},
]
print(truncate_history(messages, max_input_tokens=30))The estimator is only a rough guide. Use the tokenizer for your target model when exact limits matter.
Pinning Important Messages
The system prompt should normally remain in every request. It defines behavior and safety rules. You may also pin a user's requirements, an active task, or a small set of verified facts.
Pinned content consumes budget, so keep it short. Do not pin every interesting message. Pin information the assistant must follow even when older conversation is removed.
> callout note > A sliding window preserves recency, not importance. Pin durable requirements separately from ordinary history.
Preserving Message Boundaries
Never cut through a logical turn. If an assistant message contains a tool call, keep the matching tool result too. Otherwise the API may reject the request or the model may see an incomplete exchange.
For multi-message tool interactions, treat the complete user request, assistant tool call, tool result, and follow-up assistant response as one unit. A production implementation should select these units rather than individual messages.
Summarizing Older Turns
Truncation loses older facts. Before dropping them, send them to a model with a constrained summarization prompt. Preserve goals, decisions, exact values, open tasks, and constraints. Require the summarizer to avoid invented facts and limit the summary's length.
Place the resulting summary after the system prompt and before the recent verbatim messages. This hybrid approach retains long-term context while giving the model precise recent dialogue.
Exercise
Why should a sliding window reserve output space?
Show answer
The model needs room to generate its reply; using the entire context window for input can cause the request or response to exceed the limit.