RAG in Practice: Chunking, Hybrid Retrieval, Reranking and Evaluation
How to build a retrieval-augmented generation system that works: clean and chunk documents, combine dense and BM25 retrieval with RRF, rerank with a cross-encoder, assemble the context, and measure every step with Hit@k and MRR on a small runnable corpus.
After this page you will be able to
- Describe the full path of a RAG system from ingesting documents to returning an answer, and tell the offline index build from online question answering.
- Explain which metric chunking, retrieval, fusion, reranking and context assembly each affect.
- Build hybrid retrieval from BM25, dense vectors and RRF, rerank with a cross-encoder, and quantify each step with Hit@k, Recall@k and MRR.
- Troubleshoot a RAG system along the evidence chain: retrieval first, then ranking and context, and the model itself last.
On this page
- Why many applications start with RAG instead of fine-tuning
- Overview: the parts of a RAG system
- Step 1: do not throw documents straight into the vector store
- Step 2: chunking sets the ceiling for recall
- Hands-on: one document, three ways to cut it
- Step 3: metadata matters more than people think
- Step 4: embeddings and vector search
- The small corpus used on this page
- How an embedding model turns text into a vector
- How big is the index
- Exact versus approximate search
- Choosing a vector store
- Step 5: retrieval is more than dense search
- BM25: a strong baseline for word matching
- RRF: fusion by rank
- Query rewriting
- Step 6: reranking decides the gap between “retrieved” and “ranked first”
- Hands-on: are hybrid retrieval and reranking worth it?
- Step 7: context assembly is not “paste in the whole top-k”
- How to evaluate a whole RAG system
- A practical troubleshooting order
- Common mistakes
- Summary and exercises
- Quick self-check
- Further reading
- FAQ
All code on this page shares one small corpus, was run locally, and its output is pasted right after it.
Why many applications start with RAG instead of fine-tuning
Retrieval-augmented generation (RAG) means retrieving external material before answering and generating the answer from it. The name comes from the 2020 paper by Lewis et al., which combined a pre-trained generator (parametric memory) with a dense vector index of Wikipedia (non-parametric memory) reached through a pre-trained neural retriever, for knowledge-intensive tasks. Today’s RAG engineering is much broader than that paper, but the spine, retrieve first and generate second, has not changed.
When a team first connects an LLM to a product, the usual request is not a stronger generalist. It is a model that uses the company’s internal documents, answers from recent material, makes fewer things up, and does not need retraining whenever the content changes. The table compares the three options by goal:
| Goal | RAG | Fine-tuning | Put it all in the context |
|---|---|---|---|
| Knowledge changes often | Update the index | Retrain or train incrementally | Send it with every request, bounded by window and cost |
| Answers need sources | Natural fit | Hard to trace | Possible |
| Material far exceeds the window | Good fit | A poor way to inject many facts | Does not fit |
| Change tone, format or behavior | Weak | Strong | Prompting, with limited reliability |
| Only a few pages of material | Probably overkill | Overkill | Often the simplest |
“A poor way to inject many facts” has experimental support. In a controlled comparison, Ovadia et al. (2023) put unsupervised fine-tuning against RAG on a range of knowledge-intensive tasks. Fine-tuning helped somewhat, but RAG was better for both knowledge the model had seen and entirely new knowledge, and the models struggled to learn new facts through unsupervised fine-tuning.
RAG is not a silver bullet either. It solves “get the relevant external information to the model”. It does not directly fix weak reasoning, failing tool calls or workflow orchestration.
Overview: the parts of a RAG system
A minimal working RAG system splits into seven steps. The figure separates the offline index build from online question answering:
| Step | Phase | What it decides | First metric to look at |
|---|---|---|---|
| 1. Cleaning | Offline | Whether the index holds noise | Manual spot checks |
| 2. Chunking and metadata | Offline | The ceiling for recall | Share of sentences cut in half |
| 3. Embedding and index | Offline | Semantic match quality and storage cost | Recall@k on your own data |
| 4. Retrieval | Online | Whether the candidates contain the right evidence | Recall@k |
| 5. Reranking | Online | Whether the right evidence comes first | Hit@1, MRR |
| 6. Context assembly | Online | What the model actually sees | Context length, redundancy |
| 7. Generation and evaluation | Online and offline | Whether the answer follows the evidence | Faithfulness, citation accuracy |
A bad RAG answer usually has more than one cause, and the causes stack up across steps. Building the seven steps as separate modules is what gives you something to tune.
Step 1: do not throw documents straight into the vector store
Many RAG prototypes fail at the first step. Once noise enters the index, high-similarity results contain low-value fragments, and the model receives a context that looks long but holds little usable information.
| Noise | Consequence | Fix |
|---|---|---|
| Headers, footers, navigation menus, copyright notices | Repeated in every chunk and raise the similarity of irrelevant chunks | Remove by template rules or frequency |
| Duplicate and near-duplicate documents | The top-k fills up with the same content | Exact deduplication, then near-duplicate removal (for example MinHash) |
| Broken tables and image placeholders | Numbers no longer line up with rows and columns | Convert tables to Markdown or expand them by row, add text for images |
| Lost heading hierarchy | A chunk loses its context (clause 3 of which document?) | Keep the heading path as metadata or prepend it to the chunk |
The first layer of RAG quality control is not in retrieval. It is at the data entrance.
Step 2: chunking sets the ceiling for recall
Chunking is the most underrated step in a RAG system. A chunk that is too large binds unrelated information together and its embedding becomes an “average meaning”. A chunk that is too small breaks the semantics, and retrieval returns half a sentence. In practice you decide chunk_size, chunk_overlap, whether to keep the heading as context, and whether to split by characters, paragraphs, headings or tables.
| Document type | Suggestion |
|---|---|
| Fact-dense (FAQ, clauses) | Smaller chunks, so less unrelated content comes along |
| Procedures | Keep steps whole, never split one procedure |
| Long papers and specifications | Split by heading level first, then enforce a length limit |
The most stable approach is not to cut by a fixed number of characters. Respect semantic boundaries first, then enforce a length limit. There is no universal best chunk size: sweep it on your own evaluation set (see the evaluation sections below).
Hands-on: one document, three ways to cut it
The widget below chunks a made-up expense policy. Light-shaded text is the part shared with the previous chunk. A “cut sentence” is a sentence that no chunk contains in full, so even if it is retrieved the model only sees half of it. You can paste in your own document too.
- Fixed-length windows cut sentences. With chunk size 120 and no overlap, 9 of the 19 sentences are cut (the widget’s splitter also counts the title and the number and the name of each heading as sentences). At chunk size 60, 11 are cut.
- Overlap helps little, has no guarantee and costs storage. At chunk size 120, overlaps of 5, 10, 15 and 20 cut 7, 8, 9 and 8 sentences, which is not monotonic. A window can never hold a sentence longer than itself, and two sentences here are 122 and 133 characters long, so at size 120 some sentences stay cut whatever the overlap (4 at overlap 100, with 52 chunks and 5.50x redundancy). A guarantee needs a window longer than the longest sentence (133 characters in this document) and an overlap at least as long as that sentence: then some window always contains it whole. At chunk size 200 and overlap 133 no sentence is cut, at the price of 15 chunks and 2.64x redundancy (1.20x at size 120 and overlap 20).
- Splitting by sentence or paragraph never cuts a sentence. At chunk size 120, sentence splitting gives 11 chunks, 0 cut sentences and no redundancy (a sentence longer than the size stays whole, so a chunk can exceed 120 characters). Paragraph splitting gives 13 chunks at size 120, because a section longer than the size is packed by sentence; at size 400 every section fits and it gives 5 chunks (the title and four sections, 225 characters on average). That is what “respect semantic boundaries first, then enforce a length limit” means.
Step 3: metadata matters more than people think
RAG is often understood as “text vector search”, but high-quality systems almost always rely on metadata filters. Metadata is not only for showing the source in the UI. It changes the retrieval strategy directly:
| Metadata | What it is for |
|---|---|
| Access scope | Filter by permission before retrieval; chunks the user may not see should never become candidates |
| Update time | Filter by time window to get the latest material, or flag stale content |
| Document type, department | Narrow the scope first, then run dense retrieval inside the small set |
| Heading path, section | Show the source and prepend the heading to the chunk for context |
Without metadata, many retrieval mistakes are almost impossible to correct.
Step 4: embeddings and vector search
The small corpus used on this page
The code below shares one small corpus: 23 chunks from a made-up company handbook in six topics (travel expenses, account security, remote work, leave and attendance, system error codes, purchasing and backup), plus 12 queries, each labelled with the chunk it should hit. The queries come in three kinds: paraphrases that share few words with the target (such as “login credentials” for “password”), bare identifiers (such as E1042), and natural mixed questions. The corpus was built for demonstration and every policy in it is fictional.
The corpus and the queries (click to see the code)
chunks = {
"exp-scope": "Travel expense scope: transport, lodging and meal costs "
"on business trips are reimbursable; flights must be "
"economy class and high-speed rail second class.",
"exp-limit": "Lodging is capped by city tier: at most 600 yuan per "
"night in tier-one cities and at most 400 yuan per night "
"elsewhere.",
"exp-submit": "Expense claims must be submitted within 30 calendar days "
"after the trip ends; late claims will not be reimbursed.",
"exp-material": "A claim needs an electronic invoice, the itinerary and "
"the approval form; a claim missing any of them is sent "
"back.",
"exp-advance": "An advance must be requested 3 working days ahead, up "
"to 10000 yuan per request, and settled within 7 working "
"days after the trip.",
"acc-reset": "Password reset: click \"Forgot password\" in the "
"self-service portal and verify your identity with an SMS "
"code to set a new password.",
"acc-policy": "Information Security Policy IT-SEC-003 requires "
"passwords of at least 12 characters with upper and lower "
"case letters, digits and symbols.",
"acc-lock": "An account is locked for 30 minutes after 5 consecutive "
"wrong passwords and unlocks automatically afterwards.",
"acc-mfa": "Every employee must enable two-factor authentication within "
"the first week, using an authenticator app or a hardware "
"security key.",
"vpn-install": "Remote access to the intranet requires the company VPN "
"client, signing in with your company account and "
"two-factor authentication.",
"vpn-cert": "When the VPN reports \"certificate expired\", download a new "
"certificate from the self-service portal and import it "
"into the client; certificates last one year.",
"remote-policy": "With the approval of the department head, employees "
"may work remotely up to 2 days per week and must stay "
"online and join the regular meetings.",
"leave-annual": "Annual leave depends on total years of work: 5 days "
"for 1 to under 10 years, 10 days for 10 to under 20 "
"years and 15 days for 20 years or more.",
"leave-sick": "Sick leave needs a diagnosis certificate from a "
"hospital; up to three days is approved by the direct "
"manager, longer leave must be filed with HR (see "
"HR-LV-012).",
"attendance": "The company uses flexible hours with core hours from "
"10:00 to 16:00; everyone must work 8 hours a day.",
"comp-time": "Overtime on rest days can be taken as time off in lieu, "
"which must be used within 3 months of the overtime, or it "
"expires.",
"err-1041": "E1041: login session timed out and the user must sign in "
"again; sessions are valid for 8 hours by default.",
"err-1042": "E1042: database connection pool exhausted; check the "
"maximum connections setting and restart the affected "
"service.",
"err-1043": "E1043: disk usage above 90%; clean up logs or expand the "
"data disk.",
"err-1044": "E1044: the server certificate is about to expire; renew it "
"within 14 days before expiry.",
"err-1045": "E1045: request rate limited; each endpoint accepts at most "
"100 calls per minute, so retry later.",
"buy-threshold": "A single purchase above 5000 yuan needs quotes from "
"at least three suppliers and approval from the "
"department head.",
"backup": "The production database gets a full backup at 2 a.m. every "
"day, kept for 30 days, with a recovery drill every quarter.",
}
# (query, the chunk it should hit)
queries = [
("How late can I hand in receipts after coming back "
"from a trip?", "exp-submit"),
("I forgot my login credentials, what now?", "acc-reset"),
("How do I reach the company network from home?", "vpn-install"),
("What do I need to bring for a day off when I feel ill?", "leave-sick"),
("E1042", "err-1042"),
("What should I do about error code E1044?", "err-1044"),
("How long must passwords be under IT-SEC-003?", "acc-policy"),
("HR-LV-012", "leave-sick"),
("Can't reach the database, the error says the "
"connection pool is full", "err-1042"),
("Which documents must I upload with an expense claim?", "exp-material"),
("How much can I borrow in advance and when must I "
"pay it back?", "exp-advance"),
("How many wrong passwords before I get locked out?", "acc-lock"),
]
How an embedding model turns text into a vector
An embedding model maps a piece of text to a fixed-size vector , so that texts with similar meaning land close together. This page uses BAAI/bge-small-en-v1.5 from the BGE family (BERT architecture, 384 dimensions; the model card cites the C-Pack paper). Following the model card, we take the hidden state at the [CLS] position of the last layer and L2-normalize it. Similarity is cosine:
Once the vectors have unit length, cosine similarity equals the inner product, and the squared Euclidean distance is . So “largest inner product”, “largest cosine” and “smallest Euclidean distance” give the same ranking, and a vector store can use any of the three as long as both stored and query vectors are normalized.
import numpy as np
import torch
from transformers import AutoModel, AutoTokenizer
ids, texts = list(chunks), list(chunks.values())
name = "BAAI/bge-small-en-v1.5" # 384-dim vectors, taken at [CLS]
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
def embed(batch):
x = tok(batch, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
cls = model(**x).last_hidden_state[:, 0]
return torch.nn.functional.normalize(cls, dim=-1).numpy()
D = embed(texts) # one row per chunk, every row a unit vector
q = embed(["I forgot my login credentials, what now?"])[0]
sims = D @ q # inner product of unit vectors = cosine similarity
print(D.shape)
for j in np.argsort(-sims)[:3]:
print(f"{sims[j]:.3f} {ids[j]}")
print(np.allclose(((D - q) ** 2).sum(1), 2 - 2 * sims, atol=1e-5))
Output:
(23, 384)
0.727 acc-reset
0.657 err-1041
0.656 acc-lock
True
Here the right chunk acc-reset is first, ahead of err-1041 by 0.07. The model card reminds you that retrieval cares about the relative order of scores, and that absolute values have no general meaning; if you filter by similarity, choose the threshold on your own data. The final True confirms the identity above. The BGE models also support a query instruction (a short prefix for short queries); for v1.5 the card says retrieval degrades only slightly without it, and this page does not use it.
How big is the index
The main cost of a vector index is memory: vectors of dimensions at bytes each take bytes.
for n, d in [(10**5, 384), (10**6, 768), (10**7, 1024)]:
f32, i8 = n * d * 4 / 1e9, n * d / 1e9 # 4 bytes per float32, 1 per int8
print(f"{n:>10,} x {d:>4} dims: float32 {f32:6.2f} GB, int8 {i8:5.2f} GB")
Output:
100,000 x 384 dims: float32 0.15 GB, int8 0.04 GB
1,000,000 x 768 dims: float32 3.07 GB, int8 0.77 GB
10,000,000 x 1024 dims: float32 40.96 GB, int8 10.24 GB
GB here means bytes, and the numbers cover the vectors only, not the neighbor lists of a graph index such as HNSW, the metadata or the original text. int8 scalar quantization shrinks each dimension to one byte at some cost in retrieval accuracy, which you should confirm on your own evaluation set.
Exact versus approximate search
With a few tens of thousands of vectors, one matrix product is an exact brute-force search that is fast enough, and the D @ q above is exactly that. Beyond that you switch to an approximate nearest neighbor (ANN) index, trading a little accuracy for speed. HNSW searches greedily over a multi-layer neighbor graph (paper); IVF clusters the vectors and scans only the few clusters nearest to the query; PQ compresses vectors into short codes to save memory. FAISS packages these indexes as a library (paper).
Choosing a vector store
For a first RAG system, do not spend all your effort on this choice, but know where each option leans:
| Type | Examples | Good for | Watch out for |
|---|---|---|---|
| Local library | FAISS | Prototypes, offline batch jobs, embedding in your own service | Persistence, filtering and updates are up to you |
| Database extension | pgvector (PostgreSQL) | You already run PostgreSQL, moderate scale, filtering together with business data | Check performance and tuning at very large scale |
| Search engine | Elasticsearch, OpenSearch | An existing search cluster, keyword and vector search in one system | The embedding model and analyzers are yours to configure |
| Dedicated vector service | Milvus, Qdrant and similar | High concurrency, multi-tenancy, complex filters, horizontal scaling | One more system to operate |
The real criteria are not popularity but data size, whether you need access control, what database stack you already have, and how much operational complexity the team can accept.
Step 5: retrieval is more than dense search
Many people encode the question into a vector and run similarity search the first time they build RAG. That is a fine starting point but not always the best one. The DPR paper (Karpukhin et al., 2020) reports that, on open-domain QA datasets, dense retrieval beat a strong Lucene-BM25 baseline by roughly 9 to 19 points of absolute top-20 accuracy. On your own data and queries, which one wins depends on the kind of query.
| Strategy | Good at | Weak at |
|---|---|---|
| Dense retrieval | Semantic matches, paraphrases, synonyms | Identifiers, model numbers, proper nouns, numeric detail |
| Keyword retrieval (BM25) | Terms, identifiers, commands, clause numbers | Nothing to match when no word is shared (“credentials” versus “password”) |
| Hybrid retrieval | The two complement each other, suits mixed query distributions | You must choose a fusion method; latency and complexity go up |
| Query rewriting and multi-query retrieval | Colloquial, ambiguous or multi-part questions | One more model call, with extra latency and cost |
The best retrieval method differs from question to question. Standardizing on a single retriever makes the system narrow.
BM25: a strong baseline for word matching
BM25 scores a chunk by how often the query terms occur in it and how rare each term is:
Here is the number of times term occurs in chunk , is the chunk length, is the average chunk length, is the number of chunks and is the number of chunks containing . The parameter controls how quickly term frequency saturates (ten occurrences do not score ten times one occurrence), and controls length normalization (longer chunks contain more words by default and need a discount). Lucene’s defaults are and , and it writes the IDF as to keep it non-negative (see the Lucene 9.10 documentation). For the background on BM25, see the survey by Robertson and Zaragoza.
The code below is a direct translation of the formula. For simplicity the tokenizer lowercases and splits on non-alphanumerics, with no stemming and no stop-word list, which puts BM25 at a disadvantage on natural English questions (you will see this in the results).
import math
import re
from collections import Counter
def tokenize(text):
"""Lowercase words and numbers; no stemming, no stop-word list."""
return re.findall(r"[a-z0-9]+", text.lower())
docs = [Counter(tokenize(t)) for t in texts]
lens = [sum(d.values()) for d in docs]
N, avgdl = len(docs), sum(lens) / len(docs)
df = Counter(t for d in docs for t in d) # chunks containing the term
def bm25(query, k1=1.2, b=0.75):
scores = np.zeros(N)
for t in set(tokenize(query)) & set(df):
idf = math.log(1 + (N - df[t] + 0.5) / (df[t] + 0.5))
for j, d in enumerate(docs):
if t in d:
norm = d[t] + k1 * (1 - b + b * lens[j] / avgdl)
scores[j] += idf * d[t] * (k1 + 1) / norm
return scores
scores = bm25("Which documents must I upload with an expense claim?")
for j in np.argsort(-scores)[:3]:
print(f"{scores[j]:5.2f} {ids[j]}")
Output:
5.32 exp-material
3.46 comp-time
3.34 exp-submit
The first hit shares just “claim” and “an” with the question: the chunk lists an invoice, an itinerary and an approval form and never says “documents” or “upload”. The runner-up, comp-time, is about time off in lieu of overtime and scores only because it shares “which” and “must” with the question. BM25 reads word overlap, and without a stop-word list, filler words count.
RRF: fusion by rank
Dense retrieval scores are cosines (in ) while BM25 scores have no upper bound, so the two cannot simply be added. Reciprocal rank fusion (RRF) sidesteps scores and uses only the rank within each list:
is the set of rankings, is the rank of in ranking (counting from 1), and a chunk missing from a list adds nothing. The constant comes from the paper by Cormack et al. (2009): they fixed it in a pilot experiment, and report that was near-optimal while the choice was not critical. Highly ranked chunks contribute more, and lower-ranked ones do not vanish.
def top(scores, k=5, positive=False):
order = [int(j) for j in np.argsort(-scores)]
return [j for j in order if scores[j] > 0 or not positive][:k]
def rrf(rankings, k=60):
fused = Counter()
for ranking in rankings:
for pos, j in enumerate(ranking, start=1):
fused[j] += 1 / (k + pos)
return [j for j, _ in fused.most_common()]
query = "E1042"
by_dense = top(D @ embed([query])[0])
by_bm25 = top(bm25(query), positive=True)
for label, ranking in [("dense", by_dense), ("bm25", by_bm25),
("fused", rrf([by_dense, by_bm25]))]:
print(f"{label:5}", [ids[j] for j in ranking[:3]])
Output:
dense ['err-1044', 'err-1043', 'err-1042']
bm25 ['err-1042']
fused ['err-1042', 'err-1044', 'err-1043']
For the bare identifier E1042, dense retrieval ranks the right chunk only third, behind two other error codes: the five error-code chunks differ mainly in one number, which an embedding model barely separates. BM25 puts it first because the token e1042 occurs in exactly one chunk. After fusion the right chunk is first: it appears in both lists and collects from BM25 plus for its third place in the dense list, about 0.0323, while the dense list’s first choice has only . That is the strength of RRF: neither list has to be right on every query. Its limit is that it reads only ranks and ignores how confident a list is, so agreement between lists counts for more than one confident list.
Query rewriting
You can also rewrite the query before retrieval, at the price of one more model call:
| Technique | Idea | Cost |
|---|---|---|
| Conversation rewriting | Turn references in a multi-turn chat (“it”, “the previous one”) into a standalone question | One extra call |
| Multi-query expansion | Have the model rephrase the question several ways, retrieve for each, and fuse with RRF | Retrievals multiplied by the number of rephrasings |
| Query decomposition | Split a compound question into sub-questions and retrieve for each | Latency and orchestration complexity |
| HyDE | Ask the model to write a hypothetical answer first, then retrieve with its embedding (paper) | One extra generation, and the model’s errors can leak into retrieval |
Step 6: reranking decides the gap between “retrieved” and “ranked first”
The top-k that retrieval returns is not necessarily the top-k that belongs in the context: the retrieval stage favors coverage over final ranking precision. A reranker judges relevance more carefully for each “query plus candidate chunk” and moves the truly relevant fragments up. Typical problems it can fix: dense retrieval ranks a chunk that is semantically close but does not answer the question too high, or several chunks are related to the question and the key evidence is buried below them.
Reranking uses a cross-encoder: the query and the chunk are concatenated into one input, so the model reads both at once and outputs a relevance score directly. It differs from the bi-encoder used for retrieval mainly in cost:
| Bi-encoder (dense retrieval) | Cross-encoder (reranking) | |
|---|---|---|
| Input | Query and chunk encoded separately | Query and chunk encoded together |
| Chunk representation | Computed offline and stored in the index | Cannot be precomputed |
| Compute per query | Encode one query, then a vector search | One forward pass per candidate, linear in the number of candidates |
| Precision | Coarser, suited to retrieval | Finer, suited to the final ranking |
That is why a cross-encoder runs only on the few dozen candidates retrieval returns. Nogueira and Cho (2019) were among the first to use BERT this way for passage reranking, and the BGE model card also recommends bge-reranker for reranking the top-k returned by an embedding model.
from transformers import AutoModelForSequenceClassification
rname = "BAAI/bge-reranker-base" # cross-encoder: reads (query, chunk) jointly
rtok = AutoTokenizer.from_pretrained(rname)
reranker = AutoModelForSequenceClassification.from_pretrained(rname)
def rerank(query, cands):
x = rtok([query] * len(cands), [texts[j] for j in cands],
padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
scores = reranker(**x).logits.view(-1)
order = scores.argsort(descending=True)
return [cands[i] for i in order]
query = "What do I need to bring for a day off when I feel ill?"
pool = rrf([top(D @ embed([query])[0]), top(bm25(query), positive=True)])
print("fused ", [ids[j] for j in pool[:4]])
print("reranked", [ids[j] for j in rerank(query, pool)[:4]])
Output:
fused ['leave-annual', 'comp-time', 'leave-sick', 'backup']
reranked ['exp-material', 'leave-sick', 'comp-time', 'leave-annual']
The right chunk leave-sick is the dense list’s first choice, but BM25 can only match filler words such as “a” and “to” in it (the chunk says “days”, not “day”), so it gets a single vote. Two chunks that appear in both lists overtake it, and it ends third after fusion. The cross-encoder moves it up to second, but puts exp-material first, a chunk that shares the “what do I need” intent and not the topic. A reranker is another model with its own mistakes. Its scores have no fixed range either: only the relative order is meaningful, so do not hard-code an absolute threshold on them.
Hands-on: are hybrid retrieval and reranking worth it?
Now chain the steps into four systems and compare them on the 12 queries: dense retrieval, BM25, the two fused with RRF, and the fused list reranked. Each retriever returns its top 5 (BM25 keeps only chunks with a score above 0), and the reranker scores all fused candidates. There are three metrics, and each query here has exactly one chunk it should hit:
is the rank of the right chunk, and a chunk outside the top 5 scores 0 (it contributes 0 to MRR). With several relevant chunks, Hit@k generalizes to ; here each query has one relevant chunk, so Recall@5 equals Hit@5.
def dense(q):
return top(D @ embed([q])[0])
def sparse(q):
return top(bm25(q), positive=True)
def hybrid(q):
return rrf([dense(q), sparse(q)])
def hybrid_rerank(q):
return rerank(q, hybrid(q))
def rank_of(ranking, gold, k=5):
"""Rank of the gold chunk within the first k, or 0 if absent."""
ranking, j = ranking[:k], ids.index(gold)
return ranking.index(j) + 1 if j in ranking else 0
systems = {"dense": dense, "bm25": sparse, "rrf": hybrid,
"rerank": hybrid_rerank}
ranks = {m: [rank_of(f(q), g) for q, g in queries]
for m, f in systems.items()}
print(" ", *(f"{m:>7}" for m in ranks))
for i in range(len(queries)):
print(f"Q{i + 1:<3}", *(f"{r[i] or '-':>7}" for r in ranks.values()))
print("\n hit@1 hit@3 recall@5 mrr@5")
for m, r in ranks.items():
n = len(r)
print(f"{m:>7} {sum(x == 1 for x in r) / n:6.2f}"
f" {sum(1 <= x <= 3 for x in r) / n:6.2f}"
f" {sum(x > 0 for x in r) / n:9.2f}"
f" {sum(1 / x for x in r if x) / n:7.2f}")
Output (- means the right chunk is not in the top 5; the first table gives its rank for Q1 to Q12):
dense bm25 rrf rerank
Q1 1 1 1 1
Q2 1 2 1 1
Q3 1 2 1 1
Q4 1 - 3 2
Q5 3 1 1 1
Q6 2 1 1 1
Q7 1 1 1 1
Q8 1 1 1 1
Q9 1 1 1 1
Q10 1 1 1 1
Q11 1 3 1 1
Q12 1 1 1 1
hit@1 hit@3 recall@5 mrr@5
dense 0.83 1.00 1.00 0.90
bm25 0.67 0.92 0.92 0.78
rrf 0.92 1.00 1.00 0.94
rerank 0.92 1.00 1.00 0.96
| Method | Hit@1 | Hit@3 | Recall@5 | MRR@5 |
|---|---|---|---|---|
| Dense | 0.83 | 1.00 | 1.00 | 0.90 |
| BM25 | 0.67 | 0.92 | 0.92 | 0.78 |
| RRF fusion | 0.92 | 1.00 | 1.00 | 0.94 |
| Fusion plus rerank | 0.92 | 1.00 | 1.00 | 0.96 |
- The two retrievers fail differently. Dense retrieval is strong on natural questions but slips on the two error-code queries (Q5
E1042ranks 3rd, Q6 ranks 2nd), where neighboring codes look alike. BM25 gets both right, but with no stemming or stop-word list it is weak on natural questions: for Q4 the right chunk is not in the top 5 at all, and Q2, Q3 and Q11 are pushed down to 2nd, 2nd and 3rd. - Fusion beats either alone on the first rank. RRF reaches Hit@1 of 0.92, above both dense retrieval (0.83) and BM25 (0.67), and keeps Recall@5 at 1.00.
- The reranker changes little here. Fusion had already put the right chunk first for 11 of the 12 queries, so there is little left to fix; MRR moves from 0.94 to 0.96 because Q4 improves from 3rd to 2nd. Whether a reranker pays for its latency on your data is again something to measure.
This is a small experiment that demonstrates mechanisms, not a benchmark. It has only 23 chunks and 12 queries, so one query is worth 8.3 points of Hit@1; the queries were built on purpose to cover paraphrases, identifiers and mixed questions; there are no confidence intervals; and you should not use it to rank BM25, BGE or any reranker. The only takeaway is that hybrid retrieval and reranking fix different failures. Redo it with your own queries and labels to learn whether they are worth it for your data.
The widget below turns this rank table into something you can compute yourself: pick a retrieval system and drag k, and Hit@k and MRR@k are recomputed live from the same ranks — watch how RRF fusion gets a perfect Recall@5 while Hit@1 stays at 92%.
Step 7: context assembly is not “paste in the whole top-k”
Many first versions of a RAG system retrieve the top 5 or 10 chunks and concatenate them straight into the prompt. That causes three problems: the context may be too long, several chunks repeat each other, and key evidence is diluted by long irrelevant passages. This ties into the Lost in the Middle findings: a long context is not the same as high utilization, and models use evidence best at the beginning or end and worse in the middle. Better context assembly usually does the following:
- remove duplicates and near-duplicates;
- group chunks by document or section;
- put the most important evidence first (or last);
- limit the total number of tokens, and add a relevance threshold so that fewer chunks is better than noise;
- attach a number and a source to every chunk, so the model can cite it and people can verify it.
def build_prompt(query, ranking, budget=300):
"""Take chunks in rank order within a character budget, numbered."""
picked, used = [], 0
for j in ranking:
if used + len(texts[j]) > budget:
break
picked.append(j)
used += len(texts[j])
context = "\n".join(f"[{n}] {texts[j]}"
for n, j in enumerate(picked, start=1))
return ("Answer only from the sources below. If they do not contain the "
"answer, say so, and cite sources as [number].\n\n"
f"Sources:\n{context}\n\nQuestion: {query}")
query = "How much can I borrow in advance and when must I pay it back?"
prompt = build_prompt(query, hybrid_rerank(query))
for line in prompt.splitlines(): # show only the first 60 characters
print(line[:60] + ("..." if len(line) > 60 else ""))
Output:
Answer only from the sources below. If they do not contain t...
Sources:
[1] An advance must be requested 3 working days ahead, up to...
[2] Annual leave depends on total years of work: 5 days for ...
Question: How much can I borrow in advance and when must I p...
Source [2], the annual leave rule, has nothing to do with the question. It came along only because the character budget was not used up yet. That is the typical result of truncating by budget alone: either add a relevance threshold (the gap to the first chunk, or an absolute value, calibrated on your own data), cap the number of chunks, or tell the model in the prompt that it may ignore unrelated sources. The character budget is only illustrative; in practice count the generator’s tokens.
The prompt itself should stress boundaries and evidence: answer only from the given sources, admit when they are insufficient, cite sources, and when sources conflict describe the difference instead of blending them. The goal of a RAG prompt is not to make the model more eloquent but to make it improvise less. Why models improvise, and how to measure whether they dare to say they do not know, is covered in Hallucination and Calibration; retrieved pages and documents can also carry hidden instructions, see Prompt Injection and Jailbreaks. For a systematic treatment of prompt design see Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation, and for structured answers see Structured Outputs and Function Calling.
How to evaluate a whole RAG system
RAG evaluation cannot look only at the final answer, because the mistake can come from any layer. Each layer has its own metrics and needs its own data:
| Layer | What to look at | Typical metrics and methods |
|---|---|---|
| Retrieval | Whether the candidates contain the right evidence | Hit@k, Recall@k, MRR, on a labelled query set |
| Ranking | Whether the right evidence ranks near the top | Hit@1, MRR, nDCG; compute before and after reranking |
| Generation | Whether the answer is correct, faithful to the evidence, and declines when evidence is missing | Human review, or an LLM judge (see LLM-as-a-Judge); Ragas is one example of automated evaluation of this kind |
| System | Latency, cost, stability on long documents | Time per stage, token usage, P95 latency |
If you lump all of this into “do users like it”, you cannot tell which layer to improve. You need a fixed, independent evaluation set and a library of failures: label a few dozen to a few hundred real queries and rerun them after every change (a new embedding model, a different chunk size, another fusion). For evaluation methodology and statistical confidence, see LLM Evaluation Methodology.
A practical troubleshooting order
When a RAG system performs badly, work through these in order:
- Does the retrieved list contain the right evidence (Recall@k)?
- If yes, is the right evidence ranked high enough (Hit@1, MRR)?
- If so, is the assembled context diluted by noise?
- If it still fails, does the prompt clearly require answers based on evidence?
- Only then ask whether the model itself is too weak.
Many teams blame “the model is not big enough” when retrieval was already wrong. The figure compresses the order into a reminder: do not swap in a bigger model first, narrow the problem down along the evidence chain instead:
Common mistakes
| Mistake | Why it is wrong | What to do |
|---|---|---|
| Treating RAG as a universal brain booster | Complex planning, tool use and multi-step decisions cannot be solved by retrieval | Use RAG as the knowledge layer, together with tools and workflows |
| Dense retrieval only | Identifier-like queries lose rank (Q5 and Q6 here come 3rd and 2nd) | Add BM25 and fuse with RRF |
| Vector retrieval without metadata filters | In enterprises, permissions, time and document type matter just as much | Filter first, then retrieve |
| The bigger the top-k the better | More chunks are not necessarily more accurate and can dilute the key evidence | Retrieve wide, then rerank, deduplicate and truncate |
| A fixed similarity threshold | The absolute similarity value has no general meaning | Calibrate on your own data, or use relative ranks only |
| No independent evaluation set | You cannot tell whether a change is an improvement or luck | A fixed evaluation set plus a library of failures, rerun after every change |
Summary and exercises
Key points:
- RAG is “retrieve first, then generate”: offline indexing (cleaning, chunking, embedding) and online answering (retrieval, fusion, reranking, assembly, generation) can be optimized independently.
- Dense retrieval is good at paraphrases and BM25 at identifiers and terms, and their failures tend to differ. RRF computes from ranks alone and needs no score alignment.
- A cross-encoder reads the query and chunk together, which is more accurate but cannot be precomputed, so it runs only on the few candidates retrieval returns.
- Evaluate in layers: Hit@k, Recall@k and MRR for retrieval and ranking, plus faithfulness for generation. In this page’s small experiment Hit@1 goes from 0.83 (dense) and 0.67 (BM25) to 0.92 (fusion and rerank), a demonstration of the mechanism only.
- Troubleshoot along the evidence chain: is the evidence retrieved, is it ranked high, is the context diluted, does the prompt constrain, and only then suspect the model.
Quick self-check
1. In RRF fusion, a chunk is ranked first by dense retrieval and absent from the BM25 list. With k=60, what is its fused score?
- 1
- 0.5
- 1/61, about 0.0164
- It depends on the cosine similarity the dense retriever gave it
RRF uses ranks only: this list contributes 1/(60+1), and the list where the chunk is absent adds nothing. The size of the scores plays no part, which is why RRF needs no alignment between retrievers.
2. Why is a cross-encoder usually run only on the few dozen candidates retrieval returns, not on the whole corpus?
- It cannot handle long text
- It has to run the model on each (query, chunk) pair together, which cannot be precomputed, so the cost grows linearly with the number of candidates
- Its output cannot be used for ranking
- It must be fine-tuned on your data before it can score
A bi-encoder can precompute chunk vectors offline and encode only the query at search time. A cross-encoder needs a full forward pass per candidate, so it is used for the final ranking after retrieval.
3. When all vectors are L2-normalized, which statement is true?
- Cosine similarity and inner product rank differently
- The largest inner product is the smallest Euclidean distance
- The similarity can be read directly as a probability
- Normalization only matters for Chinese models
For unit vectors, the squared distance is 2 minus twice the inner product, so a larger inner product means a smaller distance, and cosine equals the inner product.
4. The right chunk for a query is not in the top 5 of any retriever. Where should you look first?
- Switch to a larger generator
- Reword the prompt
- Cleaning, chunking, the embedding model and the retrieval strategy
- Only raise the number of candidates sent to the reranker
If the evidence never becomes a candidate, reranking, assembly and prompting cannot recover it. Follow the evidence chain from the front and fix retrieval first.
5. For Q4 (the sick-leave question), dense retrieval ranks the right chunk first, yet after fusion it is third. What explains this?
- The RRF implementation is wrong
- BM25 matched only filler words, and the chunks it matched also appeared in the dense list; RRF rewards agreement between lists, so they overtook the right chunk
- The dense retriever’s score for the right chunk dropped
- RRF always moves the first dense result down
The right chunk gets only 1/61, about 0.016, from the dense list. Two other chunks appear in both lists: leave-annual (dense 2nd, BM25 3rd) scores about 0.032 and comp-time (dense 3rd, BM25 5th) about 0.031, so both rank higher. Noise that both lists agree on can beat a single correct vote.
6. Why is it a bad idea to hard-code “only use results with similarity above 0.8”?
- Different embedding models have different similarity distributions, so absolute values carry no general meaning and the threshold must be calibrated on your data
- An inner product can never exceed 0.8
- A threshold makes retrieval slower
- Cosine similarity can only be 0 or 1
The BGE model card says explicitly that retrieval cares about relative order and not absolute values. If you need a threshold, choose it from the similarity distribution on your own data.
Exercises:
- Document A is ranked 1st by dense retrieval and 11th by BM25. Document B is ranked 4th by both. With k=60, which has the higher RRF score?
- How much memory do 1 million 768-dimensional float32 vectors take? And as int8? Does the number include the index structure?
- Set the BM25 parameter to 0. What does the score become, and what is wrong with such a retriever?
- Your production system has 100,000 chunks and a Recall@5 of 0.80, and you want 0.90. In what order do you investigate and try things?
Reference answers
- A scores and B scores , so B is higher. RRF prefers chunks that are near the top of both lists over a chunk that is very high in one list and far down in the other.
- bytes, about 3.07 GB; at one byte per dimension int8 takes about 0.77 GB. The number does not include an index structure: it covers the vectors only, and the neighbor lists of a graph index such as HNSW, the metadata and the original text come on top.
- With the denominator is and the numerator is , so they cancel: each matched term contributes only , regardless of its count or the chunk length. It degenerates into “which terms matched, and how rare they are”. The problem is that ten occurrences count the same as one, and long and short chunks are no longer told apart.
- Take the failing queries and look at where the right chunk is. If it is not even in the top 50, the problem is on the retrieval side: check cleaning and chunking (are chunks cut, is heading context kept), whether the embedding model suits your domain, and whether identifier-like queries need BM25 in a hybrid setup. If it is in the top 50 but not the top 5, the problem is on the ranking side: add a reranker or query rewriting. After each change recompute Recall@5 on a fixed evaluation set and keep only the changes that help.
Further reading
-
For the original paper, see Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks; for a map of the methods that came after it, read the RAG survey explainer.
-
For why long contexts hurt RAG, read the Lost in the Middle explainer and Long Context: Position Extrapolation, Training Recipes and Cost.
-
To see where embeddings come from, read Tokenizers and Embeddings: BPE, Vocabulary Size and the Embedding Table.
-
For prompt design and structured outputs in applications, see Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation and Structured Outputs and Function Calling: From JSON Mode to Constrained Decoding.
-
Retrieval and ranking: Karpukhin et al., Dense Passage Retrieval; Cormack et al., Reciprocal Rank Fusion; Nogueira and Cho, Passage Re-ranking with BERT; Gao et al., HyDE.
-
Models and indexes: the model cards of BAAI/bge-small-en-v1.5 and BAAI/bge-reranker-base; HNSW and The Faiss library.
-
Evaluation: Ovadia et al., Fine-Tuning or Retrieval?; Es et al., Ragas.
-
Anthropic, Effective Context Engineering for AI Agents (2025): a systematic summary of context engineering (compaction, truncation, isolating untrusted content), much of which applies directly to RAG context assembly.
FAQ
- Should I use RAG or fine-tuning?
- Use RAG when the model has to work with external knowledge that changes (company documents, recent material) and the answer should cite its source: updating knowledge means updating the index, and answers can be audited. Consider fine-tuning when you want to change the model's behavior, tone or output format. In the controlled comparison by Ovadia et al. (2023), unsupervised fine-tuning gave only some improvement, while RAG did better on both knowledge the model had seen and entirely new knowledge. The two can also be combined.
- What are the parts of a RAG system?
- Offline: document cleaning, chunking and metadata design, embedding and building the index. Online: query understanding, retrieval, fusion and reranking, context assembly and generation. An evaluation loop sits around both. Chunking sets the ceiling for recall, reranking decides whether the right evidence comes first, and context assembly decides what the model actually sees.
- Do I need dense retrieval, BM25 and a reranker?
- It depends on the queries. Dense retrieval is good at paraphrases, BM25 at identifiers and rare terms, and their failures tend to differ. RRF uses ranks only, so the two score scales need no alignment. A cross-encoder scores each (query, chunk) pair jointly, which is more accurate but slower. In this page's 23-chunk, 12-query experiment, Hit@1 is 0.83 for dense and 0.67 for BM25, and 0.92 after fusion. That is a demonstration of the mechanism, so measure on your own data.
- Where do I look first when a RAG answer is wrong?
- Follow the evidence chain from the front. First check whether the right evidence is in the top-k; if not, look at cleaning, chunking, embeddings, metadata filters and the retrieval strategy. Then check whether it is ranked high enough (reranker, query rewriting, hybrid retrieval), then whether the assembled context is diluted by noise, and suspect the model last.
- How do I evaluate a RAG system?
- Evaluate in layers. Retrieval: Recall@k, Hit@k and MRR on a labelled query set. Ranking: the rank of the right evidence. Generation: whether the answer is correct, faithful to the evidence, and declines when the evidence is insufficient, judged by humans or an LLM judge. System: latency and cost. Keep a fixed evaluation set and a library of failures, or you cannot tell whether a change really helped.