Managing Conversation Token Budgets
Introduction
Welcome to Reducing LLM Work and Cost in Python. We begin by moving from observing token usage to actively controlling it in an application. As we learned earlier, local estimates help us plan, while provider-reported usage remains the source of truth for billing.
A conversation request includes previous messages, not just the newest question. Each additional message can increase input tokens and cost, as well as put pressure on the model's context window. In this lesson, we will create a deliberate history budget. We will measure the conversation, keep the most useful recent context, preserve the system instruction, and calculate the savings before sending the request.
Count Tokens for Strings, Messages, and Conversation History
A budget is only useful when it is based on a consistent measurement. We use the supplied o200k_base tokenizer and build the measurement in three layers: one string, one message, and the complete history.
count_tokens() converts text into tokens and returns the number of tokens. message_tokens() applies that helper to both the message's role and content. The role is part of the message representation, so leaving it out would make our budget noticeably too optimistic. history_tokens() adds the cost of every message.
A note on precision. Counting role and content gets us much closer than counting content alone, but it is still a local approximation. For this simple text example, it omits known provider framing, such as message-boundary tokens and provider-supplied system content. It is not a guaranteed mathematical lower bound: different providers, models, endpoint serialization rules, structured content, and tokenizer mismatches can make the provider's count differ in either direction. It is still useful here because we compare a full history against a trimmed one using the same local method. For a hard context-window limit, use a provider-supported token-counting mechanism when available; otherwise reserve a conservative safety margin and reconcile against provider-reported usage afterward.
The complete solution expands the abbreviated history list into seven PostgreSQL messages. The discussion moves from database setup to filters and indexes, then to frequent writes, and finally to the question about what to measure before adding an index. This final question is the message our trimming strategy must protect.
Prioritize Recent Context with a Token Budget
Now we need a rule for deciding which messages stay. We give the conversation a budget of 50 tokens, keep the system instruction separate, and scan the history from newest to oldest.
The trimming process works as follows:
reversed(history)starts with the newest message, which is the final user question.usedtracks the tokens already selected.- A message is kept only when adding it keeps the total within the budget.
continueskips an oversized message but keeps scanning older messages. This allows a shorter, older message to use leftover space. It also means that if the newest user message alone exceedstoken_budget, that message is skipped too, and the history we send can come back empty or without the very question we set out to protect. Production code should treat the latest user message as a mandatory minimum rather than something the budget can drop - see the note below.- The kept messages are reversed again so the model receives them in normal chronological order.
The system message is not passed to trim_history(), so it does not compete with conversation messages for this budget. It remains available to guide the model's behavior.
Scope of this demonstration. The message-by-message selector used in the following trimming practices is intentionally simplified. It can retain an assistant answer without its related user message, retain older context detached from its turn, or omit the newest user request when that request alone exceeds the budget. Production code should reserve space for the latest user request, keep user/assistant turns as indivisible groups, and usually stop when the next older complete turn does not fit.
Visualize the Trimming Flow
The flow below shows how newest-first selection protects the final question while restoring chronological order before the request is sent.

Measure the Effect of Trimming
Selection alone is not enough. We should measure what was retained and what was removed. These lines calculate the full history total, the trimmed total, the number of messages kept, and the token savings.
Each measurement answers a practical question:
- Full history shows the input size before optimization.
- Trimmed history shows how many conversation tokens will be sent.
- Messages kept shows how much of the conversation remains.
- Tokens saved shows the input work removed by trimming.
These values help us choose a budget based on evidence rather than guesswork. A smaller budget can reduce cost and context pressure, but it may remove facts needed for a useful answer. A larger budget preserves more context but sends more input with every request. Because the system message is intentionally excluded, these numbers describe the conversation budget only.
Send the Budgeted Conversation and Interpret the Verified Output
After measuring the history, we send the system instruction followed by the trimmed conversation. The * operator expands the list, so every retained message appears in its original order.
MODEL identifies the model used for the request, and client provides access to the Responses API. The system message is outside the history budget, but it is still part of the provider request. Therefore, it can still contribute to billed input tokens. This distinction lets us protect important instructions while separately controlling conversation history.
When we run the complete solution with the seven-message history and a 50-token budget, it produces this verified output:
The first four lines show the tradeoff clearly: the full history uses 83 tokens, the trimmed history uses 48, four of seven messages remain, and 35 tokens are saved. The response begins with "Before adding it..." because the final question survived the newest-first scan. The answer also uses the preserved discussion about query behavior, index maintenance, and frequent writes, showing why retaining recent context can preserve usefulness while reducing input work.
Because these are local estimates, the request's response.usage.input_tokens will report a somewhat larger number. That gap is the structural overhead described earlier, and comparing the two is a good habit to build now.
Conclusion and Next Steps
We now have a repeatable way to manage conversation context. We count both the role and content of each message, sum those message costs, scan from newest to oldest, skip messages that do not fit, and restore chronological order before sending the request. This protects the latest question while allowing older, shorter messages to fill available space.
We also separated the system instruction from the conversation budget. The instruction remains in the request, even though it is not included in the trimmed history total. Finally, we measured the result instead of assuming the optimization worked. In the following practice, we will implement these helpers, lower the budget from 50 tokens to 25, and verify how the retained messages and savings change while the final question remains available.
