RAG: Grounding LLM Answers in Real Documents
A language model that answers from memory will eventually answer from imagination, and for anything proprietary or current that is disqualifying. Retrieval-augmented generation fixes the ordering: find the relevant passages first, hand them to the model as evidence, and require the answer to come from that evidence. The result is a system whose knowledge can be updated by editing a corpus instead of retraining, and whose answers can be traced back to a source. This lesson walks the pipeline end to end and shows where quality is actually won or lost.
The Pipeline, Piece by Piece
RAG has two halves that run on different schedules. Offline, ingestion loads documents, splits them into chunks, embeds each chunk, and writes vectors plus metadata into a store. Online, a query is embedded the same way, the store returns nearest neighbors, optional reranking reshuffles them, and a prompt assembles the surviving passages around the question for the model to answer.
Most teams underestimate the offline half. Chunk boundaries decide what can be retrieved at all: a policy sentence separated from its section heading is meaningless on its own, and a chunk spanning two topics matches neither well. Metadata â document title, section path, update date, access controls â travels with every vector and later enables filtering, citation, and permission enforcement. A retrieval system without provenance is a system that cannot explain itself, and users stop trusting it after the first confidently wrong answer.
Chunking Is a Recall Decision
Fixed-size splitting with overlap is the default because it is simple, but it ignores structure. Better options split on headings, sentences, or semantic boundaries, and size the chunks to the query you expect: short chunks match precisely, long chunks carry more context but dilute the embedding. Overlap exists so that a fact straddling a boundary is still findable from one side, and 10 to 20 percent is usually enough.
from langchain.text_splitter import (
RecursiveCharacterTextSplitter,
MarkdownHeaderTextSplitter,
)
md_headers = [("#", "h1"), ("##", "h2"), ("###", "h3")]
markdown_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=md_headers, strip_headers=False)
text = """# Refunds
## Standard policy
Customers may request a refund within 30 days of delivery.
Items must be unused and in original packaging.
## Exceptions
Opened electronics are eligible for store credit only.
"""
sections = markdown_splitter.split_text(text)
print([s.metadata for s in sections])
recursive = RecursiveCharacterTextSplitter(
chunk_size=450,
chunk_overlap=80,
separators=["\n\n", "\n", ". ", " ", ""],
keep_separator=True,
)
chunks = recursive.split_text("\n\n".join(s.page_content for s in sections))
print(len(chunks), "chunks; longest:", max(len(c) for c in chunks))
for chunk in chunks:
assert len(chunk) <= 450 + 80
print("overlap preserves boundary sentences")
Run your splitter over the real corpus and read twenty outputs before shipping. Silent truncation, chunks that are pure whitespace, and headings detached from their body are all common and all invisible in a unit test built from toy text.
Retrieval, Reranking, Synthesis
Vector search alone optimizes for semantic similarity, which is not the same as usefulness. Production stacks add three refinements. Hybrid search unions dense vectors with sparse keyword scores, catching queries where exact identifiers matter â error codes, part numbers, product SKUs. Metadata filters exclude stale or unauthorized documents before any similarity is computed. A cross-encoder reranker then scores the top twenty candidates jointly with the query, trading a little latency for a large precision gain, because rerankers can read query and passage together instead of comparing fixed vectors.
| Stage | Candidate count | Latency | What it improves |
|---|---|---|---|
| Sparse keyword search | Thousands | Low | Exact terms, IDs, acronyms |
| Dense vector search | Thousands | Low | Paraphrase and intent match |
| Hybrid union and dedupe | Hundreds | Low | Recall across both regimes |
| Metadata filter | Hundreds | Low | Freshness, permissions, locale |
| Cross-encoder reranker | Top 20 to 50 to top 3 to 8 | Medium | Precision of the final set |
| Synthesis with citations | 3 to 8 passages | High | Faithful, attributable answer |
Tune in that order. Improving the generator before the retriever just teaches the model to write more persuasive answers to the wrong evidence.
Prompting With Evidence, Not Vibes
The synthesis prompt must make the contract explicit: answer only from the passages, cite them, and say when they do not cover the question. Number the passages so citations have stable handles, keep each passage clearly delimited so the model can attribute claims, and put the question last. Ask for abstention explicitly â models rarely volunteer it â and prefer a short, sourced answer over a comprehensive-sounding one.
def build_context(hits, max_chars=4000):
parts, used = [], 0
for rank, hit in enumerate(hits, start=1):
passage = f"[{rank}] {hit['title']} ({hit['source']}):\n{hit['text']}"
if used + len(passage) > max_chars:
break
parts.append(passage)
used += len(passage)
return "\n\n".join(parts)
def generate_answer(question, hits):
prompt = f"""Answer the question using only the passages below.
Passages:
{build_context(hits)}
Rules:
- Cite passages as [n] after each claim.
- If the passages do not contain the answer, reply exactly: NOT COVERED.
Question: {question}
Answer:"""
return call_model(prompt, temperature=0.0, max_tokens=400)
hits = [
{"title": "Refunds", "source": "policy.md", "text": "Refund requests are accepted within 30 days of delivery."},
{"title": "Shipping", "source": "policy.md", "text": "Standard shipping takes 3 to 5 business days."},
]
print(generate_answer("How long do I have to return an order?", hits))
The literal NOT COVERED sentinel is deliberate: it is trivial to detect, easy to alert on, and far better than a paragraph of hedging that your downstream logic cannot parse.
Measuring Whether Grounding Works
Evaluate the two halves separately, because a single end-to-end score hides which one broke. For retrieval, compute recall at k â the fraction of questions whose gold passage appears in the top k â plus mean reciprocal rank for ordering quality. For generation, measure faithfulness: the share of claims in the answer that are supported by the retrieved passages. Answer relevance and context precision round out the picture, and all four can be estimated automatically with a judge model before you spend on human review.
Track the slice that matters rather than the average: queries with no answer in the corpus, queries needing two documents joined, and queries whose vocabulary is rare. Those cases drive user distrust. Log the retrieved passage identifiers with every response so you can replay a complaint exactly, and sample failing transcripts weekly into the eval set. Retrieval quality decays as the corpus changes even when no code ships â a recall drop is usually a content problem, not a model problem.
A practical cadence works well here: run the automated suite nightly on the labeled set, review a handful of live transcripts by hand each week, and promote only changes that move both retrieval and faithfulness in the right direction. Keep each evaluation run tied to a prompt version and an index snapshot, because a score without provenance cannot be compared to anything later.
Where RAG Still Struggles
Multi-hop questions that need two documents chained together are poorly served by single-shot retrieval, and the usual fix is query decomposition or an iterative loop that retrieves again based on what it found. Questions whose answer depends on aggregation â totals, counts, ranges across a table â should be answered by a query tool, not by reading passages. Tables themselves embed badly, so structured sources are better queried than vectorized. And when users ask about the system rather than the corpus, retrieval adds noise; route those to a plain model call.
âšī¸Debugging order
Common Mistakes
Chunking by raw character count through structured documents
Fix: Split on headings and sentences so every chunk keeps its title and section path
Passing fifty passages to the model and hoping
Fix: Rerank and cap at three to eight, or relevant evidence gets diluted by noise
Never testing abstention
Fix: Seed the eval set with unanswerable questions and require a machine-readable refusal
Tuning the generator while retrieval recall is low
Fix: Measure recall at k first; synthesis cannot recover evidence it never saw
Storing vectors without source metadata
Fix: Keep title, path, date, and permissions on every chunk for citation and access control
Key Takeaways
- RAG separates knowledge (in the corpus) from behavior (in the weights)
- Chunk boundaries and metadata determine recall before any model runs
- Hybrid search plus a cross-encoder reranker beats pure vector search on most corpora
- Prompts must require citations and an explicit not-covered sentinel
- Evaluate retrieval and generation separately, and watch the slices users actually ask about