Module 3 of 6 · 50 minutes

Embeddings and semantic search

Embeddings let systems match meaning rather than exact words. They're the foundation of semantic search, recommendations and RAG.

By · Last updated

Learning objectives

  • Explain what an embedding is
  • Compute cosine similarity
  • Describe the steps of semantic search
  • Recognise the limits of embeddings
  • Build a small semantic search
  • Explain why hybrid search and reranking are used
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport random
import re
import numpy as np
import pandas as pd

random.seed(7)
templates = {
    "delivery": ["My parcel arrived {d} days late and the box was crushed",
                 "Delivery took {d} days and the courier left it in the rain",
                 "Still waiting for my order after {d} days, no update",
                 "The tracking link never updated and delivery was {d} days late"],
    "product":  ["The {p} broke after a week",
                 "Love the {p}, great quality and well made",
                 "The {p} is much smaller than the photos suggest",
                 "Excellent {p}, works perfectly"],
    "billing":  ["I was charged twice for order {o}",
                 "Refund for order {o} still not received",
                 "The discount code did not apply at checkout",
                 "Invoice for order {o} shows the wrong amount"],
}
products = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
rows = []
for i in range(400):
    cat = random.choice(list(templates))
    msg = random.choice(templates[cat]).format(
        d=random.randint(2, 9), p=random.choice(products), o="GFY-%05d" % random.randint(10000, 99999))
    label = cat if random.random() > 0.08 else random.choice(list(templates))  # ~8% noisy labels
    rows.append({"text": msg, "category": label})
messages = pd.DataFrame(rows)

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
X_tfidf = tfidf.fit_transform(messages["text"])

3.1 Meaning, not just words

TF-IDF only matches exact words: "parcel" and "package" look unrelated. Embeddings fix this by representing words, sentences or documents as lists of numbers (vectors) learned so that texts with similar meanings sit close together. They power semantic search, recommendations, clustering and retrieval-augmented generation.

Practice mode on this page

Calling a real AI model needs a secret API key, and a key must never sit in a web page. So the cells that call a model on this page talk to a small pretend model built into the page. The code is what you'd write for the real thing, but the replies come from simple rules, not real AI. To use a real model, copy the code into a notebook such as Colab and add your own key (see Python for AI, Module 5).

parcel still missingpackage not arrivedcourier lost my boxrefund not receivedcharged twicemoney back pleasekettle brokelamp stopped workingquery: “my package hasn't come”meaning space (2D sketch)
Embeddings place texts with similar meanings close together, so a query finds its nearest neighbours even without shared words.

3.2 Measuring similarity

The usual measure is cosine similarity: how closely two vectors point in the same direction, from −1 (opposite) to 1 (identical direction). You can try the idea right now with TF-IDF vectors:

from sklearn.metrics.pairwise import cosine_similarity

query = ["my package has not arrived"]
q_vec = tfidf.transform(query)
scores = cosine_similarity(q_vec, X_tfidf).ravel()
best = scores.argsort()[-3:][::-1]
for i in best:
    print(round(scores[i], 2), messages["text"].iloc[i])

Notice that TF-IDF can only match on shared words like "arrived" — it doesn't know "package" means "parcel". That's the gap embeddings close.

3.3 Getting embeddings

