AI Hints
Home›RAG Tutorial›A First RAG App
RAG · Lesson 8 of 120

The Simplest Retriever

Matching words.

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

A retriever takes a question, and returns the most useful text. The simplest one counts shared words. Whichever page shares the most words with the question wins.

The Simplest Retriever
From the video: The Simplest Retriever
  • Question in
  • Best text out
  • Count shared words

Counting shared words

Words turns text into a set of lower case words. For each page, we count how many question words it contains, and sort the pages by that score. Run it. For a question about renting an e-bike, the rentals page scores highest.

word_retriever.pypython
import re
from kb import load_docs

def words(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))

def retrieve(question, docs, k=2):
    q = words(question)
    scored = [(len(q & words(d["text"])), d["source"]) for d in docs]
    return sorted(scored, reverse=True)[:k]

print(retrieve("How much does it cost to rent an e-bike for a week?", load_docs()))
Output
[(8, 'rentals.md'), (7, 'warranty.md')]
Also uses kb.py
from pathlib import Path

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

Good and bad

Word matching is fast, and easy to understand. But it only sees exact words. A question that says charge won't match a page that says charging, unless they share other words. Common words like the, and is, add noise too. We'll fix these problems step by step.

keyvalue
Goodsimple and fast
Badexact words only
Noisecommon words count
Fixbetter retrievers later

Summary

The simplest retriever ranks pages by shared words. It works sometimes, but it misses meaning. Next, your first complete RAG app.

Key takeaways
  • Words to sets
  • Count the overlap
  • Sort and take the top
Next up: Your First RAG App — under twenty lines