Sub topic 11
Keeping context within budget
This chapter assumes you can read basic Python and have called a chat API. It also assumes you know what a context window is and that a chat resends its history on every turn. Here you will learn three ways to keep that history within budget: trimming, summarizing, and retrieval.
Why history needs managing
A chat resends its full history as input on every call. The history grows each turn, so two limits get closer. The first is the context window, which is a hard limit. The second is the bill, which is a soft one. If the history plus the requested output exceeds the window, the call fails or the provider cuts off the oldest content. Managing context means choosing what to send before that happens.
Strategy 1: trim
Trimming keeps the newest messages and drops the oldest. It is the simplest strategy and costs nothing extra. This function walks backwards from the newest message and stops when the budget is full.
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))You pass in count_tokens, so you can use a tokenizer library or a rough estimate. Use the tokenizer that matches your model. Counts from a different tokenizer are only approximate, so leave a safety margin.
Trimming has two common errors:
- Dropping the system prompt. The system prompt is not part of the chat turns. Count it separately and subtract its size from the budget before you trim.
- Splitting a pair. Some APIs reject a tool result whose matching tool call was trimmed away. Drop messages in whole groups.
The budget should also reserve room for the reply. If the window is 8,000 tokens and you allow 500 output tokens, the history budget is at most 7,500 minus the system prompt.
Strategy 2: summarize
Summarizing replaces old messages with a short summary written by the model. It keeps the key facts, such as names, decisions, and open questions, in far fewer tokens. The cost is an extra LLM call, and details can be lost or distorted.
A common pattern keeps the last few turns word for word and summarizes everything older. Run the summary only when the history crosses a threshold. Summarizing on every turn pays for extra calls without saving much.
Strategy 3: retrieve
Retrieval stores old messages or documents outside the prompt and fetches only the pieces relevant to the current question. You search a store, usually by embedding similarity (comparing numeric representations of meaning) or by keywords. You then add the top few results to the prompt.
Retrieval suits large reference material and very long sessions. It adds complexity, since you must run a search system. It can also miss relevant pieces, in which case the model never sees them.
Comparing the strategies
| Strategy | Extra cost | Keeps exact wording | Main risk |
|---|---|---|---|
| Trim | None | Yes, for recent messages | Forgets early context |
| Summarize | One extra call | No | Lost or wrong details |
| Retrieve | Search system | Yes, for retrieved pieces | Misses relevant pieces |
You can combine them. For example, keep the system prompt, a running summary, the last four turns, and any retrieved documents.
Seeing the effect
Without management, input grows quickly. This function simulates a chat that resends everything.
def total_input_tokens(system_tokens, user_tokens, reply_tokens, turns):
total = 0
history = system_tokens
for _ in range(turns):
history += user_tokens
total += history # the whole history is sent as input on every call
history += reply_tokens
return total
print(total_input_tokens(500, 100, 300, 10)) # 24000Ten turns bill 24,000 input tokens, although the user and the model wrote only 4,000 new tokens. Trimming to a fixed budget caps the per-call input, so total cost grows roughly linearly with turns instead of quadratically.
Exercise
Your window is 8,000 tokens, your system prompt is 600 tokens, and you allow 800 output tokens. What is the largest budget you can pass to trim_history for the chat messages?
Show answer
8,000 - 600 - 800 = 6,600 tokens. In practice, use a little less to leave a margin for tokenizer differences.
Exercise
A support chat must remember a customer's order number from turn 2 at turn 40. Which strategy is riskiest for this, and what would you do about it?
Show answer
Trimming is riskiest because turn 2 is dropped first. Store the order number outside the history, for example in the system prompt or a pinned message, so it is sent on every call.