LESSON 57 Β· RAG

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.

45 min readβ€’Intermediateβ€’Generative AI

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.
1

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.

QuestionWhat did the user ask?
β†’
RetrieveWas evidence found?
β†’
ContextWas it selected?
β†’
GenerateWas it used?
β†’
EvaluateWhat failed?
Key idea:Make one change at a time when possible, rerun the same evaluation set, and keep the baseline so you can prove whether the change helped.
2

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.

BETTER DATAClean and current documents

Remove accidental duplicates, preserve important headings, and keep document versions identifiable.

BAD DATANoise enters the index

Old policies, broken extraction, navigation text, and duplicated pages can compete with the correct evidence.

Practical rule:When answers are consistently wrong about one document family, inspect the source and ingestion pipeline before changing the model.
3

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.

FIXED-SIZE

Simple baseline

Useful when documents have little structure.

SENTENCE

Natural boundaries

Keeps sentence-level meaning together.

RECURSIVE

Structure-aware

Uses a hierarchy of separators.

SEMANTIC

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.

4

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.

TOO SMALLPrecise but incomplete

The retrieved chunk may contain a sentence but miss the condition or exception immediately around it.

TOO LARGEComplete but noisy

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.

5

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.

Match the domain

Test whether terminology, abbreviations, and product language are represented well.

Keep query and document models compatible

Use an embedding setup designed to compare the two sides correctly.

Benchmark before switching

Compare Recall@K and downstream answer quality on a fixed dataset.

Watch dimensions and cost

Larger vectors can affect storage, latency, and indexing cost.

6

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.

</> Python
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.

7

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.

SEMANTICβ€œHow can I reset access?”

Can match passages that explain account recovery even if the wording differs.

KEYWORDβ€œERR_AUTH_401”

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.

8

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.

QueryUser question
β†’
Top 20Fast candidates
β†’
RerankDeep relevance
β†’
Top 5Focused context

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.

9

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.

K = 3Focused context

Lower noise, but relevant supporting evidence may be missed.

K = 15Broad context

Higher chance of including evidence, but more material must be ranked and processed.

Better approach:Test K values against Recall@K, context relevance, answer correctness, latency, and token cost. Choose the smallest K that reliably supports the task.
10

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.

Deduplicate

Do not send the same passage repeatedly.

Preserve source metadata

Keep document, page, section, or version information.

Limit noise

Prefer evidence that directly supports the question.

Protect context budget

Leave room for the user's question and generated answer.

11

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.

</> Python
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.

12

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.

ENOUGH EVIDENCEAnswer and cite

Use the retrieved evidence and identify the supporting source when citations are part of the application.

INSUFFICIENT EVIDENCEDo not invent

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.

13

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.

USER QUERYβ€œWhat about refunds?”

Too broad to retrieve the correct policy reliably.

RETRIEVAL QUERYβ€œrefund eligibility window and conditions”

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.

14

Use a Better Retrieval Pipeline

1 Β· FILTER

Metadata

Restrict by known constraints such as tenant, region, language, or version.

2 Β· RETRIEVE

Hybrid/vector

Generate a broad but relevant candidate set.

3 Β· RERANK

Relevance

Reorder candidates using a stronger relevance model.

4 Β· CONTEXT

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.

15

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.

</> Python
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.

16

Measure More Than Accuracy

A production improvement should consider quality and system behavior together.

Retrieval

Recall@K, Precision@K, MRR, NDCG.

Generation

Correctness, relevance, completeness, faithfulness.

Operations

Latency, throughput, failure rate, cache behavior.

Cost

Embedding, reranking, retrieval, and LLM token costs.

17

Common Improvement Mistakes

01Adding components without evidence

More layers do not guarantee better retrieval or answers.

02Changing many variables at once

You lose the ability to tell which change helped or hurt.

03Using only final-answer scores

A good score can hide retrieval failures and unstable behavior.

04Ignoring cost and latency

A quality gain may not justify a much slower or more expensive system.

18

Practical Improvement Checklist

βœ“ Inspect data

Are documents current, clean, complete, and deduplicated?

βœ“ Test chunking

Do chunks preserve the evidence needed to answer questions?

βœ“ Benchmark retrieval

Does the correct evidence appear in the candidate set?

βœ“ Add filters

Can metadata remove obviously wrong candidates?

βœ“ Test hybrid search

Do exact terms matter for your query distribution?

βœ“ Test reranking

Does second-stage ranking improve ordering enough to justify its cost?

βœ“ Improve context

Are duplicates and irrelevant passages removed?

βœ“ Improve grounding

Does the model answer from evidence and abstain when evidence is insufficient?

19

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.

STEP 1Add metadata filtering

Restrict retrieval to the correct region and document version.

STEP 2Compare hybrid retrieval

Test whether exact terms improve the candidate set.

STEP 3Rerank candidates

Improve ordering before selecting final context.

STEP 4Re-evaluate

Compare retrieval, answer quality, latency, and cost with the baseline.

Your goal:Do not simply make the system more complex. Find the smallest set of changes that produces a measurable improvement.
20

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.
21

Quick Quiz

1. The correct chunk never appears in Top-K. What should you investigate first?

A) Font size   B) Retrieval/chunking/embeddings   C) Final answer wording

2. Why not always increase Top-K?

A) It can increase noise, latency, and token cost   B) It disables embeddings   C) It removes metadata

3. What is reranking used for?

A) Reorder retrieved candidates by stronger relevance   B) Create PDFs   C) Replace chunking

4. What is the best way to compare an improvement?

A) One example   B) Same fixed evaluation set plus system metrics   C) Guess from model confidence

22

Key Takeaways

Remember:A strong RAG system is usually the result of an iterative engineering process: inspect failures β†’ improve one layer β†’ evaluate β†’ measure trade-offs β†’ repeat.

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.