Embeddings come from trained models. You can call an embeddings API (for example OpenAI's embeddings, Amazon Bedrock or Google Vertex AI), or run an open-source model locally. The shape of the code is the same either way:

Python · embeddings via an API (practice mode on this page)from openai import OpenAI

client = OpenAI()   # the real SDK reads OPENAI_API_KEY from the environment — never paste keys into code
EMBED_MODEL = "YOUR-EMBEDDING-MODEL"     # copy a current model name from the provider's docs

texts = ["my package has not arrived", "parcel still missing", "refund not received"]
resp = client.embeddings.create(model=EMBED_MODEL, input=texts)
vectors = np.array([d.embedding for d in resp.data])
print(vectors.shape)                         # (texts, numbers per text)
print(cosine_similarity(vectors).round(2))   # the first two should be most similar

The first two texts have no words in common — one says "package" and "not arrived", the other "parcel" and "missing" — yet their vectors are close, and neither is close to the refund message. That is what an embedding gives you that word counts can't.

3.4 Semantic search in four steps

  1. Embed every document (or chunk) once and store the vectors.
  2. Embed the user's query with the same model.
  3. Rank documents by cosine similarity to the query.
  4. Return the top results — or pass them to an LLM to answer from (RAG).

For more than a few thousand documents, store vectors in a vector database or index that finds nearest neighbours quickly. Combining embeddings with keyword search (hybrid search) usually beats either alone — see the RAG course.

Here are the four steps as code, on a five-answer help centre:

Python · semantic search over a small FAQfaqs = ["Returns are free within 30 days of delivery.",
        "Standard delivery takes 3 to 5 working days.",
        "Refunds are paid to your original payment method within 7 days.",
        "Discount codes must be entered before checkout and cannot be combined.",
        "If an item arrives broken, send a photo and we will replace it."]

def embed(texts):
    resp = client.embeddings.create(model=EMBED_MODEL, input=list(texts))
    return np.array([d.embedding for d in resp.data])

faq_vectors = embed(faqs)                                   # step 1: embed the documents once

def semantic_search(question):
    scores = cosine_similarity(embed([question]), faq_vectors).ravel()   # steps 2 and 3
    return faqs[scores.argmax()], round(float(scores.max()), 2)          # step 4

for q in ["my mug came smashed", "how long until my order gets here?", "is there a voucher I can use?"]:
    print(q, "->", semantic_search(q))

"Smashed" finds the answer about broken items, and "voucher" finds discount codes, with no words in common. Try your own questions. The practice model only knows a small vocabulary, so you will find gaps quickly; a real embedding model has the same kind of gaps, just much further out.

Embed alldocuments onceStore vectors(index / vector DB)Embed thequeryRank by cosinesimilarityReturn top results(or feed an LLM)
Semantic search in practice. Steps 1–2 happen in advance; steps 3–5 run for every query.

3.5 Limits of embeddings

  • Similar isn't the same as correct: "refund approved" and "refund refused" can sit close together
  • Embeddings reflect their training data, including its biases and blind spots
  • Domain jargon and rare product names may be poorly represented — test on your own data
  • Changing embedding model means re-embedding everything; vectors from different models aren't comparable
Python · similar is not the same as correctpair = embed(["Your refund has been approved", "Your refund has been refused"])
print("Similarity:", cosine_similarity(pair)[0, 1].round(2))

Two messages with opposite meanings for the customer score as highly similar, because they are about the same thing. Search by meaning finds text on the right topic; it can't tell you which answer is true.

3.6 Hybrid search: keywords and meaning together

Embeddings are weak exactly where keyword search is strong: order numbers, product codes, names and other exact strings. An embedding model has never seen "GFY-48213" and has no idea what it is "similar" to. Production search systems therefore run both and combine the scores — hybrid search.

Python · keyword, semantic and hybrid scores side by sidefrom sklearn.feature_extraction.text import TfidfVectorizer

notes = ["Order GFY-48213: customer reports the parcel never arrived",
         "Order GFY-51077: kettle replaced after it arrived cracked",
         "Customer asked how to apply a discount code at checkout",
         "Package lost by courier, refund issued in full"]
keyword = TfidfVectorizer(token_pattern=r"[A-Za-z0-9-]+").fit(notes)
note_kw, note_vec = keyword.transform(notes), embed(notes)

def hybrid_search(query, weight=0.5):
    kw = cosine_similarity(keyword.transform([query]), note_kw).ravel()
    sem = cosine_similarity(embed([query]), note_vec).ravel()
    table = pd.DataFrame({"keyword": kw.round(2), "semantic": sem.round(2),
                          "hybrid": (weight * kw + (1 - weight) * sem).round(2), "note": notes})
    return table.sort_values("hybrid", ascending=False)

print(hybrid_search("GFY-51077").to_string(index=False))
print()
print(hybrid_search("my shipment went missing").to_string(index=False))

For the order number, the keyword score does all the work and the semantic score is close to useless. For "my shipment went missing" it is the other way round: no words match, and meaning carries it. The hybrid column gets both right.

Many systems add a final step, reranking: a slower, more careful model reads the question alongside each of the top twenty or so results and re-orders them. Fast methods narrow thousands of documents to a shortlist; the reranker makes the final call on the shortlist.

Exercise: a tiny FAQ search

Using a TfidfVectorizer fitted on the FAQs in the starter code, write search(question) that returns the best-matching answer and its score. Try a question that uses different words from the FAQ. What happens, and how does that compare with semantic_search from 3.4?

Your turnfrom sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

faq_list = ["Returns are free within 30 days of delivery.",
            "Standard delivery takes 3 to 5 working days.",
            "Refunds are paid to your original payment method within 7 days.",
            "Discount codes must be entered before checkout and cannot be combined.",
            "If an item arrives broken, send a photo and we will replace it."]

# Write your code here, then press Run
Show a solution
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

faq_list = ["Returns are free within 30 days of delivery.",
            "Standard delivery takes 3 to 5 working days.",
            "Refunds are paid to your original payment method within 7 days.",
            "Discount codes must be entered before checkout and cannot be combined.",
            "If an item arrives broken, send a photo and we will replace it."]

faq_vec = TfidfVectorizer(stop_words="english").fit(faq_list)
faq_X = faq_vec.transform(faq_list)

def search(question):
    s = cosine_similarity(faq_vec.transform([question]), faq_X).ravel()
    return faq_list[s.argmax()], round(float(s.max()), 2)

print(search("how long does delivery take"))
print(search("my mug came smashed"))   # no shared words: score 0, and the 'best' answer is just the first one
# The first result is wrong as well: to TF-IDF 'take' and 'takes' are different words,
# so only 'delivery' matched, and it matched the returns answer. semantic_search gets both right.
Exercise: find near-duplicate messages

Support teams often receive the same complaint several times. Embed the five messages in the starter code, compute the similarity between every pair, and print the pairs scoring above 0.6. Which messages are saying the same thing?

Your turninbox = ["My parcel is late", "Package still delayed", "I was charged twice",
         "Double payment taken from my card", "Love the new kettle"]

# Write your code here, then press Run
Show a solution
inbox = ["My parcel is late", "Package still delayed", "I was charged twice",
         "Double payment taken from my card", "Love the new kettle"]

vecs = embed(inbox)
sims = cosine_similarity(vecs)
for i in range(len(inbox)):
    for j in range(i + 1, len(inbox)):
        if sims[i, j] > 0.6:
            print(round(float(sims[i, j]), 2), "|", inbox[i], "|", inbox[j])
# Grouping near-duplicates lets one reply (or one fix) deal with many messages.

Key takeaways

  • Embeddings place similar meanings close together.
  • Cosine similarity measures how closely vectors point the same way.
  • Embed documents once, embed each query, rank, return.
  • Similar isn't the same as correct; test on your own data.
  • Don't mix vectors from different models.
  • Keyword search wins on exact codes and names; embeddings win on meaning; hybrid search uses both.
  • A reranker re-orders a shortlist with a slower, more careful model.