Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 16 / Stage 4

Embeddings and vector search

Goal: Find relevant text by meaning: vectors, similarity, chunking, and the sparse/dense trade-off. Time: ~2.5 hours · Needs: Part 2 (cosine), Part 13

What you will learn

  • What embeddings are
  • Similarity search with cosine and top-k
  • Sparse vs dense vectors: TF-IDF/BM25 vs neural embeddings
  • Chunking long text
  • Hybrid search

Topics in this part

Practice

Run from the repo root with PYTHONPATH=tools. Everything is offline.

Exercise 1: Top-3 for five queries

Build the TF-IDF index over SUPPORT_DOCS and print the top-3 doc ids with scores for five queries of your own. Mark which top-1 hits look wrong.

Show the solution to Exercise 1
# Exercise 1: Top-3 for five queries
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import SUPPORT_DOCS

texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)

QUERIES = [
    "how long is the laptop warranty",
    "pay when the parcel arrives",
    "order arrived broken",
    "ship to another country",
    "lost my login",
]
for q in QUERIES:
    scores = cosine_similarity(vec.transform([q]), doc_vectors)[0]
    top = [(SUPPORT_DOCS[i]["id"], round(float(scores[i]), 3))
           for i in scores.argsort()[::-1][:3]]
    print(f"{q!r:40s} -> {top}")

Exercise 2: The paraphrase gap

Score these query pairs against the index: ("return an item", "send it back"), ("reset password", "can't get into my account"). Print each query's top-1 doc and score. Which paraphrases survive keyword matching, which don't?

Show the solution to Exercise 2
# Exercise 2: The paraphrase gap
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import SUPPORT_DOCS

texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)


def top1(q):
    scores = cosine_similarity(vec.transform([q]), doc_vectors)[0]
    i = int(scores.argmax())
    return SUPPORT_DOCS[i]["id"], round(float(scores[i]), 3)


pairs = [("return an item", "send it back"),
         ("reset password", "can't get into my account")]
for direct, paraphrase in pairs:
    print(f"{direct!r:28s} -> {top1(direct)}")
    print(f"{paraphrase!r:28s} -> {top1(paraphrase)}")
    print()
# The direct wording hits its doc; paraphrases that share no content words
# ('send it back') score near zero or land elsewhere — the sparse gap.

Exercise 3: Chunker with structure

Write chunk_paragraphs(text, max_words) that splits on blank lines and only falls back to word-window splitting (with overlap 5) inside paragraphs longer than max_words. Test on a three-paragraph text where one paragraph is 60 words.

Show the solution to Exercise 3
# Exercise 3: Chunker with structure
def chunk_words(text, size, overlap):
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]


def chunk_paragraphs(text, max_words):
    chunks = []
    for para in [p.strip() for p in text.split("\n\n") if p.strip()]:
        if len(para.split()) <= max_words:
            chunks.append(para)
        else:
            chunks.extend(chunk_words(para, max_words, overlap=5))
    return chunks


short1 = "Returns are free within 30 days."
long_para = " ".join(f"word{i}" for i in range(1, 61))
short2 = "Contact support by chat, day and night."
text = f"{short1}\n\n{long_para}\n\n{short2}"

for i, c in enumerate(chunk_paragraphs(text, max_words=25)):
    words = c.split()
    preview = " ".join(words[:4]) + (" ... " + " ".join(words[-2:]) if len(words) > 6 else "")
    print(f"{i}: {len(words):2d} words | {preview}")
# Short paragraphs stay whole; only the 60-word one is window-split (with the
# 5-word overlap visible between its pieces).

Exercise 4: Tiny hybrid

Implement reciprocal-rank fusion rrf(rank_a, rank_b) = Σ 1/(60+rank). Rank the docs for "refund for damaged blender" by TF-IDF, by a keyword-presence score, and by their fusion. Print all three rankings.


Show the solution to Exercise 4
# Exercise 4: Tiny hybrid
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from ailab import SUPPORT_DOCS

texts = [d["title"] + ". " + d["text"] for d in SUPPORT_DOCS]
ids = [d["id"] for d in SUPPORT_DOCS]
vec = TfidfVectorizer(stop_words="english").fit(texts)
doc_vectors = vec.transform(texts)

QUERY = "refund for damaged blender"

tfidf_scores = cosine_similarity(vec.transform([QUERY]), doc_vectors)[0]
tfidf_rank = [ids[i] for i in tfidf_scores.argsort()[::-1]]

keyword_scores = [sum(w in t.lower() for w in QUERY.lower().split()) for t in texts]
keyword_rank = [ids[i] for i in sorted(range(len(ids)), key=lambda i: -keyword_scores[i])]


def rrf(*rankings, k=60):
    score = {doc: 0.0 for doc in ids}
    for ranking in rankings:
        for rank, doc in enumerate(ranking, start=1):
            score[doc] += 1.0 / (k + rank)
    return sorted(ids, key=lambda d: -score[d])


print("tfidf  :", tfidf_rank[:4])
print("keyword:", keyword_rank[:4])
print("fused  :", rrf(tfidf_rank, keyword_rank)[:4])

Mini-project: Help-centre search

Build top-3 search over SUPPORT_DOCS and run all 8 EVAL_QUESTIONS through it; print each question's ranked ids, flagging ✓/✗ against the labelled relevant doc. Summarise: how many top-1 hits, how many top-3?

A complete version is in solutions/mini_help_centre_search.py.

Stretch: swap TF-IDF for neural embeddings stored in pgvector and compare recall@3.

Common mistakes

Mistake Why it is wrong Fix
One vector per document Everything averages into mush Chunk, then embed
Chunks cut mid-sentence by byte count Facts split, retrieval misses Split on structure, add overlap
Pure dense with SKUs/ids in queries Embeddings blur exact tokens Hybrid
Pure sparse for conversational queries Paraphrases miss Dense or hybrid
Trusting the demo without an eval You can't see the misses Measure recall@k first (Part 17)

Quick recap

  • Embeddings place similar meanings at nearby vectors, and cosine similarity is the ruler.
  • Search means embedding the documents once, embedding the query, and taking the top k (ANN indexes handle scale).
  • Sparse matches words, dense matches meaning — the "send back" miss is measured, not hypothetical.
  • Chunk by structure with overlap; keep metadata for citations.
  • Hybrid search fuses dense and sparse scores; make it the default once identifiers appear in queries.

Checklist

  • I can explain an embedding in one sentence.
  • I ran top-k search and read the scores.
  • I can predict which query types break sparse and which break dense.
  • I chunked text with overlap and know the defaults.
  • I know when hybrid is worth the extra moving part.

Read more: Embeddings guide

Search the guide