Learning path: Build and Measure a RAG System · Step 3 of 12
Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
Swap a toy embedder for a model that learned. Two roads (all-MiniLM-L6-v2 on your machine, or OpenAI's API with your key), three sizes (384, 1,536 and 3,072 numbers), one rule, and three use cases built on the same rank function, with real scores.
What you will learn
- Choose between an open embedding model you run and a provider API you pay per call
- Embed text with all-MiniLM-L6-v2 and read what the 384 numbers are
- Follow the one rule: embed questions and documents with the same model
- Use one rank function for search by meaning, duplicate tickets and recommendations
Before you start
- Embeddings: Words as Vectors and Cosine Similarity
- Similarity Search with NumPy
A toy embedder that only knows the words you typed in by hand gives up fast. Give it I can't get into my account and it returns zeros. In this article we swap it for a model that actually learned from a huge amount of text, look at the numbers it gives back, and put it to work three ways.
In a RAG system this is the embed step: the one that turns text into numbers. Every step after it leans on those numbers, so if they're poor, everything after them suffers. If cosine similarity is new to you, start with Embeddings and Cosine Similarity.
Two roads to an embedding
Think about a cup of coffee. You can buy a machine for home: set it up once, and every cup is yours. Or you go to a café: nothing to set up, but you pay for every cup. Either way, you get a cup of coffee.
You get embeddings through the API, not from a chat window. And the model sizes differ:
| Model | Road | Numbers per text |
|---|---|---|
| all-MiniLM-L6-v2 | Open, runs on your machine | 384 |
| text-embedding-3-small | OpenAI API | 1,536 |
| text-embedding-3-large | OpenAI API | 3,072 |
The trap: each model draws its own map. Never compare vectors from two different models. Embed your questions and your documents with the same one.
One function, two backends
The project hides both roads behind one function in embedder.py. The environment variable EMBED_BACKEND picks the road; the default is the free local model.
import math
import os
from dotenv import load_dotenv
load_dotenv()
BACKEND = os.getenv("EMBED_BACKEND", "local").lower()
LOCAL_MODEL = "all-MiniLM-L6-v2"
OPENAI_MODEL = "text-embedding-3-small"
MODEL = OPENAI_MODEL if BACKEND == "openai" else LOCAL_MODEL
_local = None
def embed(texts):
if BACKEND == "openai":
from openai import OpenAI
reply = OpenAI().embeddings.create(model=OPENAI_MODEL, input=texts)
return [item.embedding for item in reply.data]
global _local
if _local is None:
from sentence_transformers import SentenceTransformer
_local = SentenceTransformer(LOCAL_MODEL)
return [list(map(float, v)) for v in _local.encode(texts, normalize_embeddings=True)]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def rank(query, items, top=3):
"""The items closest in meaning to the query, best first: [(score, item), ...]."""
vectors = embed([query] + items)
scored = [(cosine(vectors[0], v), item) for v, item in zip(vectors[1:], items)]
return sorted(scored, reverse=True)[:top]
The model loads once, the first time it's needed. For the API road, load_dotenv() reads your key from a .env file, so it never sits in the code.
One sentence, 384 numbers
01_local_model.py embeds the sentence that broke the toy:
from embedder import MODEL, embed
SENTENCE = "I can't get into my account"
if __name__ == "__main__":
vector = embed([SENTENCE])[0]
print(f"model: {MODEL}")
print(f"sentence: {SENTENCE}")
print(f"numbers: {len(vector)}")
print("first 6: " + ", ".join(f"{x:.3f}" for x in vector[:6]))
model: all-MiniLM-L6-v2
sentence: I can't get into my account
numbers: 384
first 6: -0.003, -0.058, -0.014, -0.002, 0.015, -0.036
384 numbers for one short sentence, and 378 more behind the six shown. To be honest, one number alone means nothing. The meaning sits in the whole list.
The API version, 02_openai_model.py, first checks for a key. With none, it prints No OPENAI_API_KEY in .env, so no call was made. and stops. With your own key, the call goes to OpenAI, and OpenAI's guide gives 1,536 numbers for text-embedding-3-small. (The lecture run had no key, so no API call was made.)
Use case 1: search by meaning
Inside rank, three lines do all the work. The first embeds the question and all nine help articles: ten vectors from one model. The second compares the question with each article. Then sorted puts the closest first and top=3 keeps the best three. 03_search.py runs three questions:
search: I can't get into my account
0.52 Unlock a locked account
0.49 How to reset your password
0.28 Change your billing address
search: I was charged twice
0.66 Get a refund for a double charge
0.26 Cancel your plan
0.25 How to reset your password
search: how do I save my notes to a file
0.78 Export your notes
0.19 Download your monthly invoice
0.15 How to reset your password
The sentence that gave the toy zeros now finds the right articles. The first question is a close race, 0.52 against 0.49, and both are fair answers. The other two have a big gap between first and second. The bigger the gap, the clearer the match. Note that "save my notes to a file" shares almost no words with "Export your notes".
Use case 2: duplicate tickets
04_duplicates.py embeds six support tickets. itertools.combinations makes every pair (that's 15), cosine scores each one, and only pairs at or above a cut-off of 0.6 are kept.
def duplicates(tickets=TICKETS, threshold=THRESHOLD):
vectors = embed(tickets)
pairs = [(cosine(vectors[i], vectors[j]), tickets[i], tickets[j])
for i, j in combinations(range(len(tickets)), 2)]
return sorted((p for p in pairs if p[0] >= threshold), reverse=True)
pairs above 0.6:
0.81 The app crashes when I open settings <-> Settings screen closes the app immediately
0.70 I was charged twice this month <-> My card got billed two times
Two pairs say the same thing in different words. The other 13 pairs stay under the line; the best of them is only 0.25.
Use case 3: what to read next
A student has just read Python lists and loops for beginners. 05_recommend.py ranks the seven other titles against it with the same rank function:
you just read: Python lists and loops for beginners
0.56 Python functions made simple
0.45 Reading files in Python
0.35 Sorting data with Python dictionaries
The sourdough bread book drops to the bottom. Three use cases, one move every time: embed, then find what is close. When you have thousands of vectors instead of nine, that search is done with a matrix or a vector database; see Similarity Search and Chroma and pgvector.
Common mistakes
- Mixing models: documents embedded with MiniLM, questions with the API. The scores mean nothing.
- Switching the model later without re-embedding every stored document.
- Reading single numbers in a vector. Only the whole vector, compared with another, carries meaning.
- Putting the API key in the code. Keep it in
.env. - Copying a cut-off like 0.6 to a new model. Scores sit on a different scale per model; pick the threshold on your own data.
Quick recap
| Idea | In one line |
|---|---|
| Two roads | Open model you run (free, offline) or provider API (key, pay per use) |
| Sizes | 384 (MiniLM), 1,536 (3-small), 3,072 (3-large) |
| One rule | Questions and documents through the same model |
| One move | Embed, then find what is close: search, duplicates, recommendations |
Try it yourself
Add a ticket to 04_duplicates.py that repeats another one in new words, for example "I can't log in since I got a new phone". Does it pair up with "I can't sign in after changing my phone", and at what score?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.