Rana Maninder Singh
Lesson 5 of 8Generative AI

Embeddings for Semantic Search

Lesson opener

In one line: What an embedding vector represents.

Why it matters: Support agents should not hunt the wiki by exact wording while the customer waits on chat.

Before this lesson: Structured outputs / Text & embeddings (DL)

Before you start

ResourceLink
PreviousStructured outputs
NextRAG basics
PrerequisitesStructured outputs, Text & embeddings (DL)
Time~55 minutes

What you will learn

  • What an embedding vector represents
  • Ranking passages with cosine similarity (runnable, no API key)
  • How API embedding endpoints fit the same pattern
  • Offline helpers for top-k selection and tiny numpy vector stores

Pinned libraries

pip install -r docs/genai/requirements.txt

Pinned in docs/genai/requirements.txt:

openai>=1.40.0,<2
scikit-learn==1.5.2
numpy==2.1.3

Local demos use scikit-learn==1.5.2 and numpy==2.1.3. API embedding examples need openai>=1.40.0,<2 and # requires: api-key. Embedding model ids such as text-embedding-3-small are as of September 2026, check the pricing page / embeddings guide before you lock a production choice.


From keywords to meaning

Keyword search fails when the customer says "money gone" and the FAQ says "UPI debit". Embeddings place similar meanings nearby in vector space — the same idea you met in dl6, now used for retrieval.

In an Indian D2C FAQ, customers say "paisa cut", "amount deducted", or "UPI failed" for the same intent. Keyword filters miss synonyms; vector ranking surfaces the refund policy chunk even when the words differ.

WHY Support agents should not hunt the wiki by exact wording while the customer waits on chat.

WHEN FAQ search, policy lookup, and the retrieve step of RAG (genai6) — before you generate an answer.

A Bengaluru grocery app FAQ that only matches the string UPI will miss "money gone from bank but cart still unpaid." Embeddings (or even a strong TF-IDF prototype) rank by related words in the corpus. That is enough to prototype; production usually switches to a provider embedding model with the same query/document model rule.

Failure modes — search that looks smart and is not

Failure modeWhat you seeWhat to do
Keyword-only FAQSynonym questions return emptyAdd vector ranking (this lesson)
Mixed embedding modelsScores look random after a model swapRe-embed the whole corpus with one model
Huge undivided PDFsTop hit is a weak average of many topicsChunk by intent before embed (genai6)
No score floorLow-similarity junk still enters the promptGate on min cosine (offline demo below)
Stale indexNew GST policy never ranksRebuild vectors when docs change

Local demo — TF-IDF vectors + cosine

This runs offline with scikit-learn from the course requirements file:

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

docs = [
    "UPI debit succeeded but order still shows unpaid",
    "How to reset your Bengaluru office Wi-Fi password",
    "Refund timelines for cancelled grocery orders",
    "Update GSTIN on your tax invoice profile",
]
query = "payment cut but booking not confirmed"

vec = TfidfVectorizer()
X = vec.fit_transform(docs)
q = vec.transform([query])
scores = cosine_similarity(q, X).ravel()
ranked = sorted(enumerate(scores), key=lambda t: t[1], reverse=True)
for i, s in ranked:
    print(f"{s:.3f}  {docs[i]}")

WHY Cosine similarity ranks by angle, not raw magnitude.

WHEN Prototyping retrieval before paying for embedding APIs.

TF-IDF is not a neural embedding, but it teaches the same retrieve-then-rank shape you will keep when you swap in API vectors. For a twenty-line internal FAQ, this offline path is often enough to show product that synonym search works before anyone opens a billing console. For multi-thousand-doc corpora, move to a dedicated embedding model and a vector store — keep the same top_k helper interface so RAG code does not care which backend scored the passages.


Offline demo — top-k helper

Wrap ranking so RAG code can ask for the best two passages without reprinting sort logic.

# Offline demo: reusable top-k ranking over TF-IDF cosine scores
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


def top_k(docs: list[str], query: str, k: int = 2) -> list[tuple[str, float]]:
    vec = TfidfVectorizer()
    X = vec.fit_transform(docs)
    scores = cosine_similarity(vec.transform([query]), X).ravel()
    idx = scores.argsort()[::-1][:k]
    return [(docs[i], float(scores[i])) for i in idx]


faq = [
    "UPI failure refunds post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
    "GST invoices can be re-issued from Billing > Tax profile.",
]
hits = top_k(faq, "When does UPI money come back?", k=2)
print(hits)
assert "UPI" in hits[0][0]

Use k=2 or k=3 for FAQ bots unless evals prove more context helps. Extra chunks burn tokens in the later generate step (genai2) and can dilute the answer with a near-miss IT policy when the customer only asked about refunds.


Offline demo — tiny numpy matrix "store"

Small FAQs fit in a dense matrix. Store document vectors, embed the query the same way, multiply for scores. This mirrors what a vector DB does at larger scale.

# Offline demo: keep doc vectors in a numpy matrix and score a query
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import normalize

docs = [
    "Replace damaged items within 7 days with unboxing video.",
    "UPI failure refunds post within 3-5 banking days.",
    "Shift deliveries to the next working day after 8pm cutoff.",
]
vec = TfidfVectorizer()
X = normalize(vec.fit_transform(docs).toarray())
q = normalize(vec.transform(["refund for failed UPI"]).toarray())
scores = (q @ X.T).ravel()
best = int(np.argmax(scores))
print(best, docs[best], float(scores[best]))
assert "UPI" in docs[best]

