Build a RAG app

Chapter 6 of 1130 min

Embeddings: meaning as numbers

  1. Load
  2. Chunk
  3. Embed
  4. Search
  5. Ask the AI
  6. App

In this chapter you will:

  • learn what an embedding is, and why it captures meaning
  • install your first AI model and run it on your own laptop
  • measure how close two sentences are in meaning

The idea

In chapter 5, "days off" and "annual leave" looked like strangers to your program, because it compared spelling. To compare meaning, you need a way to write meaning down that a computer can work with.

An embedding does exactly that. A small AI model reads a piece of text and turns it into a long list of numbers, here 384 of them. You can't read the numbers yourself, but they have one useful property: texts that mean similar things get similar numbers, even when they share no words.

The model learned this by reading a huge amount of text, so it has seen "days off", "holiday" and "annual leave" used in the same kinds of sentences.

To compare two embeddings, we use a similarity score. It is close to 1 when two texts mean nearly the same thing, and close to 0 when they're unrelated.

Install the model's library

Make sure your virtual environment is on (you see (.venv)), then:

pip install sentence-transformers

This is the biggest download of the project, a few hundred MB, because it brings PyTorch, the machine learning library the model runs on. Give it a few minutes.

On Linux, first run pip install torch --index-url https://download.pytorch.org/whl/cpu, then the line above. Otherwise pip downloads the much bigger version of PyTorch made for graphics cards, which this project doesn't need.

Try it

Create a new file, try_embeddings.py. It's a playground, separate from your app:

try_embeddings.py
from sentence_transformers import SentenceTransformer
 
model = SentenceTransformer("all-MiniLM-L6-v2")
 
sentences = [
    "How much time off do I get?",
    "Everyone gets 24 days of paid annual leave each year.",
    "Lock your laptop screen when you walk away.",
]
 
vectors = model.encode(sentences)
print("Each sentence became", len(vectors[0]), "numbers")
print("The first five numbers of sentence 1:", vectors[0][:5])
 
scores = model.similarity(vectors[0], vectors)
print()
for i in range(len(sentences)):
    print(round(float(scores[0][i]), 2), sentences[i])
  • SentenceTransformer("all-MiniLM-L6-v2") loads a small, free embedding model. The first time, it downloads it (about 90 MB); after that it loads from your disk. It runs on your own laptop: no account, no key, no cost.
  • model.encode(sentences) turns each sentence into its list of numbers, called a vector.
  • model.similarity(vectors[0], vectors) compares the first sentence with every sentence, including itself.

Predict, then check

The question is about time off. Which of the other two sentences will score higher against it, and will either score close to 1?

Show answer

The annual-leave sentence scores far higher than the laptop one, though neither is close to 1:

1.0 How much time off do I get?
0.31 Everyone gets 24 days of paid annual leave each year.
0.08 Lock your laptop screen when you walk away.

The question compared with itself is exactly 1. Annual leave is clearly related (0.31), the laptop sentence is not (0.08). Scores are useful for comparing, not as a percentage: 0.31 isn't "31% the same", it's just much closer than 0.08.

python try_embeddings.py

You should see

Each sentence became 384 numbers
The first five numbers of sentence 1: [ 0.05878139 -0.01700913  0.00775919  0.02061877  0.02844626]
 
1.0 How much time off do I get?
0.31 Everyone gets 24 days of paid annual leave each year.
0.08 Lock your laptop screen when you walk away.

The long decimals can differ slightly in the last digits on your computer; the three scores should match.

You may also see a line starting Warning: You are sending unauthenticated requests to the HF Hub. That's the model download site suggesting an account; you can ignore it.

Practice

Add two sentences of your own to the list: one that means "holiday" without using any of the same words, and one about something else entirely. Run it again. Does the model rank them the way a person would?

Save your progress

git add .
git commit -m "Chapter 6: embeddings"

Stuck, or want to compare? The finished code for this chapter is tagged ch06: run git diff ch06, or see it on GitHub.