Sub topic 11
Keeping context within budget
Earlier chapters showed that every call must fit inside the context window and that the whole history is resent on each turn. This chapter covers what to do when a conversation or document set grows past what you want to send. It assumes you can read basic Python, have called a chat API, and know that input plus output tokens must fit the window.
Why you manage context yourself
A model has no memory between calls. The API receives whatever messages you put in the request, and nothing else. This has two consequences:
- You decide what the model sees. Dropping a message removes it completely from the model's view.
- You pay for what you send. A long history costs input tokens on every turn.
Context management means choosing which tokens go into each request. There are three basic strategies:
| Strategy | What it does | Main risk |
|---|---|---|
| Trimming | Drops the oldest messages | The model forgets early facts |
| Summarizing | Replaces old messages with a short summary | The summary loses detail, and it costs an extra call |
| Retrieval | Sends only the pieces of a large source that match the question | The search may miss the relevant piece |
Real systems often combine them. The diagram below shows one way to choose.
Set the budget first
Every strategy needs a number to aim at. Start from the window and subtract what you must reserve:
history budget = context window - max output tokens - system prompt tokensYou may also want to keep some headroom below that figure. Token counts from a tokenizer library can differ slightly from what the provider counts, because providers add a few tokens of formatting for each message. A safety margin of a few percent avoids rejected requests.
Your budget can also be lower than the window. A model with a 200,000-token window does not oblige you to send 200,000 tokens. Many teams set a cost budget (for example, 20,000 input tokens per call) well below the window.
Strategy 1: trimming
Trimming keeps the newest messages and drops the oldest. The function below walks backwards from the newest message and stops when the budget is used up. It takes the counting function as an argument, so you can pass in a tokenizer-based counter.
def trim_history(messages, count_tokens, budget):
kept = []
used = 0
for message in reversed(messages):
n = count_tokens(message)
if used + n > budget:
break
kept.append(message)
used += n
return list(reversed(kept))
messages = ["one two three", "four five", "six seven eight nine"]
words = lambda m: len(m.split()) # stand-in counter: one word = one token
print(trim_history(messages, words, 6))
# ['four five', 'six seven eight nine']Two details matter:
- The loop stops at the first message that does not fit. It never skips a large message to keep an older small one, so the kept messages are always an unbroken run of recent turns.
- The loop only looks at messages. It does not know which ones are important.
Pin the system prompt and fix the start
A real request needs more than the trimming loop. The system prompt must always survive, because it holds your instructions. Most chat APIs also expect the first non-system message to come from the user, so a trimmed history that starts with an assistant reply can be rejected or confuse the model. This version handles both:
def trim_history(messages, count_tokens, budget):
kept = []
used = 0
for message in reversed(messages):
n = count_tokens(message)
if used + n > budget:
break
kept.append(message)
used += n
return list(reversed(kept))
def build_prompt(system, messages, count_tokens, window, max_output):
budget = window - max_output - count_tokens(system)
if budget < 0:
raise ValueError("system prompt and max output exceed the window")
kept = trim_history(messages, count_tokens, budget)
while kept and kept[0]["role"] != "user":
kept.pop(0) # never start the history with an orphaned reply
return [system] + kept
def msg(role, n_words):
return {"role": role, "content": " ".join(["w"] * n_words)}
# Stand-in counter: words plus 4 tokens of per-message formatting overhead.
count = lambda m: len(m["content"].split()) + 4
system = {"role": "system", "content": "You are terse."}
history = [
msg("user", 10), msg("assistant", 8),
msg("user", 10), msg("assistant", 8),
msg("user", 5),
]
prompt = build_prompt(system, history, count, window=60, max_output=20)
print([m["role"] for m in prompt]) # ['system', 'user']Here the budget is 60 - 20 - 7 = 33. The loop keeps the last assistant reply (12) and the last user message (9), then stops because the next message (14) would exceed the budget. The kept run starts with an assistant reply, so the while loop removes it. Only the final user message remains. That is a lot of lost history for a small budget, which is the cost of trimming.
If the system prompt alone leaves no room, raise an error. Silently sending a truncated system prompt is a harder bug to find.
Trimming problems to expect
- Lost facts. If the user gave their name or a constraint in turn 1, trimming erases it. Pin such facts in the system prompt or in a separate "notes" message that is never trimmed.
- Broken tool exchanges. In tool-using conversations, a tool result must stay with the assistant message that requested it. Trim in whole exchanges, not single messages.
- Cache misses. Each trim changes the start of the prompt. Prompt caching depends on an identical prefix, so a window that slides by one message every turn defeats it. Trimming in larger steps, such as dropping the oldest ten turns at once, keeps the prefix stable between trims.
Strategy 2: summarizing
Summarizing replaces old messages with a short digest, usually produced by a cheaper model. The model keeps the gist of the early conversation at a fraction of the token cost.
def compress(messages, count_tokens, budget, summarize, keep_recent=4):
"""Return (summary, recent_messages). summary is None if nothing changed."""
total = sum(count_tokens(m) for m in messages)
if total <= budget:
return None, messages
split = max(len(messages) - keep_recent, 0)
old, recent = messages[:split], messages[split:]
if not old:
return None, recent
return summarize(old), recent
chat = ["m1", "m2", "m3", "m4", "m5", "m6"]
summary, recent = compress(
chat,
count_tokens=lambda m: 10,
budget=40,
summarize=lambda old: f"{len(old)} earlier messages condensed",
)
print(summary) # 2 earlier messages condensed
print(recent) # ['m3', 'm4', 'm5', 'm6']The six messages cost 60 tokens against a budget of 40, so the function summarizes everything except the last four. In production, summarize would call a model with a prompt such as "Summarize this conversation. Keep names, decisions, and open questions." You would then place the summary in the system prompt or a note message above the recent turns.
Summarizing has its own costs:
- It adds an extra call, with its own input and output tokens. It pays off only when the summary is reused over many later turns.
- Detail is lost. Numbers, code, and exact wording are the first to go, so tell the summarizer what to keep.
- Summaries of summaries drift. After several rounds, errors compound. For long sessions, re-summarize from the original messages when you can, or keep a structured notes list instead of free text.
A common compromise is a rolling window: keep the last N turns verbatim, keep one summary of everything older, and re-summarize only when the verbatim part reaches a threshold.
Strategy 3: retrieval
When the source is large, such as a manual or a ticket archive, no amount of trimming helps. Retrieval splits the source into chunks ahead of time, scores each chunk against the current question, and sends only the best ones. The sketch below uses word overlap as the score. Production systems usually score with embeddings (numeric vectors that capture meaning), but the budget logic is the same.
import re
def words_of(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
def select_chunks(question, chunks, count_tokens, budget):
q = words_of(question)
ranked = sorted(chunks, key=lambda c: len(q & words_of(c)), reverse=True)
picked, used = [], 0
for chunk in ranked:
n = count_tokens(chunk)
if used + n > budget:
continue # skip chunks that do not fit, try smaller ones
picked.append(chunk)
used += n
return picked
chunks = [
"Refunds are issued within 14 days of purchase.",
"Our office is closed on public holidays.",
"To request a refund, email support with your order number.",
]
count = lambda c: len(c.split())
print(select_chunks("How do I get a refund within 14 days", chunks, count, 18))
# ['Refunds are issued within 14 days of purchase.',
# 'To request a refund, email support with your order number.']Unlike trimming, this loop uses continue, not break. Retrieved chunks are independent, so a chunk that is too large should be skipped while smaller, lower-ranked ones can still fit.
Retrieval fails when the right chunk is never selected, and the model then answers from nothing or guesses. Test your retrieval step on its own, with questions whose answers you know. Chunk size also matters. Chunks that are too small lose surrounding context, and chunks that are too large waste budget.
Verify with real counts
Estimates drift, so check your trimming against the usage numbers the API returns. After each call, compare the reported input token count with what your counter predicted. A consistent gap tells you how large a safety margin to use. Log the reported counts per turn during development, and you will see quickly whether your budget logic holds.
Choosing a strategy
- Short chats that end quickly need no management beyond the window check.
- Support or assistant chats where only recent turns matter suit trimming, with the key facts pinned.
- Long working sessions where early decisions matter suit a rolling summary plus recent turns.
- Question answering over large documents suits retrieval, often combined with trimming for the chat part.
Exercise
A model has an 8,000-token window. You reserve 1,000 tokens for output, and the system prompt is 500 tokens. Each user message is 100 tokens and each reply is 300 tokens, so each full turn adds 400 tokens. Using trim_history with whole messages, what is the history budget, and how many complete turns (user message plus reply) fit if the next user message is also included in the history?
Show answer
The history budget is 8,000 - 1,000 - 500 = 6,500 tokens. The newest user message takes 100, leaving 6,400. Each earlier complete turn takes 400, and 6,400 / 400 = 16, so 16 earlier complete turns fit alongside the new message (16 x 400 + 100 = 6,500 tokens, exactly the budget). Because the loop walks backwards, it keeps the new user message, then reply and user message pairs back through 16 turns, and drops everything older.
Exercise
Why does selectchunks use continue when a chunk does not fit, while trimhistory uses break?
Show answer
Chat messages form an ordered conversation, and skipping a message in the middle would leave gaps that confuse the model, so trim_history stops at the first message that does not fit and keeps an unbroken recent run. Retrieved chunks are independent of each other, so skipping a large chunk and still adding smaller, lower-ranked ones that fit is safe and uses the budget better.