AI Hints
Home›RAG Tutorial›Better Retrieval
RAG · Lesson 52 of 120

Why Retrieval Fails

The usual suspects.

⏱ 2 min read▶ Video at 51:56🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Most bad RAG answers start with bad retrieval. Before we fix it, we need to know how it fails. There are a few usual suspects, and we'll meet each one in this section.

Why Retrieval Fails
From the video: Why Retrieval Fails
  • Bad answers
  • Start with retrieval
  • The usual suspects

The usual suspects

Embeddings can miss exact codes and names. Short chunks, like a lone heading, carry no facts. Vague questions match many pages weakly. And a big question may need facts from several pages at once.

ProblemExampleFix in this section
Exact codesE03keyword search
Empty chunksa lone headingchunk headers
Vague questionsit's brokenquery rewriting
Big questionstwo topicsdecomposition

A failure to study

We search for the meaning of error code E03. Run it. The top results are the error page's title, and the E05 code, not the chunk that explains E03. Embeddings see codes as similar, so the exact code gets lost.

failure.pypython
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))
for score, c in index.search("What does E03 mean?", k=3):
    print(score, "|", c["text"][:60])
Output
0.45 | # E-bike display error codes  These codes appear on the disp
0.36 | E05: the motor is overheating. Stop riding for 15 minutes, t
0.33 | # E-bike battery guide
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Summary

Retrieval fails on exact codes, empty chunks, vague questions, and big questions. Next, keyword search.

Key takeaways
  • Exact codes
  • Empty chunks
  • Vague questions
Next up: Keyword Search — BM25