RAGEngineering Hub
Chapter 9 · concept 3 of 6 · show all
  1. 1What RAG is, and why
    1. 1.1Why models need outside knowledge, and what hallucination means
    2. 1.2What RAG is: anatomy of a request
    3. 1.3RAG vs fine tuning vs long context and prompt caching
    4. 1.4Use cases and the quality, latency and cost triangle
    5. Chapter overview
  2. 2Tokens, cost and your first RAG
    1. 2.1Tokens and context windows for RAG
    2. 2.2The RAG lifecycle and your first RAG in miniature
    3. Chapter overview
  3. 3Getting documents in
    1. 3.1Content sources and file formats
    2. 3.2Parsing, layout and OCR
    3. 3.3Tables, images and mixed content
    4. 3.4Cleaning, normalization and quality gates
    5. 3.5Metadata, document identity and versioning
    6. 3.6Updates, deletes, reindexing and ingestion pipelines
    7. Chapter overview
  4. 4Chunking
    1. 4.1Why we chunk, and the main chunking strategies
    2. 4.2Structure aware chunking and tables
    3. 4.3Chunk size, overlap and token based sizing
    4. 4.4Contextual chunking and late chunking
    5. 4.5Parent child and multi representation indexing
    6. 4.6Chunk metadata, provenance and the chunking debugging playbook
    7. Chapter overview
  5. 5Embeddings
    1. 5.1Embeddings and similarity from first principles
    2. 5.2What embeddings cannot do
    3. 5.3Choosing an embedding model: size, cost, language
    4. 5.4Embedding model migration and index rebuilds
    5. Chapter overview
  6. 6Vector stores and scores
    1. 6.1Vector databases, ANN indexes and choosing a store
    2. 6.2Score calibration and thresholds
    3. 6.3Late interaction and multivector retrieval
    4. Chapter overview
  7. 7Finding the right chunks
    1. 7.1Query understanding, rewriting and expansion
    2. 7.2Dense retrieval and keyword search with BM25
    3. 7.3Hybrid retrieval and rank fusion
    4. 7.4topK, no good match, and metadata filtering
    5. 7.5Routing, diversity, deduplication and caching
    6. 7.6Reranking: two stage, cross encoder and LLM rerankers
    7. Chapter overview
  8. 8When retrieval fails
    1. 8.1Retrieval failure analysis playbook
    2. Chapter overview
  9. 9Building the answer
    1. 9.1Context selection, packing and citations
    2. 9.2Grounding prompts and abstention
    3. 9.3Lost in the middle and context management
    4. 9.4Conflicts, staleness and freshness rules
    5. 9.5Hallucination checks and answer verification
    6. 9.6Conversational RAG, answer UX and RAG APIs
    7. Chapter overview
  10. 10Measuring
    1. 10.1Why measure, and what to measure
    2. 10.2Building a golden dataset
    3. 10.3Retrieval metrics: precision, recall, MRR, nDCG
    4. 10.4Faithfulness and answer correctness
    5. 10.5LLM as judge, and judging the judge
    6. 10.6Offline and online evals, regression tests and slices
    7. Chapter overview
  11. 11Safety and operations
    1. 11.1Prompt injection and poisoned documents
    2. 11.2Access control, privacy and governance
    3. 11.3Index lifecycle operations
    4. 11.4Observability and tracing
    5. 11.5Latency, cost, caching and model routing
    6. 11.6Reliability, degraded modes and launch readiness
    7. Chapter overview
  12. 12Scale and advanced RAG
    1. 12.1Scaling, multi tenancy and enterprise architecture
    2. 12.2Choosing an architecture: naive, advanced, agentic, graph
    3. 12.3Agentic RAG and RAG as an MCP tool
    4. 12.4GraphRAG, structured data and multimodal RAG
    5. Chapter overview

Lost in the middle and context management

Models use the start and end of a long context better than the middle. Where our answers land in the context, and how ordering, short contexts and trimmed history keep the answer where the model looks.

A real question

The right chunk is in the prompt. Can the model still miss it?

Yes. Studies show models use information at the start and end of a long context better than in the middle. Keep contexts short, put the best chunk first, and trim what does not help.

The problem

Why this matters

If the answer is anywhere in the context, the model will use it.
The belief

If the answer is anywhere in the context, the model will use it.

In the “Lost in the Middle” experiments, accuracy dropped when the answer document sat in the middle of 20 documents, compared with the start or end. Position matters, more so as the context grows.
What really happens

In the “Lost in the Middle” experiments, accuracy dropped when the answer document sat in the middle of 20 documents, compared with the start or end. Position matters, more so as the context grows.

Why not the simpler way

Long context windows invite a simple strategy: retrieve a lot, paste it all, let the model find the answer. It costs more per question, and it gives the model a harder reading task. Evidence from several studies says models do not read long contexts evenly.

The idea

The idea in plain words

