Skip to content

Retrieval

Context packing for RAG: order, duplicates and source labels

Pack retrieved chunks into the prompt with fewer distractors, labeled sources and the question last, and test chunk order on your own questions instead of assuming it.

By Rose Donaldson, Context Retrieval team · Published

This article was drafted with AI assistance from the sources listed below and edited and published by the Context Retrieval team.

Before the retrieved chunks go into the prompt
  • Cut, do not pad: pass the chunks that answer, not every chunk that matched.
  • Drop repeats: remove duplicate and near-duplicate chunks before packing.
  • Label every chunk: source ID, page title, final URL and section path.
  • Question last: sources first, then the instructions and the question.
  • Test the order: move the answer chunk to the start, middle and end and compare.

Retrieval hands you a ranked list. Context packing is the step that turns that list into the text the model actually reads: which chunks go in, in what order, with what labels, and where the question sits. It gets less attention than retrieval, and its folklore is older than the models most teams now use. This note sorts what the studies found from what they did not, then gives packing rules and one test to run on your own questions.

What the 2023 position studies found

The best-known result is "Lost in the Middle" by Liu and colleagues.1 In its multi-document question answering task, each prompt held 10, 20 or 30 documents, one of which contained the answer. Across the models tested (MPT-30B-Instruct, LongChat-13B, GPT-3.5-Turbo, Claude-1.3 and their long-context variants), accuracy was often highest when the answer document sat at the start or end of the context and lowest when it sat in the middle: the U-shaped curve. In the worst positions with 20 and 30 documents, GPT-3.5-Turbo did worse than its closed-book score of 56.1%, where it saw no documents at all.

Two smaller findings from the same paper matter more for packing. First, the reader saturated well before the retriever did: passing 50 retrieved documents instead of 20 improved accuracy by only about 1.5% for GPT-3.5-Turbo and about 1% for Claude-1.3. Second, repeating the query before and after the documents made the synthetic key-value task nearly perfect, but barely changed the multi-document QA results.

Anthropic's long-context tests from September 2023 point the same way on placement.2 With Claude Instant 1.2 on documents of roughly 70K and 95K tokens, accuracy fell as the relevant passage moved further from the end of the prompt, and the authors stressed putting the instructions at the end. Asking the model to pull relevant quotes into a scratchpad before answering helped in every head-to-head comparison they ran.

What a 2025 report did not find

Chroma's "Context Rot" report from July 2025 tested 18 models, including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3 variants.3 In its own needle-in-a-haystack task it placed the needle at 11 positions and found no notable variation in performance by position. That does not overturn Lost in the Middle, which used a different task and older models. It does mean the middle-position drop is not a settled property of current models.

What the report did find is more useful for RAG. Distractors, passages on the same topic that do not answer the question, hurt performance, and some distractors hurt more than others. On LongMemEval, every model did markedly better on focused prompts of about 300 tokens than on full histories of about 113K tokens holding the same answer. One result runs against intuition: shuffling the sentences of the haystack improved performance across all 18 models. The report's conclusion is that how information is presented matters, not only whether it is present.

Packing rules that follow

From these results we take five defaults. Each one is a starting point to measure, not a finding of ours.

  • Cut, do not pad. If the reader saturates and distractors hurt, the last few chunks of a long list cost more than they add. Set the number of packed chunks from your question set, and prefer a reranker cut-off to a fixed large k.
  • Remove repeats before packing. Two copies of one paragraph use budget and act as a distractor for each other. Exact duplicates are cheap to drop; near-duplicates need MMR or index-time dedupe, covered in near-duplicate chunks in the top-k.
  • Label every chunk. A short source ID, the page title, the final URL after redirects and the heading path, in a fixed structure. The model cites the ID, and your code maps it back to a URL.
  • Sources first, question last. Put the instructions and the question after the packed chunks, as Anthropic's tests suggest.
  • Ask for quotes first. A quote step before the answer helped in Anthropic's comparisons, and it gives the citation check something exact to verify.

On order, best-first is the simplest choice and keeps logs readable. If your tests show a middle drop with your model, an edges-first order puts the top two chunks at the start and the end.

A packer you can read in one screen

