Gradient LabOpen in Gradient Lab

Lessons › Projects

Build a mini search engine (the R in RAG)

A search tool that answers questions from a company handbook by quoting the right passage and citing its source, and says so when it doesn’t know.

No setup needed. Run every step in your browser on Gradient Lab, or download it.

Open the notebook

Level: Intermediate · Time: 30 min · You’ll practise: TF-IDF vectors, cosine similarity, retrieval, grounded answers

Steps

1. Load the documents

Load 12 handbook passages, one per line, each with a title.

passages = [line.strip() for line in open("handbook.txt", encoding="utf-8") if line.strip()]
titles = [p.split(":")[0] for p in passages]
print(f"Loaded {len(passages)} passages")

2. Turn every passage into a vector

Turn every passage into a vector with TF-IDF, which gives rare, specific words more weight.

vectorizer = TfidfVectorizer(stop_words="english", ngram_range=(1, 2))
doc_vectors = vectorizer.fit_transform(passages)

3. Search = embed the question the same way, then find the closest passages

Search: turn the question into a vector the same way and rank passages by cosine similarity.

def search(question, k=2):
    q = vectorizer.transform([question])
    scores = cosine_similarity(q, doc_vectors)[0]
    best = scores.argsort()[::-1][:k]
    return [(titles[i], passages[i], scores[i]) for i in best]

4. "Answer" by quoting the best passage with its source, or admit we don't know

Answer by quoting the best passage with its source, or admit it isn’t in the handbook when the match is weak.

def answer(question):
    results = search(question)
    title, text, score = results[0]
    print(f"\nQ: {question}")
    if score < 0.1:
        print("A: I couldn't find that in the handbook.")
        return
    print(f"A: {text.split(':', 1)[1].strip()}")
    print(f"   Source: {title} (match {score:.2f}); next best: {results[1][0]} ({results[1][2]:.2f})")

questions = sys.argv[1:] or [
    "How many holiday days do new staff get?",
    "Can I work from another country?",
    "What do I do if a customer's card is stolen?",
    "Who won the cricket match?",
]
for q in questions:
    answer(q)

Expected output

$ python mini_search.py
Loaded 12 passages

Q: How many holiday days do new staff get?
A: New staff get 25 days of paid holiday per year, plus public holidays. Unused days up to 5 can be carried into the next year.
   Source: Holiday leave (match 0.49); next best: Password resets (0.06)

Q: Can I work from another country?
A: Employees may work from abroad for up to 30 days a year with manager approval. Longer stays need HR sign-off.
   Source: Remote work (match 0.37); next best: Complaints (0.00)

Q: What do I do if a customer's card is stolen?
A: If a customer reports a lost or stolen card, block it immediately in the card system and order a replacement free of charge.
   Source: Card blocking (match 0.50); next best: Complaints (0.08)

Q: Who won the cricket match?
A: I couldn't find that in the handbook.

Stretch goals

Download p09-mini-search.zip