Sub topic 11
Embeddings and Semantic Search
This chapter assumes you can write basic Python, read JSON, and know what a prompt and a model API are. You don't need any machine learning background.
What an embedding is
An embedding is a list of numbers (a vector) that a model produces for a piece of text. Texts with similar meaning get vectors that point in similar directions. "How do I get my money back?" and "refund steps" end up close together, even though they share no words.
Keyword search matches exact terms. Semantic search matches meaning, by comparing vectors instead of strings.
How semantic search works
- Embed every document once and store the vectors. This is the indexing step.
- When a query arrives, embed it with the same model.
- Score each document vector against the query vector.
- Return the top results.
Measuring closeness
The usual score is cosine similarity. It measures the angle between two vectors. A value near 1 means the vectors point the same way, and a value near 0 means they are unrelated.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, docs, k=2):
# docs is a list of (text, vector) pairs
ranked = sorted(docs, key=lambda d: cosine(query_vec, d[1]), reverse=True)
return [text for text, _ in ranked[:k]]
docs = [("refund policy", [1.0, 0.0]), ("shipping times", [0.0, 1.0]), ("refund steps", [0.9, 0.1])]
print(top_k([1.0, 0.0], docs))This prints ['refund policy', 'refund steps']. Real vectors have hundreds or thousands of dimensions, not two. The logic is the same. At scale, a vector database or an approximate nearest-neighbor index replaces the full sort, because scoring every document on every query gets slow.
Common errors
- Mixing models. Query and documents must use the same embedding model. Vectors from different models are not comparable.
- Chunks that are too large or too small. A long document averages many topics into one vector. A tiny fragment loses context. Split documents into passages of a few sentences to a few paragraphs.
- Trusting the score blindly. Top-k always returns something, even when nothing is relevant. Set a minimum similarity threshold and test it on real queries.
- Expecting exact matches. Semantic search can miss product codes, names, or error numbers. Many systems combine it with keyword search (hybrid search).
- Stale index. When documents change, re-embed them. Otherwise results point to old content.
Where it is used
- Search over help articles, notes, or code.
- Finding duplicate or similar tickets.
- Recommending related content.
- Retrieval for answering questions from your own documents.
Exercise
A search for "error E4021" returns articles about general error handling but not the article that mentions E4021. Why might this happen, and what is one fix?
Show answer
Embeddings capture meaning, so a rare exact token like a code can get little weight in the vector. Add keyword search alongside semantic search (hybrid search) so exact terms are matched directly.
Exercise
You switch to a newer embedding model but keep the old stored document vectors. What goes wrong?
Show answer
The query vectors and document vectors come from different models, so their similarity scores are meaningless. You must re-embed all documents with the new model.