Retrieval-Augmented Generation (RAG) with Python

Lesson 6 of 9

Retrieval

With both the knowledge base and the query turned into vectors, this lesson finds which stored chunks are actually relevant to the question, by measuring how similar their vectors are.

Cosine similarity

The standard way to compare two vectors for similarity is cosine similarity: the cosine of the angle between them, ranging from -1 (opposite) to 1 (identical direction), regardless of each vector's magnitude. For sparse Counter-based vectors, it only needs to look at the words that appear in both:

Pythonshares state with other Python blocks

Run it, the password-related pair should score noticeably higher than the unrelated pair, exactly what makes retrieval work.

Retrieving the top-K matches

Scoring the query against every stored chunk and keeping only the best few (top-K) is the retrieval step itself:

Pythonshares state with other Python blocks

sort(..., reverse=True) puts the highest similarity scores first, then [:top_k] keeps only that many, everything else is discarded, only the most relevant handful of chunks moves on to the next step.

TIP

top_k is another tunable knob: too small and you might miss a relevant chunk, too large and you dilute the final prompt with irrelevant text (and pay for more tokens). 2-5 is a common starting point for small knowledge bases.

📝 Retrieval Quiz

Passing score: 70%
  1. 1.What does cosine similarity measure between two vectors?

  2. 2.retrieve() keeps only the top_k highest-scoring chunks and discards the rest.

  3. 3.Retrieving only the best few matches instead of every chunk is called top-____ retrieval.