Persist X and the fitted vectorizer (or the API embedding matrix) next to the FAQ version id. When content ops in Pune edits a refund sentence, rebuild the store in the same deploy — otherwise agents see confident wrong ranks from yesterday's vectors.


Offline demo — min-score gate before you trust a hit

Low cosine scores still produce a "top" document. Gate retrieval so a weak match becomes an empty list your RAG prompt can refuse on.

# Offline demo: drop weak cosine hits below a minimum score
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


def retrieve_gated(
    docs: list[str],
    query: str,
    k: int = 2,
    min_score: float = 0.05,
) -> list[tuple[str, float]]:
    vec = TfidfVectorizer()
    X = vec.fit_transform(docs)
    scores = cosine_similarity(vec.transform([query]), X).ravel()
    ranked = sorted(enumerate(scores), key=lambda t: t[1], reverse=True)
    hits = [(docs[i], float(s)) for i, s in ranked[:k] if s >= min_score]
    return hits


faq = [
    "UPI failure refunds post within 3-5 banking days.",
    "Password resets need the registered work email OTP.",
    "GST invoices can be re-issued from Billing > Tax profile.",
]
strong = retrieve_gated(faq, "UPI refund timing", min_score=0.01)
weak = retrieve_gated(faq, "quantum teleportation warranty", min_score=0.25)
print("strong", strong)
print("weak", weak)
assert strong and "UPI" in strong[0][0]
assert weak == []

WHY A forced top-1 always returns something — including irrelevant IT text for a payments question.

WHEN Before you paste retrieved chunks into a generate prompt; empty hits should become "I do not know" in genai6 / genai7.

Tune min_score on a labelled set of Indian support queries, not on a single happy-path demo. Festival-week slang and code-mixed Hindi–English can score lower than clean English even when the FAQ is right — raise k carefully, do not silently disable the gate.


API embeddings (production shape)

# requires: api-key
import os
import sys
from openai import OpenAI

api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    print("Set OPENAI_API_KEY; never hard-code keys.", file=sys.stderr)
    sys.exit(1)

client = OpenAI(api_key=api_key)
try:
    resp = client.embeddings.create(
        # Model as of September 2026, check the pricing page / embeddings guide
        model="text-embedding-3-small",
        input=["UPI debit succeeded but order still shows unpaid"],
    )
except Exception as exc:
    print(f"API call failed: {type(exc).__name__}: {exc}", file=sys.stderr)
    sys.exit(1)

vector = resp.data[0].embedding
print(len(vector))

Store vectors in a vector DB or a simple numpy matrix for small FAQs. Always embed the query with the same model you used for documents.

[!important] Mixing embedding models (or versions) silently breaks ranking.

Cost and ops notes for Indian teams: embedding calls are usually cheaper than chat completions per token, but re-embedding a full catalog after every typo fix still adds up. Batch document embeds on deploy; embed queries online. Keep model ids labelled as of September 2026, check the pricing page / embeddings guide when you compare vendors. Log which embedding model produced each index so a silent SDK default upgrade cannot invalidate ranks overnight.


Chunking preview

Long policies must be split into overlapping chunks before embedding — covered in RAG. Rule of thumb for FAQs: one intent per chunk. Oversized chunks dilute cosine scores; tiny chunks lose the sentence that held the policy number.

A single "Refunds & returns" mega-section that mixes UPI failures, card chargebacks, and damaged-goods photo rules will rank middling for every query and excellent for none. Split so the UPI sentence can surface alone. Overlap a sentence or two when a policy number is referenced from the next paragraph — full chunking strategies land in the next lesson.

Offline demo — compare keyword hit vs TF-IDF rank

Show stakeholders why "money gone" misses a UPI debit FAQ under keywords but surfaces under vector ranking.

# Offline demo: keyword miss vs TF-IDF hit on the same FAQ row
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

docs = [
    "UPI debit succeeded but order still shows unpaid",
    "How to reset your Bengaluru office Wi-Fi password",
]
query = "money gone from bank"

keyword_hit = any("money" in d.lower() and "gone" in d.lower() for d in docs)
vec = TfidfVectorizer()
X = vec.fit_transform(docs)
scores = cosine_similarity(vec.transform([query]), X).ravel()
best = int(scores.argmax())
print("keyword_hit", keyword_hit, "tfidf_best", docs[best], float(scores[best]))
assert keyword_hit is False
assert "UPI" in docs[best]

Verified against openai 1.40.0,<2, scikit-learn 1.5.2, numpy 2.1.3 documentation, September 2026.

Test yourself

  1. Why can keyword search miss "money gone" vs "UPI debit"?
  2. What does cosine similarity compare?
  3. Which sklearn class builds the local vectors in the demo?
  4. Why must query and documents use the same embedding model?
  5. What does text-embedding-3-small return in resp.data[0].embedding?
  6. True or false: TF-IDF demos replace production embedding APIs for huge corpora.
  7. What prior lesson introduced neural embeddings?
  8. What is a sensible FAQ chunking rule of thumb?
  9. Name one failure mode of mixing embedding models.
  10. True or false: higher cosine score means more similar in the demo ranking.

What's next

RAG basics