← Building with AI

Searching your documents

Score documents by shared keywords and pick the best.

Start this lesson

A model doesn't know your shop's opening hours or your school's rules. Retrieval fixes that: first search your own documents for the parts that match the question, then give those parts to the model. The search can be simple. Count how many important words a document shares with the question, and keep the documents with the highest scores.

def words(text):
    return {w.strip("?.,!:;()") for w in text.lower().split() if len(w.strip("?.,!:;()")) > 3}

q = words("How much is a yearly membership?")
d = words("Membership: A yearly membership costs 60 dollars.")
print(q & d)        # {'yearly', 'membership'}
print(len(q & d))   # score: 2

A set keeps each word once. q & d is the set of words in both. Skipping short words (3 letters or fewer) ignores little words like 'how' and 'is'.

Real systems often use embeddings: lists of numbers that capture meaning, so 'bike' can match 'bicycle'. The steps are the same: score, sort, take the top few.

This is called RAG, retrieval-augmented generation: retrieve the documents, then generate the answer with them.