What is the "lost in the middle" problem?

Learning path, stage 3 of 5: RAG and fine-tuning · question 6 of 10

LLMs use information at the beginning and end of a long context much better than information in the middle. In the original study, accuracy on multi-document QA dropped noticeably when the relevant passage sat mid-prompt, even for long-context models. So "just stuff everything in" is not a retrieval strategy.

What to do about it

  • Retrieve less, more precisely: rerank and keep the top 5–10, not 50.
  • Order on purpose: put the most relevant chunks first (or last, next to the question).
  • Put the question at the end of long prompts, after the documents. Long-context prompting guides recommend this.
  • Use structure: wrap each document in tags with an ID and title so the model can find and cite it.
  • Ask for quotes first: have the model pull the relevant quotes, then answer from them.
  • Test with a needle in a haystack: place a known fact at different depths and check that it's found.

Nuance

Newer models are much better at using long contexts than the models in the 2023 paper, but noise and position still matter. Measure on your own data.

Sources

Code example

tsx
1// Order retrieved chunks so the strongest sit at the edges of the context.
2type Scored = { id: string; text: string; score: number };
3
4export function edgeOrder(chunks: Scored[]): Scored[] {
5 const sorted = [...chunks].sort((a, b) => b.score - a.score);
6 const front: Scored[] = [];
7 const back: Scored[] = [];
8 sorted.forEach((c, i) => (i % 2 === 0 ? front : back).push(c));
9 return [...front, ...back.reverse()]; // best first, second-best last, weakest in the middle
10}
11
12export function buildContext(chunks: Scored[], question: string) {
13 const docs = edgeOrder(chunks)
14 .map((c) => `<document id="${c.id}">\n${c.text}\n</document>`)
15 .join("\n");
16 // documents first, question last
17 return `${docs}\n\nFirst quote the passages that answer the question, then answer it.\nQuestion: ${question}`;
18}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app