Search first, then answer
A language model answers from its weights, which means it cannot know last week's release notes, your internal policy document, or the pricing page you shipped yesterday. Retrieval-augmented generation fixes that by splitting the task in two. At setup time, your documents are split into chunks, converted into vectors, and stored in an index. At ask time, the question is converted into the same kind of vector, the index returns the closest chunks, and those chunks are pasted into the prompt alongside the question. The model then answers using only that evidence.
The split matters because it changes what you are optimizing. Model quality is out of your hands past a certain point, but retrieval quality is entirely yours. A system that retrieves the wrong paragraph will produce a fluent, confident and incorrect answer, and no amount of prompt wording will save it. That is why the practical craft of RAG lives in chunking and retrieval, not in the final template.
Chunking is the decision that shapes everything
Chunks are the unit of retrieval, so a question can only ever be answered with the text that happens to sit inside one chunk. Split too small and a sentence loses the paragraph that gives it meaning. Split too large and the embedding averages over several topics, so the chunk ranks poorly for every one of them, and even when it is retrieved the prompt spends context on irrelevant neighbors.
| Chunk size | Retrieval precision | Context cost | Typical use |
|---|---|---|---|
| 200 to 400 characters | High, sometimes fragmentary | Low | FAQ pairs, headers |
| 500 to 800 characters | Balanced default | Moderate | Prose, manuals |
| 1200 to 2000 characters | Lower, multi-topic | High | Legal or technical clauses |
| Whole document | Poor unless tiny corpus | Very high | Short notes only |
Overlap is the other half of the setting. A fifty to one hundred character overlap means a sentence that straddles a boundary appears in one of the two chunks intact, which removes an entire category of near-miss retrievals. Overlap is cheaper than shrinking the chunk, and it fixes boundary problems without making every chunk less focused.
Before tuning numbers, inspect your documents. A corpus of short FAQ entries wants small chunks split on question boundaries. A manual with long explanatory sections wants medium chunks split on headings when possible. Splitting on structure before falling back to a character count is the single highest-leverage change you can make, and it takes only a few lines. If your files already carry useful metadata such as a title, product area or last-updated date, attach it to every chunk at split time, because later you will want to filter retrievals by source and re-indexing to add metadata later is pure wasted work.
Loading and splitting documents
Start with plain text and one directory. Loaders for PDF and HTML exist, but they introduce their own extraction errors, and debugging retrieval is much easier when the text you index is text you can read.
from pathlib import Path
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import (
RecursiveCharacterTextSplitter,
MarkdownHeaderTextSplitter,
)
def load_corpus(root: str):
docs = []
for path in sorted(Path(root).rglob("*.md")):
docs.append(TextLoader(str(path), encoding="utf-8").load()[0])
return docs
header_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=[("#", "h1"), ("##", "h2")],
strip_headers=False,
)
recursive_splitter = RecursiveCharacterTextSplitter(
chunk_size=700,
chunk_overlap=100,
separators=["\n\n", "\n", ". ", " ", ""],
)
def build_chunks(root: str):
chunks = []
for doc in load_corpus(root):
for section in header_splitter.split_text(doc.page_content):
for piece in recursive_splitter.split_text(section):
chunks.append(piece)
return chunks
chunks = build_chunks("docs")
print(f"{len(chunks)} chunks, average {sum(map(len, chunks)) // len(chunks)} chars")
The recursive splitter matters more than it looks. It tries the largest separator first and only falls back to smaller ones when a block is still too big, so paragraphs stay intact and sentences are only broken when they must be. Naively slicing every n characters produces chunks that begin mid-sentence, which embeddings handle poorly.
Embeddings and the index
An embedding model maps text to a fixed-length vector so that similar meanings land nearby. You do not need to train one; hosted APIs and small open-weight models both work well for English corpora. The vector store keeps those vectors and answers nearest-neighbor queries, in memory for small projects and in a dedicated service once the corpus or query rate grows.
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Chroma.from_texts(
texts=chunks,
embedding=embeddings,
persist_directory="./chroma_store",
metadatas=[{"source": i} for i in range(len(chunks))],
)
retriever = vectorstore.as_retriever(
search_kwargs={"k": 4},
)
hits = retriever.invoke("How do I rotate API keys?")
for i, doc in enumerate(hits):
print(f"--- hit {i} ---")
print(doc.page_content[:200])
Two settings cause most early disappointment. The value of k, how many chunks come back, defaults too low for multi-part questions; four to six is a reasonable starting point for prose. And embedding models differ meaningfully in cost and quality across providers, so if retrieval looks weak, evaluate two models on ten of your own questions before you start rewriting the chunker.
The chain, and what the model is allowed to say
With retrieval working, assembly is straightforward: fetch context, build a prompt that binds the question to it, run the model, and parse the answer. The prompt should state that the answer must come from the context and that missing information must be admitted, not guessed.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
template = """Answer the question using only the context below.
If the context does not contain the answer, reply exactly:
'I could not find that in the provided documents.'
Context:
{context}
Question: {question}
Answer:"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI(model="gpt-4o-mini", temperature=0)
def rag(question: str, k: int = 4) -> str:
docs = retriever.invoke(question)
context = "\n\n---\n\n".join(d.page_content for d in docs)
chain = prompt | model | StrOutputParser()
return chain.invoke({"context": context, "question": question})
print(rag("What is the key rotation policy?"))
The refusal clause is doing real work. Without it, a model presented with unrelated context will still produce a fluent answer, which is the most common way a RAG system erodes trust in its first week of use. With it, the system degrades visibly instead of silently.
Answer quality comes from retrieval, not prose
Evaluate retrieval separately from generation, or you will never know which half is broken. Take twenty real questions, mark which chunk should have been retrieved for each, and measure recall at k. If the right chunk is not in the top four, generation cannot save the answer, and your fix belongs upstream in chunking, embeddings or metadata filtering.
âšī¸Citations are a debugging tool
Ask the model to quote the sentence it used, or return the source identifier alongside the answer. A wrong citation points you at a retrieval failure in seconds; an uncited wrong answer sends you reading the prompt instead.
For generation, keep a small labeled set of question-and-answer pairs and score answers with a rubric rather than vibes: correct, partially correct, refused appropriately, or hallucinated. Track the refused-appropriately rate carefully. A system that refuses too often feels useless; one that refuses too rarely invents. Tuning that balance is a product decision, and it is easier to make when the numbers exist.
Cost and latency deserve measurement too. Every query pays embedding, search and generation. Caching identical questions, batching offline indexing, and trimming retrieved chunks before prompting are the three levers that move the bill most.
Common Mistakes
Splitting documents at fixed character boundaries without overlap
Fix: Use a recursive splitter on paragraph and sentence separators, with fifty to one hundred characters of overlap
Debugging the prompt when the correct chunk never made it into the context
Fix: Measure retrieval recall on a small labeled question set before touching generation
Letting the model answer freely even when the retrieved context is irrelevant
Fix: Add an explicit refusal clause so the system admits when the documents do not cover the question
Indexing PDFs directly and assuming the extractor preserved structure
Fix: Inspect extracted text first, and prefer source formats that survive extraction faithfully
Best Practices
- Split on document structure such as headings before falling back to character counts
- Keep k between four and six for prose, and log the retrieved chunks with every answer
- Return source identifiers or quotes so wrong answers are traceable to a retrieval failure
- Evaluate retrieval recall separately from answer quality on a labeled set of your own questions
- Cache question embeddings and identical queries, since users repeat questions far more often than expected
Interview Questions
Q1: Why does chunk size dominate RAG quality more than the prompt template?
Retrieval can only return what was indexed. If the relevant sentence was split away from its context, or averaged into a multi-topic chunk that ranks nowhere, the model never sees the evidence no matter how well the prompt is written.
Q2: What role does chunk overlap play?
It ensures that text spanning a boundary appears intact in at least one chunk, which prevents near-miss retrievals caused purely by where the splitter happened to cut.
Q3: How do you tell whether a bad answer came from retrieval or from generation?
Check whether the correct chunk was in the retrieved set. If it was, the problem is prompting or model behavior. If it was not, fix chunking, embeddings or the retriever before anything else.
Q4: When would you avoid RAG entirely?
When the corpus is tiny enough to fit in the context window, where full-document prompting removes the whole retrieval failure surface, or when the task needs structured data that a SQL tool serves more reliably than prose retrieval.
Key Takeaways
- RAG separates retrieval from generation, so most quality problems live upstream
- Chunk size trades precision against context cost, and structure-aware splitting beats fixed slicing
- Overlap of fifty to one hundred characters removes boundary-caused misses cheaply
- Embeddings and the vector store determine what can be found at all
- An explicit refusal clause turns silent hallucination into visible failure
- Measure retrieval recall on labeled questions before tuning prompts
- Return citations so every wrong answer names its own root cause