Improving RAG
Learn how to systematically improve a RAG system by finding the layer that causes errors and then tuning retrieval, context, generation, and system performance.
By the end of this lesson, you will be able to:
- Diagnose whether a RAG problem comes from data, chunking, retrieval, ranking, context, prompting, or generation.
- Improve retrieval with better chunking, embeddings, metadata filters, hybrid search, and reranking.
- Control context quality instead of simply increasing Top-K.
- Improve answer grounding with clear prompts and source-aware generation.
- Use evaluation data to compare changes instead of relying on a few examples.
- Balance quality, latency, token usage, and cost.
- Build a repeatable RAG improvement loop.
Start With the Failure, Not the Tool
βImprove RAGβ does not mean adding more components. First identify what is failing. If the correct evidence never enters the candidate set, changing the generation prompt will not repair retrieval.
Improve the Source Data First
RAG quality is bounded by the information you index. Duplicate, stale, incomplete, or badly extracted documents create problems before retrieval even starts.
Remove accidental duplicates, preserve important headings, and keep document versions identifiable.
Old policies, broken extraction, navigation text, and duplicated pages can compete with the correct evidence.
Improve Chunking
Chunking determines the units that retrieval can return. A chunk that is too small may lose the surrounding meaning; a chunk that is too large may contain unrelated material.
Simple baseline
Useful when documents have little structure.
Natural boundaries
Keeps sentence-level meaning together.
Structure-aware
Uses a hierarchy of separators.
Meaning-aware
Creates boundaries when topic meaning changes.
Evaluate chunking with the same questions. If relevant evidence is split across chunks, adjust boundaries or overlap rather than blindly increasing K.
Tune Chunk Size and Overlap
Chunk size and overlap are retrieval parameters, not universal constants. Start with a reasonable baseline and test alternatives on your own documents.
The retrieved chunk may contain a sentence but miss the condition or exception immediately around it.
The chunk may contain the answer plus several unrelated sections, increasing context size and distraction.
Overlap can preserve information at boundaries, but excessive overlap increases storage, retrieval duplicates, and context noise.
Improve Embeddings
Embeddings control how semantic similarity is represented. A better embedding model can improve retrieval when the existing model does not represent your domain or language well.
Test whether terminology, abbreviations, and product language are represented well.
Use an embedding setup designed to compare the two sides correctly.
Compare Recall@K and downstream answer quality on a fixed dataset.
Larger vectors can affect storage, latency, and indexing cost.
Use Metadata Filtering
Similarity alone may return a semantically related chunk from the wrong region, product, language, customer, or document version. Metadata filters can constrain the search space.
documents = [
{"id": "a", "text": "Refunds are available for 30 days.", "region": "US"},
{"id": "b", "text": "Refunds are available for 14 days.", "region": "EU"},
{"id": "c", "text": "Refunds require the original receipt.", "region": "US"},
]
region = "US"
filtered = [doc for doc in documents if doc["region"] == region]
for doc in filtered:
print(doc["id"], doc["text"])This is a teaching example. A production vector database applies metadata filters during retrieval rather than scanning every document in Python.
Use Hybrid Search When Exact Terms Matter
Semantic retrieval is strong for meaning, while keyword retrieval can be strong for exact product names, IDs, error codes, policy numbers, and uncommon terms.
Can match passages that explain account recovery even if the wording differs.
Exact token matching can be valuable when the identifier itself carries meaning.
Hybrid search combines both signals. Evaluate whether the combination improves retrieval on the query types that matter for your application.
Retrieve Broadly, Then Rerank
A useful pattern is to retrieve a larger candidate set with a fast first-stage search and then use a stronger ranking method to put the best candidates first.
Reranking is especially useful when the initial retriever finds the right evidence but does not order it well. It also adds latency and compute cost, so measure the trade-off.
Do Not Solve Everything by Increasing Top-K
Increasing K can improve recall, but it can also increase irrelevant context, token usage, latency, and distraction.
Lower noise, but relevant supporting evidence may be missed.
Higher chance of including evidence, but more material must be ranked and processed.
Improve Context Construction
Retrieval results are not automatically good model context. Remove duplicates, preserve useful ordering, include source labels, and keep the final context focused.
Do not send the same passage repeatedly.
Keep document, page, section, or version information.
Prefer evidence that directly supports the question.
Leave room for the user's question and generated answer.
Improve the RAG Prompt
The generation prompt should clearly define how retrieved context is used. A common pattern is to tell the model to answer from the supplied evidence and to acknowledge when the evidence is insufficient.
question = "What is the refund window?"
context = "Policy 17: Refunds are available for 30 days."
prompt = f"""
Answer the question using only the provided context.
If the context does not contain enough information, say that you do not have enough evidence.
Context:
{context}
Question:
{question}
"""
print(prompt)The prompt improves grounding behavior, but it cannot create missing evidence. Retrieval quality still matters.
Control Hallucinations With Evidence Rules
Good RAG systems make unsupported answers less likely by defining what the model should do when evidence is missing or conflicting.
Use the retrieved evidence and identify the supporting source when citations are part of the application.
Say that the available context is insufficient or route the question for another retrieval step.
For conflicting documents, include version or effective-date metadata and define which source should take priority.
Improve Query Understanding
Some failures begin before retrieval because the user's wording is ambiguous, abbreviated, or conversational. Query rewriting can turn a short question into a clearer retrieval query.
Too broad to retrieve the correct policy reliably.
A more explicit representation can improve candidate discovery.
Query rewriting should preserve the user's intent. An aggressive rewrite can introduce assumptions that were never requested.
Use a Better Retrieval Pipeline
Metadata
Restrict by known constraints such as tenant, region, language, or version.
Hybrid/vector
Generate a broad but relevant candidate set.
Relevance
Reorder candidates using a stronger relevance model.
Compress
Send only the evidence needed by the generator.
This layered design is often more controllable than asking one retrieval step to solve every problem.
Improve With a Fixed Evaluation Set
Keep a representative dataset of questions and expected evidence. Every change to chunking, embeddings, retrieval, reranking, prompts, or models should be tested against the same baseline.
experiments = {
"baseline": {"recall_at_5": 0.72, "answer_accuracy": 0.68},
"hybrid": {"recall_at_5": 0.81, "answer_accuracy": 0.75},
"hybrid_reranked": {"recall_at_5": 0.81, "answer_accuracy": 0.80},
}
for name, scores in experiments.items():
print(name, scores)Do not declare success from one impressive question. Look at aggregate metrics and inspect representative failures.
Measure More Than Accuracy
A production improvement should consider quality and system behavior together.
Recall@K, Precision@K, MRR, NDCG.
Correctness, relevance, completeness, faithfulness.
Latency, throughput, failure rate, cache behavior.
Embedding, reranking, retrieval, and LLM token costs.
Common Improvement Mistakes
More layers do not guarantee better retrieval or answers.
You lose the ability to tell which change helped or hurt.
A good score can hide retrieval failures and unstable behavior.
A quality gain may not justify a much slower or more expensive system.
Practical Improvement Checklist
Are documents current, clean, complete, and deduplicated?
Do chunks preserve the evidence needed to answer questions?
Does the correct evidence appear in the candidate set?
Can metadata remove obviously wrong candidates?
Do exact terms matter for your query distribution?
Does second-stage ranking improve ordering enough to justify its cost?
Are duplicates and irrelevant passages removed?
Does the model answer from evidence and abstain when evidence is insufficient?
Mini Project: Improve a Weak RAG System
Imagine your baseline RAG system has Recall@5 = 0.65 and answer accuracy = 0.61. Your evaluation set shows that many failures come from wrong-region documents and poorly ranked candidates.
Restrict retrieval to the correct region and document version.
Test whether exact terms improve the candidate set.
Improve ordering before selecting final context.
Compare retrieval, answer quality, latency, and cost with the baseline.
30-Second Recap
- Improve the layer that is actually failing.
- Start with clean, current source data.
- Tune chunking, embeddings, filters, retrieval, and reranking using evaluation data.
- Keep final context focused instead of blindly increasing Top-K.
- Use prompts and evidence rules to improve grounding, not to compensate for missing evidence.
- Measure quality together with latency and cost.
- Keep a fixed evaluation set so every change is comparable.
Quick Quiz
A) Font size B) Retrieval/chunking/embeddings C) Final answer wording
A) It can increase noise, latency, and token cost B) It disables embeddings C) It removes metadata
A) Reorder retrieved candidates by stronger relevance B) Create PDFs C) Replace chunking
A) One example B) Same fixed evaluation set plus system metrics C) Guess from model confidence
Key Takeaways
The most useful improvement is not necessarily a bigger model. Better data, chunking, retrieval constraints, ranking, and context construction can often make a larger difference.