Token Counting Context Window Management for LLM Apps
Token counting and context window management keep LLM apps inside their limits. Learn to count tokens, budget the window and trim history before it overflows.
By Galactic News Editorial · Published 2026-11-26T23:01:15+00:00 · Updated 2026-11-26T23:01:15+00:00
Token counting context window management is the skill that keeps LLM apps working. Every model reads text as tokens, not words. Every context window has a hard limit in tokens. When your prompt grows past that limit, the API rejects the call or cuts your history. Counting tokens before you call the API prevents both failures. This guide shows how tokens work, how to count them exactly, and how to manage a context window that keeps growing.
Token Counting Context Window Management Starts With the Tokenizer
A token is a subword unit produced by a tokenizer. Most modern models use Byte Pair Encoding, known as BPE. The algorithm starts with single bytes. It merges the most frequent adjacent pairs until the vocabulary reaches its target size. GPT-4's tokenizer holds around 100,000 tokens. Common English words become single tokens. Rare words, misspellings and non-English text split into several tokens.
That split is why word counts mislead. As a rough rule, one token equals about 0.75 words in English. One hundred tokens hold about 75 words. A full page of text runs near 500 tokens. Code costs more per character than prose. Non-English text costs more than English. Never estimate cost or capacity from word counts alone.
Different model families use different tokenizers. Never assume counts transfer between providers. GPT-4o uses the o200k_base encoding. GPT-4 and GPT-3.5 Turbo use cl100k_base. Open-weight models ship their tokenizer with the weights. Count with the tokenizer your model actually uses, or use the provider's own counting API when the tokenizer is not public.
How to Count Tokens Before You Call the API
The standard tool for OpenAI models is tiktoken, a fast open-source tokenizer library from OpenAI. Install it, load the encoding for your model, encode the text, and take the length of the list. That is the whole job for plain text.
- Install tiktoken. Run
pip install tiktokenin your project environment. - Load the right encoding. Use
tiktoken.encoding_for_model("gpt-4o")and let the library pick the encoding. For a named encoding, usetiktoken.get_encoding("o200k_base"). - Encode and count. Call
enc.encode(text)and takelen()of the result. That number is the token count for that string. - Count whole message lists, not single strings. Chat APIs add overhead per message. The OpenAI cookbook rule is 3 tokens per message, 1 more for a name field, and 3 tokens to prime the assistant's reply. Count the full list with the same rule, or your budget will drift low.
- Serialise tool calls and structured fields before counting. Tool result payloads can be large. They are often the hidden source of budget overruns. Convert them to JSON text first, then count.
A short helper makes this routine. Define a function that takes a messages list and a model name, loads the encoding, adds the per-message overhead, and returns the total. Call it before every API request. Log the count with the request. When a call fails on length, the log shows exactly which part grew.
For non-OpenAI models, use the matching tool. Anthropic and Google publish counting endpoints and SDK helpers. Hugging Face's tokenizers library counts exactly for open-weight models, because the tokenizer ships with the model weights. In JavaScript, gpt-tokenizer gives the same token IDs as tiktoken for OpenAI encodings without WebAssembly. Pick the counter that matches the model. A close estimate from the wrong tokenizer is worse than no estimate, because it invites false confidence.
Budgeting the Context Window
The context window is one budget shared by input and output. Input tokens plus output tokens must fit inside the model's limit. A model with a 128,000-token window, such as GPT-4o, does not give you 128,000 tokens of input. You must reserve room for the completion. Plan the budget in writing before you build the prompt.
A simple allocation works for most apps. Reserve a fixed slice for the system prompt. Reserve a slice for retrieved context or tool results. Reserve a slice for conversation history. Reserve a slice for the reply. When any slice grows past its cap, trim that slice before the request goes out. The table below shows a typical split for a 128,000-token window.
| Budget slice | Tokens | Share | Notes |
|---|---|---|---|
| System prompt | 2,000 | 2% | Fixed instructions, rarely changes |
| Retrieved context | 40,000 | 31% | RAG chunks, capped by relevance |
| Conversation history | 60,000 | 47% | Trimmed oldest-first or summarised |
| Tool results | 16,000 | 12% | Serialised to JSON, capped per call |
| Reserved for reply | 10,000 | 8% | Never spent on input |
Track usage per session, not just per call. A chat that fits today may overflow tomorrow as history grows. Store the running total with the session. Check it before each new turn. When the total crosses a threshold, such as 80 percent of the window, trigger your trimming strategy early. Waiting for the error costs a failed request and a broken conversation.
When the Window Fills: Trimming, Summarising and Retrieval
Four strategies handle a full window. Each fits a different app.
Sliding window. Drop the oldest messages first and keep the most recent turns. This fits support chats and short tasks. Keep the system prompt and the first user message if they carry the goal. Drop middle turns first when the goal lives at the start.
Summarisation. Compress old turns into a short summary and keep the summary in context. This fits long conversations where the history matters but the exact words do not. Summarise on a schedule, not on failure. A summary written under pressure reads worse than one written with room to spare.
Retrieval. Store the full history outside the window and pull back only the relevant parts. This fits RAG apps and long documents. Chunk documents by token count, not by paragraph length. A chunk that fits the budget is useful. A chunk that overflows is not.
Prompt compression. Cut filler from the system prompt and from retrieved chunks. Remove repeated instructions. Shorten examples. Every token you remove from the prompt is a token you can spend on history or on the reply.
Most production apps combine two or more of these. A common pattern is retrieval plus a sliding window: pull the relevant chunks, keep the last few turns, and summarise the rest. Test the combination on real conversations before you ship it. A strategy that works on short test chats can fail on the tenth turn of a real one.
Common Mistakes to Avoid
Five mistakes cause most token-counting failures. First, counting words instead of tokens. Second, counting a single string and forgetting message overhead. Third, forgetting that the reply also consumes the window. Fourth, using one model's tokenizer to count for another model. Fifth, letting tool results grow without a cap.
One more trap hides in the cache. The first call to an encoding downloads its vocabulary file, a few megabytes, from public storage and caches it locally. In containers or serverless functions without internet access, that download fails. Set the cache directory to a folder you ship with the app and warm it at build time.
Bottom Line
Token counting context window management comes down to three habits. Count with the model's own tokenizer before every call. Budget the window in writing, with room reserved for the reply. Trim early with a strategy that fits your app, before the API rejects the request. Build those habits into a small helper class that tracks the budget and trims history. Your LLM app will fail less, cost less, and behave the same on turn ten as it did on turn one.