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. You should also be comfortable with Python lists and dictionaries. Here you will learn why history grows without limit, what happens when it exceeds the model's limit, and several ways to keep it under control.
Why history becomes a problem
A chat API is stateless. To keep a conversation going, you resend the full message list on every call. Each turn adds at least two messages: the user message and the assistant reply. The request therefore grows with every exchange.
The model can only read a limited amount of text per request. That limit is the context window. It is measured in tokens, which are chunks of text the model processes. A token is often a short word or a piece of a longer word. Roughly, one token is about four characters of English text, but this varies by language and content.
The window covers more than your history. It usually holds all of these:
- The system message.
- Every earlier user and assistant message you send.
- The new user message.
- The model's reply, whose length is capped by a setting such as
max_tokens.
Some providers count the input and output together against one limit. Others have separate limits for each. Check the documentation for the model you use.
What happens when you exceed the limit
There are two common outcomes, and both are problems.
- The API rejects the request. You get an error that says the prompt is too long, often with the token counts. Your application must handle it, or the user sees a failure.
- The service truncates silently. Some wrappers, frameworks, or hosted products drop the oldest content for you. The conversation continues, but the model no longer sees something you assumed it saw. This is harder to notice.
A third, quieter problem appears well before the limit. Very long contexts can make a model less reliable at using details buried in the middle. Smaller histories are often both cheaper and more accurate.
Strategy 1: Keep the most recent messages
The simplest approach keeps the system message and only the latest messages. This is the function from the chapter's plan:
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:]It is easy to reason about. It has two weaknesses that you should know about.
It can cut a pair in half. If you keep the last 10 messages and the list has an odd structure, the first kept message might be an assistant reply with no user message before it. Some APIs require the first non-system message to be from the user. Anthropic's Messages API, for example, expects the conversation to start with a user turn. To be safe, drop leading assistant messages after slicing:
def trim_history_safe(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"]
kept = others[-max_turn_messages:]
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system_messages + keptIt forgets important early facts. If the user gave their name, a goal, or a constraint in the first turn, a recency window will eventually discard it. The model then behaves as if it was never told.
Strategy 2: Trim by tokens, not message count
Message counts are a rough guide. One message may hold three words and another may hold a pasted document. A token budget is more accurate.
You can count tokens exactly with the provider's tokenizer or counting endpoint, or estimate with a character-based rule. The example below uses the estimate so that it runs with no extra libraries. Replace estimate_tokens with a real counter when accuracy matters.
def estimate_tokens(text):
# Rough rule for English: about 4 characters per token.
return max(1, len(text) // 4)
def message_tokens(message):
# Add a small overhead for the role and message framing.
return estimate_tokens(message["content"]) + 4
def trim_to_budget(messages, budget_tokens):
system_messages = [m for m in messages if m["role"] == "system"]
others = [m for m in messages if m["role"] != "system"]
used = sum(message_tokens(m) for m in system_messages)
kept = []
for message in reversed(others):
cost = message_tokens(message)
if used + cost > budget_tokens:
break
kept.append(message)
used += cost
kept.reverse()
while kept and kept[0]["role"] != "user":
kept.pop(0)
return system_messages + kept
history = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain what a context window is." * 5},
{"role": "assistant", "content": "It is the amount of text a model can read at once." * 5},
{"role": "user", "content": "And what is a token?"},
]
trimmed = trim_to_budget(history, budget_tokens=60)
for m in trimmed:
print(m["role"], "-", m["content"][:40])The function walks backward from the newest message and stops when the budget is full. This keeps the newest content and discards the oldest, which is usually what you want.
Set the budget below the true limit. Leave room for the reply. If the window is 8,000 tokens and you allow replies of 1,000, your input budget should be well under 7,000, because estimates are imprecise.
Strategy 3: Summarize old turns
A summary compresses old messages into a few sentences. The model keeps the gist, and the history stays small. You ask the model itself to write the summary, then replace the old messages with it.
from openai import OpenAI
client = OpenAI()
def summarize(messages):
transcript = "\n".join(f'{m["role"]}: {m["content"]}' for m in messages)
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=[
{"role": "system", "content": "Summarize the conversation in under 100 words. Keep names, goals, decisions, and open questions."},
{"role": "user", "content": transcript},
],
)
return response.choices[0].message.content
def compact(history, keep_recent=6):
system_messages = [m for m in history if m["role"] == "system"]
others = [m for m in history if m["role"] != "system"]
if len(others) <= keep_recent:
return history
old, recent = others[:-keep_recent], others[-keep_recent:]
summary = summarize(old)
note = {"role": "system", "content": "Summary of earlier conversation: " + summary}
return system_messages + [note] + recentNotice that the transcript is passed as a single user message. The old messages are data to be summarized, not turns to continue. That keeps the summarizer from answering the old questions.
Trade-offs of summarizing:
- It costs an extra model call and some latency.
- Summaries lose detail. Exact numbers, code, and wording can be dropped or changed.
- A wrong summary then sits in the history as if it were fact. Errors compound if you summarize a summary repeatedly.
- Text from users or tools that ends up in a summary is still untrusted. If a user message contained an instruction like "ignore your rules," a careless summary can carry it forward inside a system-role message, which gives it more authority than it deserves. Phrase the summary note as a description of what happened, and consider placing it in a user message with clear labeling rather than a system message.
Strategy 4: Pin what matters
Some facts must survive any trimming. Keep them outside the rolling history and add them back each time.
- Put stable rules in the system message, which trimming never touches.
- Store key facts such as the user's name, preferences, or task state in a separate dictionary. Insert them into the system message when you build each request.
def build_request(base_system, pinned_facts, history, max_turn_messages=10):
facts = "\n".join(f"- {k}: {v}" for k, v in pinned_facts.items())
system = base_system + "\n\nKnown facts:\n" + facts
recent = trim_history_safe(
[m for m in history if m["role"] != "system"], max_turn_messages
)
return [{"role": "system", "content": system}] + recent
pinned = {"user_name": "Priya", "language": "Python"}
history = [{"role": "user", "content": "How do I read a file?"}]
print(build_request("You are a coding tutor.", pinned, history))Only store facts you have verified or that the user stated directly. A pinned fact is repeated forever.
Choosing a strategy
| Strategy | Keeps | Cost | Main risk |
|---|---|---|---|
| Last N messages | Recent turns | None | Forgets early facts, may split pairs |
| Token budget | Recent turns that fit | Token counting | Estimates can be off |
| Summarize | Gist of everything | Extra call | Lost or distorted detail |
| Pinned facts | Chosen key facts | Bookkeeping | Stale or wrong facts persist |
Real applications often combine them: pinned facts in the system message, a summary of older turns, and a token-budgeted window of recent messages.
Edge cases and gotchas
- Few-shot examples. If you use user and assistant pairs as examples, they live in the history too. A recency trim will delete them first. Keep examples in a separate list and put them before the trimmed history.
- Tool messages. A tool result must stay with the assistant message that requested it. If you drop one and keep the other, many APIs return an error. Trim them as a unit.
- Large single messages. One pasted document can exceed your whole budget. Trimming by messages cannot fix that. Truncate or chunk the content before adding it.
- Reply space. Always reserve room for the reply. A full input window leaves the model no space to answer, and the output is cut off.
- Estimates differ by model. Different models use different tokenizers. The same text may count differently, so use the counter for the model you call.
- Stored vs sent history. You can store the complete conversation for your own records and send only a trimmed view. Trimming the sent copy does not have to delete anything permanently.
Putting it together
A request-building function can apply each step in a fixed order. This version keeps a full log, builds a trimmed view, and sends only that view.
from openai import OpenAI
client = OpenAI()
SYSTEM = {"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."}
full_log = [] # complete record, never trimmed
def chat(user_text, budget_tokens=3000):
full_log.append({"role": "user", "content": user_text})
request_messages = trim_to_budget([SYSTEM] + full_log, budget_tokens)
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=request_messages,
max_tokens=300,
)
reply = response.choices[0].message.content
full_log.append({"role": "assistant", "content": reply})
return replyThis function reuses trim_to_budget from earlier. The log keeps everything, and the model sees only what fits.
Exercise
A chat app keeps only the last 10 non-system messages. After a long session, the assistant forgets that the user said they are allergic to peanuts in the first turn. Name two changes that would fix this, and one risk of each.
Show answer
Option 1: pin the fact. Store "allergy: peanuts" in a facts dictionary and add it to the system message on every request. Risk: if the fact is recorded wrongly or becomes outdated, it is repeated on every turn. Option 2: summarize older turns into a short note that keeps key facts, and send it with the recent messages. Risk: the summary may drop or distort the detail, and an error persists as if it were true.
Exercise
Your trim function slices the last 7 non-system messages and sends them to an API that requires the first non-system message to be from the user. The call sometimes fails. What is the likely cause, and how do you fix it?
Show answer
With an odd count, the slice can start on an assistant message because user and assistant messages alternate. The API then rejects the request. Fix it by removing leading non-user messages after slicing, as in trimhistorysafe, or by trimming in whole user and assistant pairs.