Why a language model needs a retrieval step
A language model's weights are a snapshot. Whatever facts, prices, or policy clauses existed at training time are compressed into billions of floating point numbers, and nothing that happens afterward changes them. For open-ended writing that is acceptable; for a support bot answering about today's refund window it is a liability: the model will recite last year's policy with the same fluency it uses for well-established physics. Fine-tuning on the new corpus is possible but expensive, slow to refresh, and fragile when the domain shifts weekly.
Retrieval-augmented generation moves the fresh knowledge out of the weights and into an external index that can be updated in seconds. The model keeps its language ability; a retriever supplies the facts for each request. The practical payoff is threefold. Answers can cite the exact passage they came from, a corpus edit requires re-embedding documents rather than retraining a model, and one generator can serve many disjoint corpora without cross-contamination between them.
Chunking decides what the retriever can find
Almost every production RAG failure traces back to chunking. Embeddings are computed per chunk, so the vector representing a passage has to mean one coherent thing. Chunks that are too large average a heading, three unrelated paragraphs, and a table into a single direction that matches no query well. Chunks that are too small lose the qualifiers â the "except for annual plans" clause ends up in a different chunk from the sentence it modifies, and the retriever happily returns the half that supports the wrong answer.
Size is therefore a semantic decision, not a performance one. Three hundred to five hundred tokens works for FAQ-style prose, five hundred to eight hundred for technical documentation, and structured content should split on its own boundaries: headings for markdown, slides for decks, worksheet tables for spreadsheets. Overlap of ten to twenty percent exists solely to keep a sentence that straddles a boundary searchable from both sides; more overlap than that mostly produces duplicate hits that crowd the top-k list.
A splitter that respects paragraph structure beats slicing by character count, because double newlines usually mark discourse boundaries. Keep the source path in metadata from the start â every later debugging step, from answering "why did this passage appear" to rendering citations, needs to know which document a chunk came from.
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.documents import Document
def chunk_document(text, source, size=480, overlap=80):
splitter = RecursiveCharacterTextSplitter(
chunk_size=size,
chunk_overlap=overlap,
separators=["\n\n", "\n", ". ", " ", ""],
keep_separator=True,
)
pieces = splitter.split_text(text)
return [
Document(page_content=p, metadata={"source": source, "chunk": i})
for i, p in enumerate(pieces)
]
sample = (
"The enterprise plan includes priority support.\n\n"
"Annual plans are billed upfront and can be cancelled within 30 days. "
"Monthly plans renew automatically unless cancelled before the next cycle.\n\n"
"Refunds are issued to the original payment method within five business days."
)
for doc in chunk_document(sample, "billing-policy.md", size=60, overlap=10):
print(doc.metadata["chunk"], repr(doc.page_content[:60]))
Dense retrieval and the index you actually need
Dense retrieval encodes the query and each chunk into the same vector space with a bi-encoder, then ranks by cosine similarity or inner product. The key property is that encoding is independent: the query embedding costs one forward pass no matter how large the corpus is, which is what makes search scalable. What you lose is exactness â approximate nearest neighbor indexes trade a little recall for orders-of-magnitude speed.
For corpora under roughly one hundred thousand chunks, an exact flat index is both simple and fast enough; brute force over fifty thousand vectors of dimension 384 is a few milliseconds on a CPU. Beyond that, an HNSW graph gives near-constant-time queries with memory overhead about the size of the vectors themselves, while IVF-PQ compresses vectors to fit memory at the cost of tuning a cluster count. Whatever index you pick, measure recall of the approximate index against exact search on a sample of real queries before shipping, because an index tuned for speed can silently drop the correct chunk out of the top ten.
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
chunks = [
"Enterprise plans include a dedicated support engineer and 99.9% uptime SLA.",
"Monthly subscriptions renew automatically unless cancelled a day before renewal.",
"Kubernetes raises OOMKilled when a container exceeds its memory limit.",
"Refunds return to the original payment method within five business days.",
]
embeddings = model.encode(chunks, normalize_embeddings=True).astype("float32")
index = faiss.IndexFlatIP(embeddings.shape[1])
index.add(embeddings)
def retrieve(query, k=2):
q = model.encode([query], normalize_embeddings=True).astype("float32")
scores, ids = index.search(q, k)
return [(chunks[i], float(s)) for i, s in zip(ids[0], scores[0])]
for text, score in retrieve("Can I get my money back after cancelling?"):
print(f"{score:.3f} {text}")
# 0.612 Refunds return to the original payment method within five business days.
# 0.401 Monthly subscriptions renew automatically unless cancelled a day before renewal.
Note the inner-product index over normalized vectors: normalization turns inner product into cosine, and the search returns scores you can threshold directly. A score floor matters more than people expect â a payroll query matched against Kubernetes notes still returns five results that look fine in a log until someone reads the answers they produced.
Hybrid search and the reranker
BM25 and dense embeddings fail on different inputs, which is why combining them is the cheapest quality win in the whole pipeline. Keyword search nails exact identifiers â CVE numbers, error codes, product SKUs â and dense search handles paraphrase, typos, and questions phrased differently from the document. "OOMKilled container exit 137" is a lexical problem; "why did my pod restart overnight" is a semantic one; real traffic mixes both.
Fusion is usually done with reciprocal rank fusion rather than score averaging, because BM25 and cosine scores live on incomparable scales. Reciprocal rank fusion uses only rank positions, so it needs no calibration: each retriever contributes one over its rank plus a smoothing constant, and the sums decide the order. After fusion, a cross-encoder reranker reads the query and each candidate chunk in one pass and produces a proper relevance score â slower than the bi-encoder by orders of magnitude, which is why it only ever sees the top twenty candidates.
| Stage | Algorithm | Typical latency | What it fixes |
|---|---|---|---|
| Dense first stage | MiniLM bi-encoder plus HNSW | 5â20 ms | Paraphrase, short questions |
| Lexical first stage | BM25 | 2â10 ms | Identifiers, rare terms |
| Fusion | Reciprocal rank fusion | under 1 ms | Mixed query styles |
| Reranking | Cross-encoder over top 20 | 50â150 ms | Precision at rank 1 |
| Generation | LLM with citation rules | 300â2000 ms | Grounded answer text |
import numpy as np
from rank_bm25 import BM25Okapi
def reciprocal_rank_fusion(rankings, smoothing=60):
scores = {}
for ranking in rankings:
for rank, idx in enumerate(ranking, start=1):
scores[idx] = scores.get(idx, 0.0) + 1.0 / (smoothing + rank)
return sorted(scores, key=scores.get, reverse=True)
bm25 = BM25Okapi([c.lower().split() for c in chunks])
def hybrid_search(query, k=2):
q = model.encode([query], normalize_embeddings=True).astype("float32")
_, dense_ids = index.search(q, len(chunks))
sparse_scores = bm25.get_scores(query.lower().split())
sparse_ids = list(np.argsort(sparse_scores)[::-1])
fused = reciprocal_rank_fusion([list(dense_ids[0]), sparse_ids])
return [(chunks[i], i) for i in fused[:k]]
for text, i in hybrid_search("pod restarted overnight OOMKilled"):
print(i, text)
Grounding the prompt so the model stays honest
Retrieval improves the odds that the right fact reaches the model, but it does not force the model to use it. Left unconstrained, an instruction-tuned LLM blends the excerpts with its parametric memory and produces an answer that is fluent, partly grounded, and impossible to audit. The fix is mostly prompt discipline: state that the excerpts are the only allowed source, require a citation marker after each factual claim, and define an explicit refusal string for the case where the context does not contain the answer.
Chunk order in the prompt also matters. Long-context models show recency and primacy bias, so information buried in the middle of a long context block is used less reliably than information at either end. Putting the highest-ranked chunks first and keeping total context well under the model's limit is safer than dumping every candidate in and hoping attention sorts it out. Citation markers pay off twice: users can verify claims, and a claim tagged with an excerpt number can be checked against that excerpt mechanically during evaluation.
def build_prompt(query, hits):
context = "\n\n".join(
f"[{n}] {text}" for n, (text, _) in enumerate(hits, start=1)
)
return f"""Answer using only the excerpts below.
Rules:
- Use only facts present in the excerpts.
- Cite the excerpt number after each claim, like [2].
- If the excerpts do not contain the answer, reply exactly: NOT IN CONTEXT.
Excerpts:
{context}
Question: {query}
Answer:"""
prompt = build_prompt(
"What is the refund window for annual plans?",
retrieve("What is the refund window for annual plans?"),
)
print(prompt[:300])
đĄLog the retrieved chunks, not just the answer
When RAG is the wrong architecture
Retrieval is not free quality. Every request pays for an index query, a reranker pass, a longer prompt, and the failure modes that come with a multi-stage pipeline â an embedding model upgrade can reorder results silently until complaints arrive. Three situations routinely argue against it.
First, when the entire knowledge base fits comfortably in the context window, say a forty-page policy document, plain long-context prompting is simpler and has no retrieval recall to lose. Second, when the knowledge is a live value â a stock price, a ticket status, a feature flag â a database lookup with a templated answer is exact, auditable, and instantaneous. Third, when the task is transformation rather than question answering â summarizing the text the user just pasted, rewriting it, translating it â retrieval contributes nothing.
A useful test before adopting RAG: write down the top twenty queries you expect. If most are answered by one obvious document, vector search may be unnecessary ceremony. If they require stitching facts from several documents or reasoning over policy exceptions across sections, RAG earns its complexity.
Scores that predict production quality
Evaluating RAG means scoring two things separately, because they fail independently. Retrieval quality asks whether the needed evidence reached the prompt; generation quality asks whether the model used it faithfully. One blended number for the whole system hides which half is broken, and the remedies are completely different â a new chunking strategy cannot fix a model that ignores correct context, and a more careful prompt cannot conjure evidence that was never retrieved.
Offline, the metrics below give a workable dashboard. Online, track citation coverage â the fraction of answers whose citations actually support the adjacent claim â and the refusal rate, since a system that never says "not in context" is almost certainly guessing sometimes.
| Metric | Question it answers | How it is computed |
|---|---|---|
| Context recall | Did the index surface all needed evidence? | Fraction of gold supporting passages retrieved |
| Context precision | Are the retrieved chunks relevant? | Relevant chunks over retrieved chunks |
| Faithfulness | Is the answer grounded in context? | Supported claims over total claims |
| Answer relevancy | Did it answer the asked question? | Graded by a judge model or human rubric |
| Refusal accuracy | Does it abstain when evidence is missing? | Correct refusals over no-evidence cases |
Start with context recall on a labeled set of fifty queries before touching anything else. Below roughly 80 percent recall, prompt engineering cannot save you; the evidence simply is not in the context. Above 95 percent, further retrieval tuning rarely moves answer quality, and remaining errors live in generation â citation mistakes, ignored refusals, or claims that paraphrase the context into something slightly stronger than the source supports.
Common Mistakes
Choosing chunk size by convenience instead of testing it against real queries
Fix: Label fifty queries with the passages that answer them, then sweep chunk sizes and measure context recall before freezing a value.
Averaging BM25 and cosine scores directly during fusion
Fix: The scales are unrelated; use reciprocal rank fusion or a trained ranker that sees both features.
Letting the model answer from parametric memory when context is irrelevant
Fix: Add an explicit refusal string to the prompt and monitor how often it is emitted.
Evaluating only end answer quality
Fix: Score context recall and faithfulness separately so you know whether to fix the retriever or the generator.
Best Practices
- Chunk on structural boundaries first and fall back to recursive character splitting only inside sections
- Attach source path, heading, and chunk index to every chunk so citations and debugging stay possible
- Log retrieved chunk ids and scores with each response to separate retrieval failures from generation failures
- Measure ANN recall against exact search on real queries whenever you change index type or parameters
- Keep a labeled evaluation set of at least fifty queries and re-run it after every pipeline change
Interview Questions
Q1: Why does RAG reduce hallucination without eliminating it?
Retrieved context constrains the model to relevant facts, but the model can still ignore the context, over-generalize a passage, or receive evidence that is itself incomplete, so faithfulness must be measured rather than assumed.
Q2: When would you skip vector search entirely?
When the corpus fits in the context window, when answers come from live structured data, or when the task is transformation of user-supplied text rather than knowledge lookup.
Q3: How does reciprocal rank fusion avoid score calibration problems?
It uses only the rank position each retriever assigns to a document, contributing one over rank plus a smoothing constant, so incomparable BM25 and cosine magnitudes never enter the calculation.
Key Takeaways
- RAG keeps knowledge in an updatable index while the model contributes language ability, which enables citations and fast corpus refreshes
- Chunk size is a semantic decision: too large dilutes the embedding, too small orphans the qualifiers that decide correctness
- Hybrid lexical and dense retrieval plus a cross-encoder reranker is the cheapest reliable quality gain in the pipeline
- Prompt rules and citation markers are what turn retrieved context into auditable, checkable answers
- Score retrieval and generation separately; context recall is the gate that decides whether prompt work can help at all