The function below takes chunks already sorted by reranker score, drops exact repeats, labels each chunk and puts the question last.

def edges_order(items):
    """Best item first, second best last, weakest in the middle."""
    front, back = [], []
    for i, item in enumerate(items):
        (front if i % 2 == 0 else back).append(item)
    return front + back[::-1]


def pack_context(chunks, question, max_chunks=8, edges=False):
    """chunks: dicts with text, title, url, section; sorted best first."""
    seen, kept = set(), []
    for c in chunks:
        key = " ".join(c["text"].split()).lower()
        if key in seen:
            continue
        seen.add(key)
        kept.append(c)
        if len(kept) == max_chunks:
            break
    if edges:
        kept = edges_order(kept)
    blocks = [
        f'<source id="S{i}" title="{c["title"]}" url="{c["url"]}" '
        f'section="{c["section"]}">\n{c["text"]}\n</source>'
        for i, c in enumerate(kept, start=1)
    ]
    return (
        "\n\n".join(blocks)
        + "\n\nAnswer using only the sources above. First quote the passages "
        "you rely on with their source id, then answer. If the sources do not "
        "answer the question, say so.\n\n"
        + f"Question: {question}"
    )


chunks = [
    {"text": "Each key allows 10 requests per second.", "title": "Billing API",
     "url": "https://example.com/docs/billing", "section": "Rate limits > Limits"},
    {"text": "Each key allows 10 requests  per second.", "title": "Billing API",
     "url": "https://example.com/docs/billing", "section": "Rate limits > Limits"},
    {"text": "Keys are created in the dashboard.", "title": "Keys",
     "url": "https://example.com/docs/keys", "section": "Create a key"},
]
print(pack_context(chunks, "How many requests per second does one key allow?"))

The second chunk differs only in whitespace, so it is dropped. max_chunks=8 is a placeholder to tune, not a recommendation. With edges=True, five chunks ranked 1 to 5 are packed in the order 1, 3, 5, 4, 2.

Test position on your own questions

You do not need to take either study's word for your model. Take 20 to 30 questions from your golden set whose answer chunk you know. For each, build three prompts with the same chunks and move the answer chunk to the first, middle and last slot. Score the answers the same way you score everything else. If the three scores are close, keep best-first order and spend your effort on fewer distractors. If the middle slot is clearly worse, switch on edges-first order and measure again.

Run the same test once with the packed chunk count halved. If answers hold or improve, your k was carrying distractors. The retrieval guide covers the question set and the recall measures that sit upstream of this step.

Footnotes

  1. Liu et al., "Lost in the Middle: How Language Models Use Long Contexts", arXiv 2307.03172 (v3, November 2023). ↩

  2. Anthropic, "Prompt engineering for Claude's long context window" (September 2023). ↩

  3. Hong, Troynikov and Huber, "Context Rot: How Increasing Input Tokens Impacts LLM Performance", Chroma technical report (July 2025). ↩

Frequently asked questions

Does chunk order in a RAG prompt matter?

It did in the 2023 Lost in the Middle study, where accuracy was often highest with the answer at the start or end of the context. A 2025 Chroma report on 18 models found no notable variation by needle position in its own test. Treat order as something to test on your data, not a settled rule.

Should I pass more retrieved chunks to the model to be safe?

Not by default. Lost in the Middle found that going from 20 to 50 retrieved documents added only about 1% to 1.5% accuracy, and Chroma found models did markedly better on short, focused prompts than on full long ones. Extra chunks add distractors as well as recall.

How should I label retrieved chunks so the model can cite them?

Wrap each chunk in a block with a short source ID, the page title, the final URL after redirects and the section path. Ask the model to cite by ID, then map the IDs back to URLs in your code.

Where should the question go in a RAG prompt?

After the sources. Anthropic's 2023 long-context tests stressed putting the instructions at the end of the prompt, after the long document.

Sources

  1. Lost in the Middle: How Language Models Use Long Contexts (Liu et al., arXiv 2307.03172v3) (Paper)
  2. Context Rot: How Increasing Input Tokens Impacts LLM Performance (Chroma technical report) (Paper)
  3. Prompt engineering for Claude's long context window (Anthropic) (Blog)