Long conversations do not need to become long prompts. This guide explains how to manage an LLM context window with repeatable token budgets, selective history, summaries, retrieval, and structured memory—so you can preserve important information without sending every past message on every request.
Overview
An LLM context window is the amount of input and output a model can process for one request. The exact limit depends on the model and provider, and the practical limit may be lower than the advertised maximum once system instructions, tools, retrieved documents, conversation history, and the requested answer are combined.
Context window management is therefore a prompt engineering problem and an application architecture problem. The goal is not simply to remove old messages. It is to decide which information should remain verbatim, which can be compressed, which should be retrieved only when needed, and which should be stored as durable application state.
A useful request budget is:
available input = context limit - reserved output - system prompt - tool and format overhead
For example, if a request has a known context limit, reserve space for the expected answer before adding conversation history. Treat that reservation as a design input rather than allowing the model response to consume the entire remaining window.
| Technique | What it keeps | Strength | Main risk |
|---|---|---|---|
| Truncation | The newest messages or a fixed recent window | Simple and predictable | Older decisions and constraints disappear |
| Rolling summary | A compact summary of earlier turns | Low implementation overhead | Details can be gradually lost or distorted |
| Hierarchical summary | Conversation, topic, and session-level summaries | Preserves multiple levels of context | Requires update rules and testing |
| Retrieval | Relevant past messages or documents on demand | Scales beyond one conversation window | Retrieval can miss or rank the wrong evidence |
| Selective history | Messages chosen by role, topic, or importance | Retains high-value evidence efficiently | Importance rules may be incomplete |
| Structured memory | Facts, preferences, decisions, and tasks in fields | Clear and easy to inspect | Incorrect or stale memory can persist |
Most production systems combine these methods. A recent-message window can support conversational fluency, a rolling summary can cover older discussion, retrieval can recover exact evidence, and structured memory can preserve durable facts.
How to estimate
Start by measuring the request components separately. Do not estimate only from character count: tokenization varies by model, language, punctuation, code, and formatting. Use the tokenizer or usage information associated with the model you are testing, and keep a representative sample of your real prompts.
- Identify the model configuration. Record the model name, provider, context limit, output setting, tool definitions, and response format. Recheck these values when changing models or providers.
- Measure fixed overhead. Count the system instructions, developer rules, tool schemas, output-schema instructions, and other content included on every request.
- Measure variable content. Count recent messages, summaries, retrieved passages, user attachments represented as text, and any generated intermediate state.
- Reserve output space. Set a maximum output budget appropriate to the task. A short classification and a long report should not use the same reservation.
- Add a safety margin. Leave room for formatting variation, metadata, and future prompt changes. The margin should be defined by testing rather than treated as a universal percentage.
Use this worksheet for each request type:
- Context limit:
________tokens - Reserved output:
________tokens - System and developer instructions:
________ - Tool definitions and response format:
________ - Recent conversation:
________ - Summary or structured memory:
________ - Retrieved context:
________ - Safety margin:
________ - Estimated total:
________
Then apply a simple admission rule: add optional context only if the estimated total remains below the request budget. If the budget is exceeded, reduce content in a defined order instead of cutting arbitrary text. A typical order is to remove low-ranked retrieved items, shorten redundant history, refresh the summary, and finally retain only the most recent turns.
Inputs and assumptions
Good context management depends on explicit assumptions. Decide what the assistant must remember, how long that information remains valid, and whether the original wording is necessary.
Classify information before compressing it
- Immediate context: The current request and the last few turns needed to interpret it.
- Task state: Open questions, completed steps, pending actions, selected options, and current errors.
- Durable memory: User preferences or project facts that should survive across sessions.
- Evidence: Exact passages, citations, records, or tool outputs that must be checked rather than paraphrased.
- Noise: Greetings, repeated instructions, acknowledgements, and superseded drafts.
Summaries are appropriate for decisions and themes, but they are not always safe replacements for evidence. If an answer depends on an exact value, quotation, identifier, or policy clause, store the source or retrieve it again. A summary can describe what happened; it may not preserve enough detail to verify what happened.
Use a typed conversation state
{
"goal": "",
"constraints": [],
"decisions": [],
"open_questions": [],
"user_preferences": [],
"recent_turns": [],
"source_refs": [],
"last_updated": ""
}
Give each field an update rule. For example, append a decision only when the user confirms it, remove an open question when it is answered, and attach a source reference when a fact comes from retrieved material. This is safer than asking a model to infer all durable memory from an unstructured transcript.
Design the summary as a contract
A useful summary prompt should specify what to preserve, what to omit, and how uncertainty should be represented. For example:
Summarize the conversation for a later assistant.
Preserve: confirmed decisions, constraints, unresolved questions,
user preferences, identifiers, and required next actions.
Do not invent missing details. Mark uncertain items as uncertain.
Remove greetings, repetition, and superseded drafts.
Return the result under these headings: Goal, Decisions,
Open Questions, Constraints, Next Actions, Evidence References.
Version this instruction like any other production prompt. A summary that is shorter but omits a critical constraint is not an optimization.
Worked examples
Example 1: Recent history plus rolling summary
Suppose a support assistant has a long troubleshooting conversation. The application keeps the latest turns verbatim, while older turns are folded into a summary containing the reported issue, confirmed environment details, attempted fixes, and unresolved questions. When the prompt approaches its budget, the application summarizes the oldest portion again rather than appending another full transcript.
This design is effective when conversational continuity matters more than exact historical wording. Test it with sessions where users change requirements, correct earlier statements, or return to an issue after several unrelated turns.
Example 2: Selective history for a coding assistant
A coding assistant can retain the current task, accepted implementation decisions, active error messages, and the latest relevant code diff. Earlier exploratory suggestions can be dropped after a decision is made. Large files should not be copied into every request; retrieve the relevant functions or symbols based on the current task.
In this case, structured memory records decisions, retrieval supplies exact code, and recent history preserves conversational references such as “the second approach.” Each source should be labeled so the model can distinguish confirmed state from suggestions.
Example 3: Hierarchical summaries for project conversations
For a project spanning many sessions, maintain three levels: a session summary, a topic summary, and a project state. The session summary captures what happened today. Topic summaries cover areas such as requirements, architecture, or unresolved defects. The project state contains only current, confirmed facts.
At query time, retrieve the project state, the relevant topic summary, and a small number of exact source records. This avoids treating every past message as equally relevant while preserving a path back to evidence.
When to recalculate
Revisit your context budget whenever a request begins failing, latency or token usage changes, summaries become less useful, or users report that the assistant forgot an important decision. Also recalculate after changing the model, tokenizer, system prompt, tool schema, response format, retrieval settings, or maximum output.
Run a quarterly review even when the application appears stable. Use representative conversations rather than synthetic short prompts. Measure:
- request and response token usage;
- how often truncation or summarization occurs;
- retrieval recall for known relevant facts;
- preservation of confirmed decisions and constraints;
- summary size, consistency, and update time;
- failure rates near the context budget;
- cost and latency under typical and worst-case sessions.
Keep a small regression set of long conversations with expected facts, decisions, and source references. Compare candidate memory strategies against that set before changing defaults. For broader production checks, pair this work with an LLM evaluation and regression testing workflow and review the cost and latency audit checklist.
Finally, document the active model limits and budget assumptions beside the implementation. When a provider changes context capabilities or API parameters, update the worksheet, rerun tokenizer samples, and test summaries against the regression set. The practical objective is not the largest possible prompt. It is a small, deliberate context that contains the information the model needs to make the next decision.