Managing the LLM Context Window: Token Budget and Compression Strategies
Summary
Describes the methodology for calculating token budgets for LLM requests, context compression strategies, and practical techniques to stay within context window limits.
Why Manage Context
The model's context window is limited. Exceeding the limit leads to errors or data truncation. Managing the token budget reduces query costs and improves response quality by preventing the model from losing important information. Basic concepts are in the glossary context-window and token-budget.
Step 1. Determine Model Limits
Each model has its own context size. Examples:
| Model | Context (tokens) |
|---|---|
| GPT-4o mini | 128 000 |
| DeepSeek V3 | 64 000 |
| Claude 3.5 Sonnet | 200 000 |
| Llama 3.1 8B | 128 000 |
Check the latest limits in the provider's documentation. For local models, see model-card.
Step 2. Count Tokens in the Request
Use the provider's tokenizer. For OpenAI, use tiktoken:
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
tokens = enc.encode("Query text")
print(len(tokens))
For other models, use the corresponding tokenizers from Hugging Face.
Step 3. Set the Budget
The budget is the maximum number of tokens I allocate for a request. Formula:
budget = context_limit - reserve_for_response
The reserve for the response is usually 10–20% of the limit. For example, for a model with a context of 64 000 tokens and a response up to 8 000 tokens, the budget for input is 56 000 tokens.
Step 4. Break the Context into Parts
If the data exceeds the budget, break it into parts. For RAG, use chunks — see rag-chunk-size. For dialogue, limit the history to the last N messages.
Example function for trimming history:
def trim_history(messages, max_tokens, enc):
total = 0
trimmed = []
for msg in reversed(messages):
msg_tokens = len(enc.encode(msg["content"]))
if total + msg_tokens > max_tokens:
break
trimmed.append(msg)
total += msg_tokens
return list(reversed(trimmed))
Step 5. Apply Context Compression
Compress long fragments before sending. Methods:
- Summarization — the model briefly summarizes old messages.
- Extract key facts — leave only important entities.
- Remove stop-words — for technical texts.
Example prompt for compression:
Compress the following dialogue to 200 tokens, preserving key facts and decisions:
<dialogue>
Step 6. Use Prompt Caching
If the system prompt and part of the context repeat, enable prompt-caching. This reduces costs and speeds up processing. More details in the post llm-prompt-caching-practice.
Step 7. Monitor Usage
Log the number of tokens in each request. Save prompt_tokens, completion_tokens, total_tokens from the API response in metrics. Send an alert if the threshold is exceeded. Tools — langfuse or helicone.
Step 8. Test on Edge Cases
Check behavior with a full context:
- Request with maximum budget.
- Request with trimmed history.
- Request with a long document.
For testing, use the mock server from the guide llm-api-mock-testing.
Conclusion
Managing the context window involves calculating the budget, trimming and compressing data, caching, and monitoring. These practices reduce costs and improve response quality. More on caching strategies in the post llm-cache-strategies, on API limits in the guide llm-api-rate-limit-budgeting.