Sub topic 1
Managing Long Conversations with Truncation and Summaries
Prerequisites
This chapter assumes basic Python, familiarity with chat APIs, and a general idea of tokens. A token is a small piece of text that a model processes.
Why every request carries the whole conversation
Most chat APIs are stateless. The server does not automatically remember earlier requests. Each request must include the system message and the relevant user and assistant messages.
Your application usually stores the conversation, then resends it when the user sends a new message.
This design makes requests reproducible, but the request grows as the conversation grows.
Context windows and what happens when you exceed them
A context window is the maximum number of tokens the model can process in one request. It includes input messages and the space reserved for the generated response.
| Part of a request | Consumes context |
|---|---|
| System instructions | Yes |
| Conversation history | Yes |
| New user message | Yes |
| Generated reply | Reserved space |
When the selected messages exceed the limit, the API may reject the request, truncate it according to provider rules, or leave too little room for a useful reply. Your application should control this behavior instead of relying on an undocumented default.
Counting tokens: exact counts versus estimates
Exact counts require the tokenizer used by the target model. A rough estimate can guide early trimming. Four characters per token is a useful approximation for ordinary English, but code, numbers, and non-English text can differ substantially.
Setting an input budget and reserving room for the reply
Let the model limit be 8,000 tokens. If you reserve 1,500 tokens for the reply, the input budget is 6,500 tokens. Count system messages first, then add recent history until the remaining budget is exhausted.
def estimate_tokens(message):
return len(message["content"]) // 4 + 4
def input_budget(model_limit, reserved_output):
return model_limit - reserved_output
messages = [
{"role": "system", "content": "Answer clearly."},
{"role": "user", "content": "Explain context windows."},
]
budget = input_budget(8000, 1500)
used = sum(estimate_tokens(message) for message in messages)
print("Input budget:", budget)
print("Estimated input:", used)
print("Fits:", used <= budget)The next chapter applies this budget with a sliding window and preserves complete message turns.
Exercise
A model accepts 8,000 tokens, and you reserve 2,000 for output. What is the maximum input budget?
Show answer
6,000 tokens, before accounting for any provider-specific overhead.