AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
✎Large Language Models
  1. Tokenization: how text becomes numbers
  2. How LLMs work: next-token prediction at scale
  3. Decoding: greedy, beam search, temperature, top-k, top-p
  4. Scaling laws: parameters, data and compute
  5. Fine-tuning & alignment: SFT, RLHF, DPO, LoRA/QLoRA
  6. Prompting: zero-shot, few-shot, chain-of-thought, structured output
  7. Retrieval-Augmented Generation (RAG)
  8. Agents & tool use: ReAct, function calling, MCP
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Large Language Models

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.

Intermediate~24 min·6 references
Key terms
RAG (Retrieval-Augmented Generation)EmbeddingChunkingVector databaseCosine similarityHallucination

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.

≈
Analogy: an open-book exam
Without RAG, the model takes a closed-book exam and must rely on memory. With RAG, it gets the textbook — but only helpful if there is a good index to find the right page quickly (the retriever) and the student still reads carefully and writes the answer (the generator). A bad index means the student confidently quotes the wrong page.

The RAG pipeline

  1. Ingest (offline): load documents (PDF, HTML, wiki, tickets), clean them, keep metadata (title, section, date, permissions).
  2. Chunk: split each document into passages of a few hundred tokens.
  3. Embed and index: turn each chunk into a vector with an embedding model and store it in a vector database.
  4. Retrieve (online): embed the user question with the *same* model and fetch the top-k most similar chunks (optionally plus keyword search).
  5. Rerank: re-score the candidates with a more accurate model and keep the best few.
  6. Generate: build a prompt with the chunks, numbered for citation, plus instructions to answer only from the context.
Loading interactive…
The six steps above as one system. Walk through the offline lane first (it runs once), then the online lane (it runs for every question). Tap the dashed “same model” arrow and notice that the LLM itself is never retrained — all new knowledge arrives through the retrieved chunks.

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) = (q · d) / (‖q‖ · ‖d‖) ∈ [−1, 1] (if ‖q‖ = ‖d‖ = 1: cos = q · d)
Normalize vectors once and cosine similarity becomes a fast dot product.
In words: The similarity between a query and a chunk is the cosine of the angle between their embedding vectors — the dot product divided by both lengths. If all vectors are normalized to length 1 when indexed, the division disappears and a plain dot product (one fast matrix multiply for all chunks) is enough.
Symbols(hover a symbol in the formula)
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
Normalized 2-D toy vectors: q = [0.6, 0.8], d₁ = [0.8, 0.6], d₂ = [0.6, −0.8] ‖q‖ = √(0.36 + 0.64) = 1, same for d₁, d₂ cos(q, d₁) = 0.6·0.8 + 0.8·0.6 = 0.96 → very similar cos(q, d₂) = 0.36 − 0.64 = −0.28 → dissimilar

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.
Loading interactive…
Real TF-IDF + cosine retrieval over a small knowledge base. Production systems use neural embeddings and a vector database, but the mechanics are the same.

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) = Σ_{r ∈ rankers} 1 / (k + rank_r(d)), k ≈ 60
Reciprocal rank fusion: documents ranked high by any retriever float to the top.
In words: Each retriever contributes 1/(k + rank) for every document it returns, and the contributions are added up. Only ranks are used, not raw scores, so BM25 and vector scores never need to be on the same scale; the constant k stops the very top rank from dominating.
Symbols(hover a symbol in the formula)
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
Doc A: rank 1 in BM25, rank 3 in vector search → 1/61 + 1/63 = 0.016393 + 0.015873 = 0.032266 Doc B: rank 2 in both → 1/62 + 1/62 = 0.032258 Doc C: rank 1 in BM25 only → 1/61 = 0.016393 Order: A > B > C — agreement between retrievers beats a single first place.
knobchunk_size
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.
knobchunk_overlap
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.
knobtop_k (retrieved chunks)
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.
knobsimilarity threshold
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.
python
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}")
A minimal RAG retriever: chunk → embed → search → rerank → prompt (sentence-transformers).
SymptomLikely causeFixes
Right passage never retrievedRecall problem: chunking, embedding model, vocabulary mismatchHybrid search, contextual headers, better/multilingual embedder, larger candidate k
Retrieved but ignored or misreadToo 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 contextModel falls back on parametric memoryInstruct “only from context”, require citations, allow “I don’t know”, check faithfulness
Outdated answersStale index, duplicate old versionsIncremental re-indexing, dates in metadata, delete superseded docs
Debugging RAG: find which stage fails before changing anything.

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.
!
Pitfalls
(1) Indexing with one embedding model and querying with another — vectors from different models are incomparable. (2) Ignoring access control: if the retriever can see HR documents, so can every user unless you filter by permissions. (3) Retrieved documents can contain prompt injections; treat them as untrusted data. (4) Bad PDF parsing (broken tables, headers in every chunk) silently caps quality — inspect your chunks. (5) Assuming a long context window makes retrieval unnecessary: stuffing everything in is slower, costlier and models use mid-context information less reliably[4].
▸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

1.
What problem does RAG primarily solve?
2.
You increase chunk size from 300 to 3,000 tokens. What is the most likely effect?
3.
Why is a cross-encoder reranker used only on the top candidates instead of the whole corpus?
4.
Users search for an error code like “ERR-4031” and dense retrieval keeps missing it. What helps most?
5.
Two vectors are normalized to length 1 and their dot product is 0.92. What is their cosine similarity?
Score: 0/5

References

  1. [1]
    Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
    PaperLewis et al.2020arxiv.org
  2. [2]
    Dense Passage Retrieval for Open-Domain Question Answering
    PaperKarpukhin et al.2020arxiv.org
  3. [3]
    Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks
    PaperReimers & Gurevych2019arxiv.org
  4. [4]
    Lost in the Middle: How Language Models Use Long Contexts
    PaperLiu et al.2023arxiv.org
  5. [5]
    Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs
    PaperMalkov & Yashunin2016arxiv.org
  6. [6]
    Sentence Transformers documentation (embeddings, cross-encoders, retrieve & re-rank)
    DocsUKP Lab / Hugging Facesbert.net
← Previous
Prompting: zero-shot, few-shot, chain-of-thought, structured output
Next →
Agents & tool use: ReAct, function calling, MCP