Retrieval-Augmented Generation (RAG)
Give an LLM access to your own, up-to-date documents: embeddings, chunking, vector databases, hybrid search, reranking, prompt assembly with citations, and how to evaluate and debug a RAG system.
An LLM’s knowledge is frozen at its training cutoff, it has never seen your company’s private documents, and when it does not know something it may hallucinate a fluent answer anyway. Retrieval-Augmented Generation fixes this by searching a knowledge base at question time and pasting the most relevant passages into the prompt[1]. Updating knowledge becomes as easy as re-indexing a document, answers can cite their sources, and access control stays in your search layer.
The RAG pipeline
- Ingest (offline): load documents (PDF, HTML, wiki, tickets), clean them, keep metadata (title, section, date, permissions).
- Chunk: split each document into passages of a few hundred tokens.
- Embed and index: turn each chunk into a vector with an embedding model and store it in a vector database.
- Retrieve (online): embed the user question with the *same* model and fetch the top-k most similar chunks (optionally plus keyword search).
- Rerank: re-score the candidates with a more accurate model and keep the best few.
- Generate: build a prompt with the chunks, numbered for citation, plus instructions to answer only from the context.
Embeddings and similarity
An embedding model maps a text to a dense vector (e.g. 384–1,536 numbers) so that texts with similar meaning land close together — “refund policy” and “bagaimana cara minta uang kembali” can match without sharing a single word. Retrieval uses bi-encoders: the query and the documents are embedded independently, so all document vectors can be precomputed. Dense Passage Retrieval showed such learned retrievers beat keyword search for open-domain QA[2], and Sentence-BERT made good sentence embeddings practical[3]. Similarity is usually Cosine similarity:
- cos(q, d)
- Cosine similarity between query q and document chunk d
- q · d
- Dot product of the two embedding vectors
- ‖q‖
- length of the query vector
- ‖d‖
- length of the chunk vector
- ∈ [−1, 1]
- the value always lies between −1 and 1 (1 = same direction)
▸Worked example
Chunking
Chunking decides what a “search result” is. Too small and a chunk lacks context (“It is processed within 7 days” — what is “it”?). Too large and one vector must summarize many topics, so similarity gets blurry and you waste context-window space. Overlap repeats a few sentences between neighbouring chunks so facts that straddle a boundary are not cut in half.
- Fixed-size (by tokens or words) with overlap — simple baseline.
- Structure-aware / recursive — split by headings, then paragraphs, then sentences; keeps sections intact. Usually the best default for docs and wikis.
- Contextual headers — prepend the document title and section path to every chunk (“Refund policy › Damaged items › …”) so each chunk is self-explanatory.
- Special content — tables, code and FAQs often deserve their own chunks rather than being split mid-row.
Try this
- Ask a question whose answer sits in one document. Then make the chunk size very small: the right chunk may lose the words that match the query and drop in rank.
- Make the chunk size very large: scores of many chunks get closer together because each chunk mixes several topics — and the assembled prompt becomes long.
- Set overlap to 0 and pick a question about a fact near a chunk boundary; then add overlap and see the full fact reappear in one chunk.
- Rephrase the query with synonyms that do not appear in the text. TF-IDF fails because it matches words, not meaning — exactly the gap neural embeddings close.
- Change top-k and read the assembled prompt: more chunks = more recall but more noise and tokens.
Vector databases and approximate search
For up to roughly a few hundred thousand chunks, exact brute-force search (one matrix multiplication) is fast enough. Beyond that, vector databases use approximate nearest neighbour (ANN) indexes that trade a little recall for huge speed-ups; the most popular is HNSW, a multi-layer navigable small-world graph[5]. Options range from libraries (FAISS) to extensions of existing databases (pgvector for PostgreSQL) to dedicated services (Qdrant, Weaviate, Milvus, Chroma, and managed cloud offerings). Pick one that supports metadata filtering (by user permissions, language, date) — you will need it.
Hybrid search and reranking
Dense embeddings capture meaning but can miss exact strings: product codes, error messages, names. Classic keyword search (BM25) catches those. Hybrid search runs both and merges the ranked lists, often with reciprocal rank fusion. Then a reranker — a cross-encoder that reads the query and a chunk *together* — rescores the top 20–50 candidates much more accurately than vector similarity can; it is too slow to run over the whole corpus, which is why it comes second[6].
- RRF(d)
- fused score of document d
- Σ_{r ∈ rankers}
- sum over all retrievers r (e.g. BM25 and dense vectors)
- rank_r(d)
- position of d in retriever r's list (1 = top); documents a retriever did not return add nothing
- k
- smoothing constant, usually 60
▸Worked example
- What it is
- Length of each indexed passage (in tokens, words or characters).
- ↑ If you increase it
- More context per chunk, fewer cut facts; but blurrier embeddings (several topics per vector), fewer chunks fit in the prompt, more irrelevant text per hit.
- ↓ If you decrease it
- Sharper matching and precise citations; but chunks lose context (pronouns, headings) and answers needing several sentences get fragmented.
- Typical values
- 200–800 tokens; ~300–500 is a common starting point. Tune on your own eval set.
- What it is
- How much text neighbouring chunks share.
- ↑ If you increase it
- Facts spanning boundaries survive intact; but the index grows and near-duplicate chunks can crowd the top-k.
- ↓ If you decrease it
- Smaller index, no duplicates; risk of splitting a sentence or a table row across two chunks.
- Typical values
- 10–20% of chunk size.
- What it is
- How many chunks are retrieved (and, after reranking, passed to the LLM).
- ↑ If you increase it
- Higher recall — the answer is more likely somewhere in the context; but more tokens, cost, latency, and distracting noise that can lower answer quality.
- ↓ If you decrease it
- Focused, cheap prompts; but if the right chunk is ranked 6th and k = 5, the model never sees it.
- Typical values
- Retrieve 20–50 candidates → rerank → pass 3–8 to the LLM.
- What it is
- Minimum similarity (or reranker score) for a chunk to be used at all.
- ↑ If you increase it
- Fewer irrelevant chunks; more “I don’t know” answers when nothing matches well — often what you want.
- ↓ If you decrease it
- Always returns something, even unrelated text, which invites confident but ungrounded answers.
- Typical values
- Model-specific — calibrate on examples; cosine scores are not comparable across embedding models.
import numpy as np
from sentence_transformers import SentenceTransformer, CrossEncoder
docs = {"refund.md": "Pengembalian dana diproses dalam 7 hari kerja setelah barang diterima ...",
"shipping.md": "Pengiriman ke luar Pulau Jawa memakan waktu 3-5 hari kerja ..."}
def chunk_words(text, size=120, overlap=30):
words, step = text.split(), size - overlap
return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]
chunks, source = [], []
for name, text in docs.items():
for c in chunk_words(text):
chunks.append(c); source.append(name)
# multilingual embedder, so Indonesian and English queries both work
embedder = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
index = embedder.encode(chunks, normalize_embeddings=True) # [n_chunks, 384]
query = "Berapa lama refund diproses?"
q = embedder.encode([query], normalize_embeddings=True)[0]
cand = np.argsort(-(index @ q))[:20] # cosine top-k
reranker = CrossEncoder("BAAI/bge-reranker-v2-m3") # multilingual cross-encoder
scores = reranker.predict([(query, chunks[i]) for i in cand])
best = [cand[j] for j in np.argsort(-scores)[:4]]
context = "\n\n".join(f"[{n + 1}] ({source[i]}) {chunks[i]}" for n, i in enumerate(best))
prompt = ("Answer using ONLY the context. Cite sources like [1]. If the context does not "
"contain the answer, say you don't know.\n\n"
f"Context:\n{context}\n\nQuestion: {query}")| Symptom | Likely cause | Fixes |
|---|---|---|
| Right passage never retrieved | Recall problem: chunking, embedding model, vocabulary mismatch | Hybrid search, contextual headers, better/multilingual embedder, larger candidate k |
| Retrieved but ignored or misread | Too much noise; key chunk buried in the middle of a long context[4] | Rerank, pass fewer chunks, put the best chunks first |
| Answer adds facts not in the context | Model falls back on parametric memory | Instruct “only from context”, require citations, allow “I don’t know”, check faithfulness |
| Outdated answers | Stale index, duplicate old versions | Incremental re-indexing, dates in metadata, delete superseded docs |
Evaluating a RAG system
- Build a golden set: 50–200 real questions with the expected answer and the source passage(s) that contain it.
- Retrieval metrics: recall@k (is a correct passage in the top-k?) and MRR (how high is the first correct passage?). Evaluate retrieval separately from generation.
- Generation metrics: faithfulness/groundedness (is every claim supported by the context?), answer relevance, and citation correctness — often scored by an LLM judge that you spot-check by hand.
- Operational metrics: latency, tokens per answer, cost, and the share of “I don’t know” responses.
▸Go deeper: the original RAG model
Lewis et al. coined “retrieval-augmented generation” for a model that combined a DPR retriever over Wikipedia with a BART generator and trained them jointly, treating the retrieved document as a latent variable; RAG-Sequence uses one document for the whole answer, RAG-Token can switch documents per token[1]. Most production “RAG” today is simpler — an off-the-shelf retriever plus a prompted LLM, no joint training — but the core insight holds: separating knowledge (an index you can update) from reasoning (the model) makes systems more accurate, more current and more auditable.
Quiz
References
- [1]Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksPaperLewis et al.2020arxiv.org
- [2]Dense Passage Retrieval for Open-Domain Question AnsweringPaperKarpukhin et al.2020arxiv.org
- [3]Sentence-BERT: Sentence Embeddings using Siamese BERT-NetworksPaperReimers & Gurevych2019arxiv.org
- [4]Lost in the Middle: How Language Models Use Long ContextsPaperLiu et al.2023arxiv.org
- [5]Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphsPaperMalkov & Yashunin2016arxiv.org
- [6]Sentence Transformers documentation (embeddings, cross-encoders, retrieve & re-rank)DocsUKP Lab / Hugging Facesbert.net