AI Hints
Home›RAG Tutorial›Vector Search
RAG · Lesson 28 of 120

Searching by Meaning

The whole index.

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

Now we can search properly. Embed every chunk once. When a question arrives, embed it, score it against every chunk, and return the best few. Let's try the question that fooled word matching.

Searching by Meaning
From the video: Searching by Meaning
  • Embed every chunk
  • Score the question
  • Return the best

Make chunks splits the help centre. We embed all chunks into one matrix. The matrix times the question vector scores every chunk at once, and arg sort puts the best first. Run it. The next day delivery chunk wins, for the question that fooled word matching.

semantic_search.pypython
import numpy as np
from rag_kit import load_docs, make_chunks, embed

chunks = make_chunks(load_docs())
vectors = embed([c["text"] for c in chunks])

question = "Can I get next-day delivery on a bike?"
scores = vectors @ embed([question])[0]
for i in np.argsort(-scores)[:3]:
    print(round(float(scores[i]), 2), chunks[i]["source"], "|", chunks[i]["text"][:50])
Output
0.72 shipping.md | Next-day delivery is available for parts and acces
0.6 shipping.md | ## UK delivery Standard delivery in the UK takes 3
0.51 shipping.md | ## International delivery We ship parts and access
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
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]

Our search kit

From now on, we'll keep this code in a small file, called rag kit. It loads documents, makes chunks, embeds text, and its index class searches. We'll reuse it in many lessons.

rag_kit.pypython
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

Semantic search embeds every chunk, scores the question against all of them, and returns the top few. Next, embeddings from an API.

Key takeaways
  • Embed chunks once
  • Score every chunk
  • Top k results
Next up: Gemini Embeddings — an embedding API