Chapter 7 of 1130 min
Search by meaning
- Load
- Chunk
- Embed
- Search
- Ask the AI
- App
In this chapter you will:
- turn every chunk of the handbook into an embedding, once
- find the chunks whose meaning is closest to a question
- fix the question that broke your keyword search
The plan
Last chapter you compared three sentences. Now do the same with the whole handbook:
- Once, at the start: embed all 26 chunks.
- For every question: embed the question, score it against every chunk, and keep the best three.
Why three and not one? Because the closest chunk isn't always the one with the answer, as you're about to see. In the next chapter the AI will read all three and pick out what it needs.
Load the model in rag.py
At the top of rag.py, under import os, add:
import os
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")The model is loaded once, when rag.py is imported, and every function in the file can use it.
Embed the chunks
Add to the end of rag.py:
# Chapter 7: turn every chunk into numbers, once
def embed_chunks(chunks):
texts = []
for chunk in chunks:
texts.append(chunk["text"])
return model.encode(texts)model.encode takes the whole list at once, which is much faster than one chunk at a time. It returns one vector per chunk, in the same order as chunks, so vector number 5 belongs to chunk number 5.
Search
Add this too:
# Chapter 7: find the chunks whose meaning is closest to the question
def search(question, chunks, chunk_vectors, top=3):
question_vector = model.encode(question)
scores = model.similarity(question_vector, chunk_vectors)[0]
best = scores.argsort(descending=True)[:top]
results = []
for i in best:
results.append(chunks[i])
return resultsscoresholds one similarity score per chunk.scores.argsort(descending=True)gives the positions of the scores from highest to lowest. If chunk 7 scored best, the list starts with 7.[:top]keeps the first three positions, and the loop turns them back into chunks.
top=3 is a default value: call search(question, chunks, chunk_vectors) and you get 3; call it with top=5 and you get 5.
Use it
Replace main.py:
from rag import load_documents, split_into_chunks, embed_chunks, search
documents = load_documents("data")
chunks = split_into_chunks(documents)
chunk_vectors = embed_chunks(chunks)
print("Loaded", len(documents), "documents and made", len(chunks), "chunks")
while True:
question = input("\nYour question (press Enter to stop): ")
if question == "":
break
for chunk in search(question, chunks, chunk_vectors):
print()
print("From", chunk["source"])
print(chunk["text"])Predict, then check
In chapter 5, How many days off do I get a year? found the paragraph about expense claims. What will search by meaning find?
Show answerHide answer
Three paragraphs from leave.txt, all about annual leave. The one that answers the question ("24 days") is second.
python main.pyYou should see
From leave.txt
You can carry up to five unused days of annual leave into the next year. Carried-over days must be used by the end of March, or they are lost. Unused days are never paid out as money.
From leave.txt
Everyone at Brightpath Studio gets 24 days of paid annual leave each calendar year. If you join partway through the year, you get two days of annual leave for every full month left in the year.
From leave.txt
To book annual leave, use the HR portal at least two weeks before the first day you want off. Leave of five days or more in a row also needs your team lead's approval.All three are about the right topic, though the question shares almost no words with them. That's search by meaning.
Notice the answer is second, not first: the carry-over paragraph talks about "days" and "the next year", which is close in meaning too. This is normal, and it's exactly why we keep the top three. Real RAG apps keep 3 to 10.
Practice
Ask Can I work from Bali for a few weeks? and Who shows me around on my first day? Then try the questions that worked with keyword search in chapter 5. Is search by meaning ever worse?
You can delete keyword_search from rag.py now, or keep it to compare. The rest of the project doesn't use it.
Save your progress
git add .
git commit -m "Chapter 7: search by meaning"Stuck, or want to compare? The finished code for this chapter is tagged ch07: run git diff ch07, or see it on GitHub.