Lost in the middle (Liu et al., "Lost in the Middle: How Language Models Use Long Contexts", arXiv 2307.03172, 2023) put the answer document at different positions among 10 to 30 documents. Accuracy formed a U: best at the start, good at the end, worst in the middle. Newer models handle long contexts better, but position effects remain worth testing on your own model.

Context management keeps the prompt focused: what to keep, in what order, and what to summarize or drop.

When you skim a long email, you read the opening and the sign-off carefully and skim the middle.

How it works

Step by step

  1. With hybrid search, our answer chunk was first in the context for 33 of 47 questions and never below third.
    1

    Know where answers land

    With hybrid search, our answer chunk was first in the context for 33 of 47 questions and never below third.

  2. Order by reranker score, keep k small. A short context has no middle to get lost in.
    2

    Best first, few chunks

    Order by reranker score, keep k small. A short context has no middle to get lost in.

  3. In chat, summarize old turns instead of keeping them all. Drop chunks the answer does not need.
    3

    Manage the rest

    In chat, summarize old turns instead of keeping them all. Drop chunks the answer does not need.

In detail

Ordering. Best first. Some systems put the second best last, so both ends hold strong chunks.

Size. Retrieve wide, rerank, pass few (RAG-29, RAG-31).

Conversation history. Keep the last few turns verbatim, summarize older ones, and drop old retrieved chunks unless the follow-up needs them. Rewrite follow-ups into stand-alone questions before search (RAG-38).

Compression. Extract only the relevant sentences from each chunk before packing. It saves tokens and can lose context; measure it.

Token budget of one RAG call: 39 instruction tokens, about 1,026 tokens of retrieved chunks, about 13 question tokens, and up to 1,024 tokens reserved for the answer, all inside the context window.ONE CALL · ABOUT 2,102 TOKENS OF A MUCH LARGER CONTEXT WINDOWInstruction ~393 retrieved chunks~1,026Question ~13Answer reserve~1,024
Median prompt in the Mini RAG Lab: 1,078 tokens across 47 golden questions (recursive 512 chunks, top 3). The answer reserve is the max_tokens the lab sends.

The code

Try it in Python

def order_for_model(chunks_best_first: list[str]) -> list[str]:
    """Best first, second best last, the rest in between."""
    if len(chunks_best_first) < 3:
        return chunks_best_first
    first, second, *rest = chunks_best_first
    return [first, *rest, second]

def trim_history(turns: list[dict], keep_last: int = 4, summarize=None) -> list[dict]:
    old, recent = turns[:-keep_last], turns[-keep_last:]
    if old and summarize:
        return [{"role": "user", "content": "Summary of earlier conversation: " + summarize(old)}, *recent]
    return recent

See it

What we measured

Measured · position of the answer chunk in a top-5 context

Polder corpus, 34 recursive 512 token chunks, 47 golden questions, hybrid search (BM25 + bge-small, RRF), best first.

Position 133 of 47
Position 211 of 47
Position 33 of 47
Positions 4 and 50 of 47
Model accuracy by positionnot measured

Measured 2026-11-04 with corpus/scripts/measure-parts-6-7.mts. Answer accuracy per position needs model calls: not measured yet, needs an API key.

Try it on a real example

Where the answer chunk sat in a top-5 context, 47 questions, hybrid search

Show
1.33 of 47 questionsThe answer is the first source the model reads.✓

The best case for any model.

Choosing

Use it when, avoid it when

Use it when
  • Best-first order and small k
  • Summarized history in long chats
Avoid it when
  • Filling a large context window because it fits
  • Assuming a long-context model reads every position equally

What it costs · Ordering is free. Summarizing history costs a small model call every few turns.

In production

Test position effects on your own model: take golden questions, place the answer chunk at positions 1, middle and last among distractors, and compare accuracy. Log context length per question; long-tail questions with huge contexts are where cost and errors pile up. Prompt caching (RAG-04) makes the fixed parts cheap; it does not help the model read the middle.

Watch out

Common mistakes

  • Long-context models solved this. They improved; test position on your model.
  • More chunks cannot hurt. They add cost and push the answer away from the start.
  • History should be kept in full. Old turns crowd out the sources that matter now.

Check yourself

Remember this

Remember these

  • Models use the start and end of a long context best.
  • Put the best chunk first and keep k small.
  • On our corpus the answer was first for 33 of 47 and never below third.
  • In chat, summarize history instead of letting it grow.

Say it in an interview

  1. 01Models use the start and end of long contexts best; Liu et al. showed a U-shaped curve.
  2. 02I order best first and keep k small, so there is little middle to lose.
  3. 03On my corpus the answer chunk was first for 33 of 47 questions and never below third.
  4. 04In chat I summarize old turns and rewrite follow-ups before search.
  5. 05I would test position effects on my own model before trusting a long context.

Quick quiz

Three questions

Question 1

Q1

What did "Lost in the Middle" (Liu et al.) find?

Question 2

Q2

On our corpus, where did the answer chunk land in a top-5 hybrid context?

Question 3

Q3 · from RAG-33

Why label each chunk with a number?

Saved on this device. No account needed.