Learning path: Build and Measure a RAG System · Step 1 of 12
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".
What you will learn
- Explain an embedding as a list of numbers that describes meaning
- Find the nearest meaning by measuring distance between points
- Build a toy sentence embedder and search help articles by closeness
- See why hand-picked numbers fail and why an embedding model learns them instead
Before you start
- Basic Python lists and dictionaries
You will hear the word embedding in almost every AI engineering conversation. It sounds harder than it is. The idea fits in one line: we turn meaning into numbers, and close numbers mean close meaning. That is what gives us search by meaning.
In this article we build that idea from scratch in plain Python, with no model and no API key, and then break it on purpose so you can see why real embedding models exist.
Where embeddings sit in a RAG system
A RAG system cuts documents into pieces, turns each piece into numbers and stores them. Then, on every question, it retrieves the closest pieces, builds a prompt and answers. Embedding is the "turn it into numbers" step. Text goes in, a list of numbers comes out, and every later stage works on those numbers, so it is the one to understand first. (The full flow is in The RAG Pipeline Explained.)
Search by meaning, not by word
Picture a help centre. A customer types I cannot log in, and the search says zero results. But there is an article called How to reset your password. Same problem. Compare the words: not one word is shared.
A keyword search matches letters, and we want something that matches meaning. A computer only understands numbers, so we need a way to turn meaning into numbers.
Think of a city map. The cafes sit together on one street, the hospitals on another. When a new cafe opens, you already know which street to look on. Same kind, same neighbourhood. An embedding does this for meaning.
Describe a word with two numbers
Take one word, kitten, and give it two scores by hand. Is it an animal? Very much: 0.85. Can you eat it? No: 0.15. Put them side by side, [0.85, 0.15], and that list is an embedding. That is the whole definition: a list of numbers that describes what something means.
Here it is in 01_word_map.py. The comment says what the two numbers mean:
"""An embedding made by hand: two numbers per word, then find the nearest words on the map."""
import math
# [how much it is an animal, how much you can eat it]
WORDS = {
"cat": [0.90, 0.10],
"kitten": [0.85, 0.15],
"dog": [0.95, 0.20],
"apple": [0.05, 0.90],
"banana": [0.10, 0.95],
"car": [0.00, 0.05],
}
def nearest(word):
"""Every other word, closest first (straight-line distance on the map)."""
me = WORDS[word]
others = [(other, math.dist(me, vec))
for other, vec in WORDS.items() if other != word]
return sorted(others, key=lambda pair: pair[1])
if __name__ == "__main__":
for word in ("kitten", "apple"):
print(f"{word} {WORDS[word]}")
for other, d in nearest(word):
print(f" {d:.2f} {other}")
Two numbers are just coordinates, so every word becomes a point on a map. Cat, kitten and dog land together, high on "animal". Apple and banana are food, so they sit together on the other side. Car is neither, so it ends up alone in the corner.
Close on the map, close in meaning
So how does the computer decide what is similar? nearest takes the numbers for our word, then math.dist measures the straight line to every other word, and sorted puts the shortest first:
python 01_word_map.py
kitten [0.85, 0.15]
0.07 cat
0.11 dog
0.86 car
1.10 apple
1.10 banana
apple [0.05, 0.9]
0.07 banana
0.85 car
1.10 kitten
1.14 dog
1.17 cat
Cat is 0.07 away from kitten, dog 0.11. Car is 0.86, and apple and banana are 1.10. Find the nearest points, and you have found the nearest meaning.
More questions, more numbers
Two questions give a flat map. Add a third, "is it small?", and the map becomes a room: same idea, one more direction. Keep adding questions and the list grows to hundreds of numbers. We can't draw that, but distance works in exactly the same way. More numbers give more ways to describe meaning.
Sentences get numbers too
Our customer typed a sentence, not a word, so here is a toy embedder in 02_tiny_search.py. It has three topics, account, billing and pets, each with a few words we chose by hand:
"""A toy embedder: score a sentence on three topics we picked by hand, then search by closeness."""
import math
import re
TOPICS = {
"account": {"log", "login", "password", "reset", "locked"},
"billing": {"invoice", "bill", "receipt", "refund", "charged"},
"pets": {"cat", "dog", "kitten", "puppy", "pet"},
}
ARTICLES = [
"How to reset your password",
"Download your monthly invoice",
"Feeding your new kitten",
]
def embed(text):
"""Text -> [account, billing, pets], scaled so the list has length 1."""
words = re.findall(r"[a-z]+", text.lower())
vec = [sum(w in topic for w in words) for topic in TOPICS.values()]
length = math.sqrt(sum(x * x for x in vec)) or 1.0
return [round(x / length, 2) for x in vec]
def closeness(a, b):
"""1.0 = same direction, 0.0 = nothing in common."""
return round(sum(x * y for x, y in zip(a, b)), 2)
def search(query):
q = embed(query)
return sorted(((closeness(q, embed(a)), a) for a in ARTICLES), reverse=True)
if __name__ == "__main__":
for text in ["I cannot log in"] + ARTICLES:
print(f"{str(embed(text)):<18} {text}")
for query in ("I cannot log in", "I was charged twice", "I can't get into my account"):
print(f"\nsearch: {query}")
for score, article in search(query):
print(f" {score:.2f} {article}")
embed lowercases the sentence, splits it into words and counts the topic words. I cannot log in contains "log", an account word, so it scores one on account. Then it scales the list to length one, so a long sentence doesn't win just by having more words. We get back three numbers: [1.0, 0.0, 0.0].
Search by closeness
search sends the question through embed, then sends each article through the very same embed. closeness multiplies the matching numbers and adds them up. How to reset your password is also an account sentence, so it scores 1.00. The invoice article is billing and the kitten article is pets: nothing in common, so 0.00. sorted(..., reverse=True) puts the highest first.
Run it, and watch it break
python 02_tiny_search.py
[1.0, 0.0, 0.0] I cannot log in
[1.0, 0.0, 0.0] How to reset your password
[0.0, 1.0, 0.0] Download your monthly invoice
[0.0, 0.0, 1.0] Feeding your new kitten
search: I cannot log in
1.00 How to reset your password
0.00 Feeding your new kitten
0.00 Download your monthly invoice
search: I was charged twice
1.00 Download your monthly invoice
0.00 How to reset your password
0.00 Feeding your new kitten
search: I can't get into my account
0.00 How to reset your password
0.00 Feeding your new kitten
0.00 Download your monthly invoice
The question and the password article get the very same list, so the first search puts the password article on top at 1.00. I was charged twice finds the invoice article, because "charged" is a billing word.
Now the last one. I can't get into my account: every article scores 0.00. We picked the words by hand, and "get into" was never on our list. "Account" is only the name of a topic, not one of its words.
An embedding model learns the numbers
You could add those words. Then someone writes I'm signed out, or can't sign on. The list never ends. Numbers we choose by hand will always miss something, so we need numbers that are learned.
That is what an embedding model gives us. It learned from a huge amount of text, and it returns hundreds or thousands of numbers per text. No single number has a name; only the whole list means something. The job is the same as our toy: text goes in, a list of numbers comes out, and you use the same model for the questions and the articles. You can see a real one at work in Real Embedding Models: an Open Model or a Provider API.
Common mistakes
- Thinking each number has a meaning. In our toy it does ("animal", "food"). In a real model, no single number has a name; only the whole list does.
- Embedding questions and documents with different models. They land on different maps, so distances mean nothing. Same model for both, always.
- Expecting keyword tricks to scale. Adding synonyms by hand fixes one query and misses the next, exactly as "get into my account" showed.
- Forgetting to scale to length one. Without it, a long sentence with many matching words can win just for being long.
Quick recap
| Idea | In our code |
|---|---|
| An embedding is a list of numbers that describes meaning | "kitten": [0.85, 0.15] |
| Close numbers mean close meaning | math.dist: kitten to cat 0.07, to apple 1.10 |
| Search becomes "find the nearest points" | search() puts the password article first at 1.00 |
| Hand-picked numbers miss words | "I can't get into my account" scores 0.00 everywhere |
| A model learns the numbers for you | Hundreds of numbers, same model for questions and documents |
Try it yourself
Put "puppy" into WORDS in 01_word_map.py. It's an animal you can't eat, so guess its nearest word first, then run it. After that, add "account" to the account topic in 02_tiny_search.py and run the failing search again. Next, see how to measure "close" in more than one way in Cosine, Dot Product or Euclidean Distance.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
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.
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.