Sub topic 12
Keeping history within the context window
This chapter assumes you can build a multi-turn loop that appends user and assistant messages to a list, and that you know chat APIs are stateless. If the second point is unfamiliar, review the chapter on why the model only knows what you send each time.
Why history grows
Because the API is stateless, every request carries the whole conversation. After ten exchanges, you send twenty messages plus the system message. The history only gets longer, and each request costs more and takes longer than the last.
The model also has a context window, which is the maximum number of tokens it can read in one request. The limit covers the input messages and the reply together. If the history plus the reply you ask for exceeds it, the API returns an error, or an older provider may cut off input. Tokens are not words. English text averages roughly three-quarters of a word per token, so count tokens, not messages.
Strategy 1: keep the system message and recent turns
The simplest fix is a sliding window. Keep the system message, which holds your instructions, and drop everything except the newest turns.
def trim_history(messages, max_turn_messages=10):
system_messages = [m for m in messages if m["role"] == "system"]
others = [m for m in messages if m["role"] != "system"]
return system_messages + others[-max_turn_messages:]Call it before every request:
response = client.chat.completions.create(
model="MODEL_NAME",
messages=trim_history(history),
)Here history stays complete in your program and only the trimmed copy is sent. That lets you log or display the full conversation later.
A gotcha: cutting in the middle of a pair
Slicing by message count can leave the window starting with an assistant message, because an odd cut separates a user message from its reply. Some APIs require the first non-system message to be a user message. Use an even max_turn_messages so user and assistant pairs stay together, or check the first message after slicing and drop it if its role is assistant.
The sliding window also forgets. If the user stated their name or a constraint in turn 2 and you drop it in turn 20, the model no longer knows it.
Strategy 2: summarize old turns
To keep older facts, ask the model to compress them. When the history passes a threshold, send the oldest turns with a request such as "Summarize this conversation in under 100 words, keeping names, decisions, and open questions." Then replace those turns with the summary, and keep the recent turns word for word.
The summary can go into the system message or into a single message at the start of the history. This costs one extra API call each time you summarize, and the summary can lose detail. It works well for long support chats and poorly when exact wording matters.
Strategy 3: count tokens, not messages
A limit of ten messages is easy to write but unreliable. One pasted document can be larger than fifty short turns. A better check measures tokens against a budget. Libraries such as tiktoken count tokens for OpenAI models, and some providers offer a token-counting endpoint. Counts differ between models, so use the counter that matches your model.
Set the budget below the true limit. Reserve space for the reply (max_tokens on Anthropic requests) and a margin for error. For example, with a 16,000-token window, you might budget 12,000 for input.
| Strategy | Keeps old facts | Extra cost | Main risk |
|---|---|---|---|
| Sliding window | No | None | Forgets early details |
| Summary | Mostly | One extra call per summary | Summary loses detail |
| Token budget | Depends on what you trim | Counting time | Counter differs from model |
Common errors
- Trimming the system message, so the model loses its instructions. Always keep it.
- Counting messages instead of tokens, so a single long message still overflows.
- Forgetting to reserve room for the reply.
- Overwriting
historywith the trimmed list, so the full record is lost.
Exercise
A chat app sends a system message plus the last 10 messages on every request. A user says their name in message 1, and 30 turns later asks "What is my name?" The model cannot answer. Why, and what is one way to fix it?
Show answer
The sliding window dropped message 1, and the API is stateless, so the model never sees it. Fix it by summarizing old turns into a short note that keeps facts such as the name, or by storing key facts and adding them to the system message.
Exercise
Why should you set your input budget below the model's full context window?
Show answer
The window covers input and reply together, so you must leave room for the reply (and a margin for token-count error). Otherwise the request can fail or the reply can be cut short.