In short
Put everything in the prompt when the material is one long document or a small, stable set that fits the window, and the questions need cross-references or the whole picture. Retrieve when the corpus is large or changes often, when each user may see only some documents, or when you need passage-level citations. Research shows models use long contexts unevenly, so measure both setups on your own questions before you choose.
Key points
- A model that accepts a long prompt does not use all of it equally well: accuracy tends to drop with length and for facts in the middle.
- Needle-in-a-haystack scores are close to perfect for most models and say little about reasoning, aggregation or paraphrased questions.
- Every prompt token is processed on every call, so time to first token and per-request cost grow with the context unless a stable prefix is reused.
- Long context wins on single long documents, cross-references and small corpora that rarely change. RAG wins on large or fast-changing corpora, per-document access control and citations.
- The common middle ground retrieves at the document or section level and packs large chunks into a token budget, best first.
- Decide with a test set from your own data, run against both setups with the same model.
What long context windows changed
The context window is the number of tokens a model reads in one request: instructions, documents, conversation and its own answer. Early chat models held a few thousand tokens, roughly a long article, so any app that answered questions over real documents had to choose a few passages to show the model. That constraint is where retrieval-augmented generation came from.
Windows have since grown by orders of magnitude. All 17 models in the RULER study claim 32K tokens or more, and the 13 models in the NoLiMa study all claim at least 128K. A window that size holds a full contract, a long transcript or a small product manual. Anthropic's contextual retrieval write-up says that if a knowledge base is under 200,000 tokens, about 500 pages, you can skip retrieval and put all of it in the prompt.
So the question changed. It used to be "how do we pick the right passages?" Now it is "do we need to pick at all?" The answer depends on three things the window size does not tell you: how well the model actually uses a long prompt, what a long prompt does to cost and latency, and what your data and users need. Tokens, not characters or pages, are the unit for all of this; see tokenization explained for why the same text counts differently across models.
What the research says about using long contexts
A model that accepts a long prompt is not the same as a model that uses all of it well. Four lines of work are worth knowing.
- Lost in the Middle (Liu and colleagues, 2023, published in TACL). On multi-document question answering and a synthetic key-value lookup, accuracy was highest when the relevant information sat at the start or the end of the input and dropped when it sat in the middle, a U-shaped curve. The authors report this held even for models built for long contexts.
- Needle in a haystack. Greg Kamradt's open-source test hides one fact, the needle, in filler text (Paul Graham essays by default) and asks the model to retrieve it, sweeping both the context length and the depth at which the needle sits. Its results, plotted as a grid of context length against needle depth, became a common way to show off a long window.
- RULER (Hsieh and colleagues, 2024). The authors argue that the plain needle test checks only a superficial form of long-context understanding, and note that models score nearly perfectly on it. RULER adds needles of varied types and counts, multi-hop tracing and aggregation tasks. Across 17 models and 13 tasks, almost all dropped sharply as length grew, and only half held satisfactory performance at 32K tokens, though every one claimed at least that much.
- NoLiMa (Modarressi and colleagues, ICML 2025). Here the question and the needle share few words, so the model has to make an association rather than match a string. The authors report that at 32K tokens, 11 of 13 models fell below half of their short-context scores; GPT-4o, one of the strongest, went from 99.3% to 69.7%.
The needle test is still useful as a smoke test: a model that fails it at a given length will not do better on harder tasks there. Its limits are what it leaves out. The needle usually repeats the question's words, it is unrelated to the haystack around it, which makes it stand out, and the task needs one fact, not reasoning across several or counting things spread through the text. Real questions over real documents are rarely that easy.
Retrieval is not free of these effects either. A RAG prompt with twenty passages is a long context too, and the same position effects apply to it. Li and colleagues (EMNLP 2024) compared RAG with long-context prompting on several public datasets and found that, with enough resources, long context did better on average, while RAG cost far less to run. Their Self-Route method sends each query to RAG first and falls back to the full context when the model judges the retrieved passages insufficient.
Cost and latency grow with the prompt
Before a model writes its first output token, it has to process every input token. That phase, often called prefill, grows with the prompt: a request with a whole manual in it waits longer for its first word than a request with five passages. In the original Transformer paper, the per-layer cost of self-attention grows with the square of the sequence length; serving systems use many optimizations, but the work still rises with every token you add.
Memory grows too. The model keeps keys and values for every token it has read, the KV cache, so a long prompt occupies more accelerator memory for the whole request and leaves less room for other requests. Hosted APIs bill per input token, so a long-context design pays for the full context on every question, while RAG pays for a few passages plus the retrieval step.
Prefix reuse changes this math. If the long, stable part of the prompt comes first and is identical on every call, providers and inference servers can reuse the computed keys and values instead of processing them again, which cuts both latency and cost for the cached part. It only works when the documents do not change between calls and sit before anything that varies. Prompt caching and the KV cache covers how prefix caching works and how to structure prompts for it.
When long context wins
- One long document, many questions about it. A contract, a spec, a transcript, a filing. Chunking it means some answers get split across chunks or lose the heading that gave them meaning; reading it whole avoids that.
- Questions that need cross-references. "Does the termination clause conflict with the renewal terms?" needs two distant sections at once, and neither one may look similar to the question. Retrieval tends to fetch the one that matches the words and miss the other.
- Aggregation and the whole picture. Summaries, "list every obligation of the supplier", timelines and comparisons need all of the text, not the top five matches.
- Small corpora that change rarely. A product manual or a policy set that fits the window can be sent whole, with a cached prefix, and there is no index to build, chunk, embed or keep in sync.
- Early prototypes. Putting the documents in the prompt is the fastest way to learn what users ask before you design a retrieval pipeline around it.
Even here, placement matters. Anthropic's prompting guide recommends putting long documents at the top of the prompt, above the instructions and the question, and says queries at the end can improve response quality by up to 30 percent in its tests. It also suggests asking the model to quote the relevant parts first, then answer from the quotes.
When RAG wins
- The corpus is bigger than any window. A help center, a ticket history, a code base or a document store of millions of pages will not fit, and sending even a fraction of it per question is slow and wasteful.
- The corpus changes often. RAG re-indexes the documents that changed and answers from them on the next query. A long prompt has to be rebuilt, and every change near the top breaks the cached prefix.
- Users may see only some documents. Access control belongs in the retrieval step, as a filter applied by the index, so a passage the user may not read never reaches the model. A prompt instruction such as "do not reveal document 12" is not access control.
- You need citations. Retrieved passages come with IDs, titles and links, so the answer can point at the exact passage and code can check that every cited ID was in the prompt. A model citing page numbers in a 300-page prompt is much harder to verify.
- Volume and latency matter. At many questions per second, a few short passages per request keep time to first token and per-request cost low and predictable.
Long context and RAG side by side
| Factor | Long context | RAG |
|---|---|---|
| Corpus size | Must fit the window, with room for instructions and the answer | Unbounded; only the retrieved passages enter the prompt |
| Freshness | Rebuild the prompt on change; edits near the top break the cached prefix | Re-index changed documents; next query sees them |
| Cross-references and aggregation | Strong: all of the text is in view | Weak unless retrieval brings back every needed section |
| Single-fact lookup in a large corpus | Wasteful, and facts in the middle are used less well | Strong when retrieval finds the passage |
| Access control | Hard: whatever is in the prompt can surface in the answer | Filter by user or tenant inside the search |
| Citations | Possible, but hard to check against a huge prompt | Passage IDs make them checkable in code |
| Latency and per-request cost | Grow with the context; prefix caching helps when it is stable | Small prompts, plus a retrieval step |
| Engineering effort | Low: no index, no chunking | Parsing, chunking, embedding, indexing and evaluation to build and run |
| Typical failure | The answer was in the prompt and the model missed it | The answer was never retrieved |
Hybrids: retrieve, then pack large chunks
Large windows did not end retrieval; they changed what it returns. Instead of five passages of a few hundred tokens, a hybrid retrieves at the document or section level and packs as much relevant text as a token budget allows. Common shapes:
- Small-to-big: search over small chunks for precision, then send their parent section or whole document. The chunking strategies deep dive covers parent-child retrieval and contextual retrieval, which prefixes each chunk with a short summary of where it sits in its document before embedding.
- Document routing: retrieve the few documents that matter, then put each of them in the prompt whole, so cross-references inside a document survive.
- Stable prefix plus retrieved tail: cache the manual or policy that every request needs at the top of the prompt, and retrieve the fast-changing material, such as tickets or account data, after it.
- Route by question: try a cheap RAG answer first and fall back to the long context when the model says the passages are not enough, as in Self-Route. LLM routing and fallbacks covers routing more broadly.
Packing is a small knapsack problem. The function below takes scored chunks, keeps the best ones that fit a budget, and then orders them so the best document comes first and each document reads in its original order. count_tokens should be your model's tokenizer; word count stands in here so the example runs anywhere.
def pack_context(chunks, budget, count_tokens, reserve=0):
# chunks: dicts with id, doc, pos (position in its document), score, text
limit, used, picked = budget - reserve, 0, []
for c in sorted(chunks, key=lambda c: c['score'], reverse=True):
cost = count_tokens(c['text'])
if used + cost > limit:
continue # too big for what is left; a smaller one may still fit
picked.append(c)
used += cost
# Best document first; each document's chunks in reading order
best = {}
for c in picked:
best[c['doc']] = max(best.get(c['doc'], 0), c['score'])
picked.sort(key=lambda c: (-best[c['doc']], c['pos']))
return picked, used
words = lambda t: len(t.split()) # stand-in; use your model's tokenizer
chunks = [
{'id': 'a1', 'doc': 'contract', 'pos': 1, 'score': 0.91, 'text': 'w ' * 300},
{'id': 'a2', 'doc': 'contract', 'pos': 2, 'score': 0.62, 'text': 'w ' * 250},
{'id': 'b1', 'doc': 'policy', 'pos': 7, 'score': 0.84, 'text': 'w ' * 500},
{'id': 'c1', 'doc': 'faq', 'pos': 3, 'score': 0.55, 'text': 'w ' * 120},
]
picked, used = pack_context(chunks, budget=1200, count_tokens=words, reserve=150)
print([c['id'] for c in picked], used) # ['a1', 'a2', 'b1'] 1050Run as shown, it keeps a1, b1 and a2 (1,050 words, exactly what is left after the reserve), skips the FAQ chunk that no longer fits, and returns the two contract chunks first in reading order. The reserve holds room for instructions, the question and the answer. Greedy by score is not the optimal knapsack, but it is predictable, and the ranking you feed it matters far more than the packing.
How to test which works for your data
Published benchmarks tell you how models behave on someone else's text. The choice for your product should come from a test on yours.
- Write a question set from real user questions, with the answer and the passages that hold it labeled. Include single-fact lookups, cross-references, aggregation questions and questions your documents do not answer.
- Build both setups with the same model and instructions: the full context (or as much as fits), and RAG at two or three values of k. Add a hybrid if your documents are long.
- Score answers for correctness and citation accuracy, and record input tokens, time to first token and total latency for each.
- Break the results down by question type and by where the answer sits in the context. An average can hide a setup that fails every cross-reference question.
- Re-run when you change the model, the window you use or the corpus.
How to evaluate RAG covers the retrieval and answer metrics in detail. For position effects on your own documents, a needle test is easy to generate. Use your real documents as the haystack, write needles that fit their style, and phrase the question in different words from the needle, which is the lesson of NoLiMa:
import random
def needle_cases(filler, needle, question, answer, lengths, depths, seed=0):
rng = random.Random(seed)
for n in lengths: # haystack size in passages; measure tokens in practice
hay = [rng.choice(filler) for _ in range(n)]
for d in depths: # 0.0 puts the needle first, 1.0 last
doc = hay[:round(d * n)] + [needle] + hay[round(d * n):]
yield {'length': n, 'depth': d, 'answer': answer,
'prompt': '\n\n'.join(doc) + f'\n\nQuestion: {question}'}
def score(cases, call_model):
# call_model: any function that sends a prompt and returns text
return {(c['length'], c['depth']): c['answer'].lower() in call_model(c['prompt']).lower()
for c in cases}
filler = ['Invoices are due on receipt.', 'The office is closed on public holidays.',
'Support tickets are triaged by severity.']
cases = list(needle_cases(filler, 'The vendor ID for the Lisbon office is VX-4471.',
'Which vendor ID does the Lisbon office use?', 'VX-4471',
lengths=[100, 1000], depths=[0.0, 0.5, 1.0]))
print(len(cases), [(c['length'], c['depth'], len(c['prompt'].split())) for c in cases[:3]])
# 6 [(100, 0.0, 621), (100, 0.5, 621), (100, 1.0, 621)]This toy question shares words with its needle, so it is the easy case. Make harder variants for your domain: a question that names the city by its country, a needle split across two passages, or two needles the model has to combine. If accuracy holds across lengths and depths for your documents and model, long context is a real option; if it falls off past some length, that length is your budget, and retrieval or a hybrid fills the rest.
If you want this kind of decision made and built into your product, see our AI agent development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts (arXiv, TACL)
- Hsieh et al., RULER: What's the Real Context Size of Your Long-Context Language Models? (arXiv)
- Modarressi et al., NoLiMa: Long-Context Evaluation Beyond Literal Matching (arXiv, ICML 2025)
- Kamradt, LLMTest_NeedleInAHaystack (GitHub)
- Li et al., Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach (arXiv, EMNLP 2024)
- Vaswani et al., Attention Is All You Need (arXiv)
- Anthropic: Introducing Contextual Retrieval
- Anthropic documentation: Prompting best practices (long context)