Hybrid Retrieval in Retrieval-Augmented Generation Systems
Introduction
We are now in the fourth and final lesson of this course on Beyond Basic RAG: Improving Our Pipeline! Up to this point, we have explored ways to enhance Retrieval-Augmented Generation (RAG) systems by refining chunking strategies and leveraging advanced retrieval methods. In this lesson, you will learn how to merge a lexical-based retrieval approach (using Okapi BM25) with your existing embedding-based retrieval mechanism, creating a powerful hybrid retrieval pipeline.
By the end of this lesson, you should be able to:
- Grasp the intuition behind Okapi BM25 for lexical retrieval.
- Construct a
BM25index on your corpus. - Combine
BM25scores with embedding-based retrieval scores using a configurable weight parameter, alpha.
Understanding the Okapi BM25 Algorithm
Within the category of lexical-based search methods, Okapi BM25 is a popular choice. It focuses on the presence of specific keywords, rewarding relevant chunks that contain more occurrences of the query terms. At the same time, it avoids overemphasizing repeated words by incorporating a saturation effect.
A few core ideas behind BM25:
- Term Frequency (TF): More keyword matches in a chunk can signal higher relevance.
- Document Length Normalization:
BM25accounts for chunk length, ensuring that very long chunks with many repeated words are not unfairly scored.
Although the underlying formula has several parameters and normalizations, the general purpose is straightforward: favor chunks containing the search terms, but don't let them dominate purely by repeating keywords.
Building a BM25 Index
Here is a simple function that builds a BM25 index from your chunked corpus. We assume you already have a collection of text chunks ready.
In this snippet:
- We split chunks into tokens (words) by lowercasing and splitting their text.
- We use a custom
BM25Indexclass to create our lexical index. - Later, we'll score new queries on this index to get relevance.
