Learn / NLP & Practical LLMs / Module 03
NLP & Practical LLMs · Module 03
RAG Foundations: Chunking, Retrieval, and Verifiable Citations
Learn the five moving parts of a Retrieval-Augmented Generation pipeline and how to check whether answers actually match their cited sources.
<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->
What RAG actually does
Large language models freeze their training knowledge at a cutoff date and do not know your internal documents. RAG (Retrieval-Augmented Generation) keeps the model fixed and supplies fresh, relevant excerpts at query time.
Every basic RAG system follows five simple steps:
- Ingest & clean: extract plain text and metadata (title, page, section, date) from PDFs, HTML, or Markdown.
- Chunk: split long documents into bite-sized passages (commonly 300–600 words) with slight overlap so sentences at boundaries do not get severed.
- Index: build a keyword index (BM25/FTS5), a vector embedding index, or ideally both.
- Retrieve: given a user question, fetch the top
kcandidate chunks (often 3–8 chunks) and optionally rerank them. - Generate with citations: instruct the model to answer only from the retrieved chunks and cite the chunk ID for every claim.
Where beginner RAG pipelines fail
Most "bad LLM answers" in a RAG app are actually retrieval bugs, not model bugs.
| Failure mode | What it looks like | Simple fix |
|---|---|---|
| Chunks too big | Relevant sentence is buried inside 2,000 noisy words. | Split by section headings into ~350-word chunks. |
| Chunks too small | A table header or definition gets separated from its values. | Keep heading context attached to every chunk. |
| Vector-only misses exact terms | Searching M-25-21 returns vague policy paragraphs. | Combine BM25/FTS5 keyword search + dense embeddings. |
| Unverified citations | Model cites [doc-2] for a number that is not in [doc-2]. | Run a deterministic quote/claim check against the cited text. |
A minimal citation check in Python
You do not need an expensive framework to catch fabricated quotes. Normalize whitespace and check whether cited spans genuinely appear in the retrieved passage:
import re
def normalize(text: str) -> str:
return re.sub(r"\s+", " ", text.lower()).strip()
def quote_supported(quote: str, source_chunk: str, min_overlap: float = 0.8) -> bool:
q_words = normalize(quote).split()
if not q_words:
return False
if normalize(quote) in normalize(source_chunk):
return True
# Fallback: 3-gram word overlap for minor punctuation differences
if len(q_words) < 3:
return False
q_grams = {tuple(q_words[i:i+3]) for i in range(len(q_words) - 2)}
s_words = normalize(source_chunk).split()
s_grams = {tuple(s_words[i:i+3]) for i in range(len(s_words) - 2)}
return (len(q_grams & s_grams) / len(q_grams)) >= min_overlap<!-- Thompson Axiomata LLC — Brent Alexander Thompson -->
Finished this module?
Mark it complete to update your browser-local progress bar for NLP & Practical LLMs.