Skip to content
NewSecurity Audit for AI-Built Apps. Fixed scope, clear report
GeekTech
AI Engineering

Context Window Management for LLM Chat Apps

Context window management for LLM chat apps: give each request a token budget, keep recent turns verbatim, summarize older ones and test long chats.

7 min read

GeekTech Engineering Team18 years building and securing software

Context window management in an LLM chat app means deciding, on every request, which tokens the model gets to see. Give each part of the request a fixed token budget, keep the latest turns word for word, replace older turns with a structured summary and drop bulky content such as old tool results first. Then test conversations long enough to trigger all of it, because a chat that works for ten turns can fail at fifty.

What counts toward the context window

The context window is the total number of tokens a model can handle in one request, input and output combined. Chat products fill it quickly because every turn resends the whole conversation. Anthropic's context windows documentation lists what counts: the system prompt, every message including tool results, images and documents, the tool definitions, and the output, including the model's thinking.

Two details are easy to miss. Prompt caching changes what you pay for a repeated prefix, but cached tokens still occupy the window. And provider-side state doesn't make history free. OpenAI's conversation state guide says that when you chain responses with previous_response_id, all previous input tokens in the chain are billed as input tokens.

Why long LLM conversations degrade before they fail

A conversation that outgrows the window fails loudly. If the input alone exceeds the model's limit, Anthropic's API rejects the request with a "prompt is too long" error.

The harder problems start much earlier:

  • Quality drops. Anthropic's documentation calls this context rot: as the token count grows, accuracy and recall degrade. An instruction given at turn 4 is easier to miss at turn 60.
  • Latency grows with every turn, because the model reads the full history before it writes anything.
  • Cost grows faster than the conversation. If each turn adds a similar number of tokens and you resend everything, total input grows with roughly the square of the turn count. By simple arithmetic, one 40-turn chat sends close to four times the input tokens of four separate 10-turn chats.

How to set a token budget for each request

Treat the context window as a budget with fixed allocations, and enforce it in code before every call. Here's an example for a model with a 200,000-token window. The numbers are illustrative:

SliceExample budgetWhen it's over budget
Output reserve, including reasoning8,000Never borrow from it
System prompt and tool definitions6,000Load only the tools this step needs
Retrieved context for this turn20,000Retrieve fewer, shorter passages
Summary of older turns3,000Summarize the summary
Recent turns, verbatim30,000Move the oldest into the summary
Current user message10,000Ask for a shorter message or a file

The total sits well under the window on purpose. A smaller context leaves less room for context rot, and the headroom absorbs cases where your estimate is off.

Count tokens with the provider's tokenizer or token counting endpoint for the exact model you call. Tokenizers can change between model generations, so a budget measured on one model doesn't carry over. Log the token count of each slice with every request. When a conversation goes wrong, that log shows which slice grew.

Context window management strategies compared

StrategyHow it worksWhat you loseGood fit
Sliding windowKeep the last N turnsEverything older, including early instructionsShort, casual chats
Clear old tool resultsReplace used tool output with a short noteRaw data, which can be fetched againAssistants that call tools
Rolling summaryReplace older turns with your own summaryDetail the summary prompt didn't ask forLong support or advisory chats
Retrieval over historyStore past turns, retrieve relevant onesTurns the search missesMulti-session histories
Provider compactionThe provider summarizes older turnsControl over what's keptApps that don't need to audit the summary
Fresh start with notesNew conversation plus a short notes blockConversational flowTask switches

Combine them in order of how much they lose: clear tool results first, then summarize older turns, and keep recent turns verbatim throughout. Anthropic's article on context engineering for agents calls tool result clearing one of the safest, lightest forms of compaction, since a model rarely needs a raw result again once it has acted on it.

Anthropic and OpenAI both document server-side compaction, and Anthropic's version is in beta at the time of writing. Before adopting it, check whether you can read what it produces. A summary you can't inspect is one you can't debug.

How to summarize older turns without losing facts

Summarization is the step most likely to lose something the user cares about. A generic "summarize this conversation" prompt keeps the gist and drops the specifics: the account number, the constraint stated once, the option already rejected. The same Anthropic article warns that overly aggressive compaction loses context whose importance only shows up later, and recommends tuning the summary prompt for recall first, then trimming for precision.

A structured summary is easier to check than prose. Ask for fixed fields:

User goal:
Facts the user stated (verbatim where exact values matter):
Decisions made and options rejected:
Constraints and preferences:
Open questions and pending actions:
Identifiers (order numbers, file names, record IDs):

Then apply these rules:

  1. Keep the system prompt out of the summary. It's resent unchanged on every request.
  2. Keep the latest turns verbatim. Users refer back to them most.
  3. Summarize in chunks, every 10 to 20 turns. Rewriting the start of the history on every request changes the prompt prefix, and prompt caching stops getting hits.
  4. Run the summary in the background after a response is sent, so the user doesn't wait.
  5. Keep the full transcript in your own storage. The summary is only what the model sees.
  6. Version the summary prompt and log which version produced each summary.

Treat the summary as untrusted text, since its inputs can carry injected instructions. If summaries persist across sessions, the risks match AI agent memory poisoning: scope each summary to one user, record its sources and never let it grant permissions.

Common context window management mistakes

  • Truncating by characters. Cutting partway through a JSON tool result or code block hands the model a malformed fragment.
  • Breaking tool call pairs. Provider APIs expect each tool result to follow the call that requested it, so remove both together.
  • Leaving retrieved documents in the history. A document retrieved at turn 5 rides along in every later request. Retrieve per turn and keep only references.
  • Ignoring the output reserve. A response that reaches the token limit stops mid-sentence. Check the stop reason and handle truncation.
  • Allowing unbounded conversations. Set a hard cap on tokens per conversation and offer a fresh start with carried-over notes.

How to test long conversations

Short test conversations never trigger trimming or summarization, so the code that runs in long sessions goes untested. Build cases that do:

  1. Plant a fact early, such as a delivery address at turn 3, and ask about it after the summary has replaced that turn.
  2. State a constraint early, such as "contact me by phone, not email", and check it still holds 50 turns later.
  3. Change a decision midway and check the summary keeps the newer one.
  4. Send one oversized message and confirm the app replies clearly instead of surfacing an API error.
  5. Record tokens per request across the run and confirm they level off.

Our guide to evaluating LLM output quality in production covers how to grade the answers. Summaries can merge or invent facts, so grade them too, and add every long-conversation failure you find in production to the test set.

If you're building a chat or assistant feature and want help with its context handling, our LLM app development work includes evaluation, guardrails and ongoing optimization of quality, latency and cost.

Frequently asked questions

Should we just use a model with a larger context window?

A larger window delays the "prompt is too long" error, but cost, latency and context rot still grow with every turn. Use it as headroom and keep budgeting what goes in. For documents, RAG vs fine-tuning covers when sending everything stops working.

How many recent turns should we keep verbatim?

Set it in tokens, not turns, because turn length varies widely. Fill the recent-turns slice of your budget from the newest turn backward. Then check in testing whether users refer back further, and adjust.

Where should conversation history be stored?

In your own database, under the same retention and access rules as other user data. If you also use provider-side state, check its retention. OpenAI's conversation state guide says response objects are kept for 30 days by default unless you set store to false, and items in Conversation objects aren't subject to that limit, so deletion requests need to cover the provider's copy too.

Insights

Related insights

More on AI Engineering →

Get AI security and automation insights, monthly

AI security, automation and governance, written by engineers. No spam, unsubscribe any time.

Book a free 30-min call