Lost in the middle & context rot
Models don't use long context evenly: facts in the middle get used worst, and quality decays as input grows even on easy tasks. Send less, better context, with key parts at the edges.
Analogy: A long meeting: everyone remembers the opening and the last five minutes, but the decision made at minute 40 is gone. The longer the meeting, the worse it gets.
How it works
- A window is how much a model can read, not how well it uses it.
- Accuracy is U-shaped by position: GPT-3.5-Turbo did worse with the answer mid-context than with no documents.
- Decay is faster when question and fact share few words, or when plausible distractors are present.
- Needle-in-a-haystack misleads: the needle usually shares words with the question, so it tests lookup, not reasoning.
- Rerank down to 3–8 chunks, put the question last, and compact old agent turns.
Check yourself
Answer to mark it learned; your answers aren't scored.
A legal RAG puts the top 40 clauses (~30K tokens) in every prompt, question first. The eval keeps missing answers whose clause ranks ~15–25. A teammate proposes raising top-k to 60 "to be safe". What do you do instead?
Go deeper
Full explanation
A context window is how much a model can read, not how well it uses it. Two effects matter.
Lost in the middle (Liu et al., 2023): in multi-document QA, accuracy is U-shaped by position, highest when the answer sits at the start or end of the context and lowest in the middle. With 20 documents, GPT-3.5-Turbo did worse with the answer mid-context than with no documents at all.
Context rot (Chroma, 2025): across 18 models, quality degrades as input grows even when the task stays trivial, such as copying back a sequence of repeated words. It degrades faster when the question and the needed fact share few words, and when plausible distractors are present.
Why the classic needle-in-a-haystack test misleads: the needle usually shares exact words with the question, so it measures lexical lookup, not reasoning over context. Near-perfect NIAH scores coexist with steep drops on harder tests like RULER and NoLiMa.
What I do about it:
- Put long documents first and the instructions + question last; restate key constraints near the end.
- Send fewer, better chunks: Reranking (cross-encoders) down to 3–8 instead of stuffing 50.
- In agents, compact old turns and tool output, and give sub-agents clean windows (Context engineering).
Code Fewer chunks, strongest at the edges, question last
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4.1" # any long-context chat model
def edge_order(ranked: list[str]) -> list[str]:
# Strongest chunks at both ends, weakest in the middle (U-shaped use)
front, back = ranked[0::2], ranked[1::2]
return front + back[::-1] # [1,2,3,4,5,6] -> [1,3,5,6,4,2]
def answer(question: str, candidates: list[str]) -> str:
top = rerank(question, candidates, keep=6) # fewer, better chunks
docs = "\n\n".join(
f'<doc id="{i}">\n{c}\n</doc>' for i, c in enumerate(edge_order(top))
)
prompt = (
f"<documents>\n{docs}\n</documents>\n\n" # long material first
"Answer only from the documents. Cite doc ids.\n"
f"Question: {question}" # question last
)
resp = client.chat.completions.create(
model=MODEL, messages=[{"role": "user", "content": prompt}]
)
return resp.choices[0].message.contentReal example
A legal-assistant RAG stuffed the top 40 clauses (~30K tokens) into every prompt. On a 200-question eval it kept missing termination clauses that ranked ~15–25, right in the middle. The team reranked down to 6 chunks, put the strongest at the edges and moved the question below the documents. The prompt shrank to ~5K tokens, input cost per query fell ~6×, and most misses disappeared: the right clause was now one of six, not one of forty.
Trade-offs +3 · −3
+ You gain
- Shorter, curated context is cheaper and faster on every single call.
- Edge placement and question-last ordering are free: no extra calls, just reordering.
- Compaction lets agents run long sessions without stale tool output drowning the goal.
− You pay
- Aggressive pruning can drop the one chunk you needed, and that recall loss is silent.
- Compaction is lossy: a summary can erase a detail a later step depends on.
- Effects vary by model and task, so you must measure on your own data, not a vendor's NIAH chart.
Use it when
Any time the prompt grows past a few thousand tokens: RAG with many chunks, long agent loops, multi-document analysis, long chat histories.
Avoid it when
Skip heavy pruning when the task truly needs the whole input (full-contract review, transcript summaries); split it into map-reduce passes instead of cutting context.
Numbers to know 4
- Liu et al.: ~20-point accuracy drop when the answer moves from the first to the middle position (GPT-3.5-Turbo, 20 documents).
- RULER: of models claiming 32K+ context, only about half held up at 32K.
- NoLiMa (2025): at 32K tokens, 11 of 13 models fell below 50% of their short-context score; GPT-4o went from 99.3% to 69.7%.
- Anthropic: putting the query after long documents improved response quality by up to 30% in its tests.
Common pitfalls 4
- Trusting a 1M-token window because the vendor's needle-in-a-haystack chart is all green.
- Stating instructions only at the top of a 100K-token prompt and never near the question.
- Raising top-k "to be safe": more chunks add distractors and push the right one into the middle.
- Never trimming agent history: stale tool output piles up and quality decays turn by turn.
Interview questions 3
Answer out loud first, then reveal.
Your model supports 1M tokens. Why not put the whole knowledge base in the prompt?Show answer
Three reasons. First, usable context is shorter than advertised: quality degrades with length even on easy tasks, and facts mid-context get used worst; vanilla needle tests hide this because the needle shares words with the question. Second, cost and latency scale with input tokens on every call. Third, every irrelevant chunk is a distractor. So I retrieve and rerank to a handful of chunks, and reserve long context for tasks that need the whole document, after measuring on my own eval at the lengths I'll actually send.
How would you check whether context length is hurting your app?Show answer
I run a length-and-position sweep on my own data: same questions, gold chunk placed at the start, middle and end, padded with realistic distractors (real neighbouring chunks, not random text) at, say, 4K, 16K and 64K tokens. I plot accuracy by position and length. If the middle or the long settings sag, I cut top-k, add a reranker, reorder strongest-to-the-edges and move the question last, then rerun the same sweep to confirm the curve flattened.
An agent gets noticeably worse after 50 turns. What is happening and what do you do?Show answer
Most likely context rot: the window is full of stale tool output, failed attempts and superseded plans, so the current goal is a small slice buried mid-context. I compact: summarize old turns into a state note with goal, decisions and open items, and drop raw tool results once used. I offload large artifacts to files the agent can re-read, and hand sub-tasks to sub-agents with fresh windows that return short summaries. Then I measure task success against turn count to confirm the decay is gone.