Context-window overflow is rarely solved by deleting the oldest message at random. A reliable LLM application measures tokens before sending a request, reserves space for the response, assigns each context item a priority, and uses truncation or summarization when the budget is tight. This guide explains how to estimate a usable context budget, design conversation memory, handle retrieved documents and tool results, and create a workflow you can revisit whenever a model, prompt, or data source changes.
Overview
An LLM context window is the maximum amount of tokenized input and output that a model can process in one request. The exact limit depends on the model and API configuration, and token counts vary with the language, formatting, code, and tokenizer. Characters and words are therefore useful for rough planning, but they are not reliable substitutes for tokenizer-based counting.
Context management has two separate goals:
- Fit: Keep the request within the model’s input and output limits.
- Usefulness: Keep the most relevant instructions, conversation turns, retrieved passages, and tool results rather than filling the window with low-value text.
A large context window does not remove the need for prioritization. Extra content can increase latency, cost, distraction, and the chance that the model overlooks an important instruction. Treat context as a limited working budget, not as a document dump.
A practical request often contains these components:
- System instructions and safety constraints
- Developer instructions or application rules
- Conversation history
- Retrieved passages or uploaded documents
- Tool definitions and tool results
- The current user request
- Reserved output space
For related production practices, see the LLM observability guide, which covers tracing prompts, token use, latency, and failed responses.
How to estimate
Start with a context-budget worksheet for every model or endpoint your application uses. Define the model’s maximum context capacity as C. Then estimate the input components and reserve output space:
usable_input_budget = context_limit - reserved_output_tokens - safety_marginThe input must satisfy:
system + developer + history + retrieval + tools + user_message <= usable_input_budgetThe safety margin protects against counting differences, wrapper content added by an SDK, tool-call formatting, and small changes in the request. It should be an explicit configuration value rather than an unexplained emergency truncation.
A repeatable token-counting workflow
- Identify the exact model and request format. Tokenization can differ between model families, and chat APIs may add message or tool metadata.
- Count each component separately. Measure system instructions, history, retrieved text, tool definitions, tool output, and the current message.
- Reserve the completion budget first. Do not spend the entire context on input if the application needs a meaningful answer.
- Apply the safety margin. Begin with a conservative buffer, then adjust it using observed request behavior.
- Prioritize before truncating. Preserve non-negotiable instructions and task-relevant evidence before removing older or redundant content.
- Log the estimate and the final request. Record component-level token counts so overflow is diagnosable rather than mysterious.
Use the tokenizer recommended for the selected model or a provider-supported counting method where available. If exact counting is unavailable before transmission, use an approximation for early filtering and handle the API’s actual response defensively. A request that passes a rough estimate can still fail after serialization.
Allocate the budget by priority
A useful default order is:
- System and developer instructions that govern the application
- Current user request and required output format
- Relevant retrieved passages
- Recent conversation turns needed to interpret the request
- Recent tool results that affect the answer
- Older history, repeated explanations, and low-confidence retrievals
This order is not universal. A coding assistant may need a complete function and its error output; a support assistant may need account state and a small set of recent actions; a research workflow may prioritize cited passages over casual conversation. Define the order per task rather than relying on a single global truncation rule.
Inputs and assumptions
Before implementing context management, document the inputs that drive your estimate. A simple worksheet can include the following fields:
| Input | What to record | Why it matters |
|---|---|---|
| Context limit | Configured model capacity | Sets the upper boundary |
| Output reservation | Maximum or target response tokens | Prevents input from consuming response space |
| System instructions | Token count and version | Usually retained across requests |
| Conversation history | Tokens per turn and retention policy | Grows with every interaction |
| Retrieved content | Number, size, and score of passages | Can spike when documents change |
| Tool content | Schema size and result size | Often adds hidden or overlooked volume |
| Safety margin | Reserved headroom | Absorbs estimation and formatting differences |
For a conversation-memory design, separate short-term memory from durable memory. Short-term memory is the recent transcript needed for the current exchange. Durable memory is a structured record of stable facts, preferences, decisions, or task state that can be retrieved selectively. Do not automatically copy every old message into durable memory. Store only information that has a defined use, provenance, and update rule.
Summaries also need an owner and a format. A useful conversation summary can include the user’s goal, decisions made, unresolved questions, constraints, relevant identifiers, and the evidence supporting each important fact. Avoid a vague paragraph that compresses away distinctions the next turn may require. If the application supports structured outputs, validate the summary before saving it; the structured output guide covers schemas, validation, and recovery patterns.
Retrieved content should be filtered before it enters the prompt. Remove duplicate passages, cap the number of chunks, prefer complete sections over arbitrary character slices, and retain source identifiers. Retrieval should answer the current question, not recreate the entire source collection. Also treat retrieved text as untrusted data: context management and prompt-injection defenses should be designed together. Use the prompt injection defense checklist when external documents or web content are included.
Worked examples
Example 1: A growing support conversation
Assume an application has a configured context capacity of C. Its fixed system and developer instructions use 1,200 tokens, the current user message uses 180 tokens, and the application reserves 1,000 tokens for the response. The team chooses a safety margin of 500 tokens.
The available budget for history and other dynamic content is:
dynamic_budget = C - 1,200 - 180 - 1,000 - 500The application can add recent turns from newest to oldest until that budget is reached. If the next turn would exceed it, the system should first remove repeated greetings or low-value exchanges, then replace an older block with a validated summary. The current request and governing instructions should not be sacrificed merely to preserve a longer transcript.
Example 2: Retrieval plus a tool result
Consider a question-answering workflow that adds retrieved passages and a database tool result. A common failure is to reserve space for the final answer but forget that the tool schema and result are part of the request. A safer sequence is:
- Count the fixed prompt and current question.
- Reserve the expected answer budget.
- Reserve the tool definition and a maximum result size.
- Retrieve candidate passages.
- Trim or rank passages until the remaining budget is safe.
- Call the tool only when it is relevant, and cap or summarize its result before the final response.
If a tool returns a large table, send a filtered projection rather than the complete result. Preserve the columns and rows needed to answer the question, along with enough metadata to explain the result. If the model needs further details, allow a second targeted tool call instead of placing every possible record in the first request.
Truncation and summarization decision table
| Situation | Preferred action | Reason |
|---|---|---|
| Old turns are unrelated | Drop them | They add tokens without task value |
| Old turns contain useful decisions | Summarize with dates and unresolved items | Preserves state in less space |
| Retrieved passages overlap | Deduplicate and rerank | Improves evidence density |
| A tool result is oversized | Filter, paginate, or summarize | Prevents operational data from crowding out instructions |
| A required instruction is oversized | Rewrite and version it | Permanent trimming can change behavior |
Keep truncation and summary events observable. The LLM evaluation guide can help you test whether shorter contexts preserve answer quality rather than merely avoiding errors.
When to recalculate
Recalculate the context budget whenever a model changes, a tokenizer or API format changes, the system prompt is revised, tools are added, retrieval settings change, or users report that the assistant has forgotten recent details. Also revisit it when a document source grows, a new language is introduced, conversation sessions become longer, or response latency and cost move unexpectedly.
Make the process operational:
- Store context limits, output reservations, margins, and truncation policies as versioned configuration.
- Track token counts by component, not only the total.
- Alert on requests approaching the configured threshold.
- Test short, long, multilingual, code-heavy, and tool-heavy conversations.
- Compare answers before and after summarization or retrieval changes.
- Review summary quality and durable-memory records for stale or unsupported facts.
- Re-run the worksheet during model migrations; do not assume token behavior transfers unchanged.
For production changes, pair context-budget updates with prompt release notes and rollback plans. The guide to prompt versioning provides a useful framework for approving and tracking these changes. If an overflow reaches production, use an incident process that distinguishes counting errors, retrieval spikes, tool-result growth, and genuine model behavior changes.
The most reliable pattern is simple: count early, reserve output space, prioritize explicitly, compress only when the content remains verifiable, and measure what the application actually sends. Revisit the worksheet whenever its inputs change. That turns context-window management from a last-minute error handler into a repeatable part of LLM application development.