RAG · Lesson 60 of 120
Multi-Query
Asking several ways.
One question is just one way of saying something. If we ask the model for a few other ways to say it, and search with all of them, we're more likely to find the right chunk.

- One phrasing
- Several phrasings
- Better chance
Searching several ways
Queries is a list the model fills. We ask for three search queries that mean the same as the question. We search with each one, and merge the lists with reciprocal rank fusion. Run it. The original question misses the charging chunk. The merged results include it.
multi_query.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from hybrid import rrf
from llm import llm
class Queries(BaseModel):
queries: list[str]
index = Index(make_chunks(load_docs()))
q = "How many hours until my e-bike is full again?"
versions = llm.with_structured_output(Queries).invoke(
f"Write 3 search queries for an e-bike shop's help centre that mean: {q}").queries
lists = [[c for s, c in index.search(v, 3)] for v in [q] + versions]
print("original:", [c["text"][:18] for c in lists[0]])
print("merged: ", [c["text"][:18] for c in rrf(*lists)[:3]])Output
original: ['## Parts and elect', '## Making a claim ', 'Next-day delivery '] merged: ['## Parts and elect', '## Charging The Vo', '# E-bike battery g']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Also uses keyword_search.py
import re
from rank_bm25 import BM25Okapi
def words(text):
return re.findall(r"[a-z0-9]+", text.lower())
class Keyword:
def __init__(self, chunks):
self.chunks = chunks
self.bm25 = BM25Okapi([words(c["text"]) for c in chunks])
def search(self, query, k=3):
scores = self.bm25.get_scores(words(query))
top = sorted(range(len(scores)), key=lambda i: -scores[i])[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses hybrid.py
from rag_kit import Index
from keyword_search import Keyword
from sentence_transformers import CrossEncoder
def rrf(*ranked_lists, k=60):
scores, chunks = {}, {}
for ranked in ranked_lists:
for rank, chunk in enumerate(ranked):
key = chunk["text"]
scores[key] = scores.get(key, 0) + 1 / (k + rank + 1)
chunks[key] = chunk
return [chunks[t] for t in sorted(scores, key=lambda t: -scores[t])]
class Hybrid:
def __init__(self, chunks):
self.dense, self.sparse = Index(chunks), Keyword(chunks)
def search(self, query, k=5):
a = [c for _, c in self.dense.search(query, k=10)]
b = [c for _, c in self.sparse.search(query, k=10)]
return rrf(a, b)[:k]
reranker = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device="cpu")
def rerank(query, chunks, k=3):
scores = reranker.predict([(query, c["text"]) for c in chunks])
order = sorted(range(len(chunks)), key=lambda i: -scores[i])[:k]
return [chunks[i] for i in order]The cost
Multi query adds one model call, and several searches, to every question. It helps most with short or oddly worded questions. Use it when recall matters more than speed.
| key | value |
|---|---|
| Extra cost | 1 model call |
| Searches | 4 instead of 1 |
| Best for | odd wording |
| Use when | recall matters |
Summary
Multi query searches with several phrasings, and merges the results, so fewer chunks are missed. Next, HyDE.
Key takeaways- Several phrasings
- Search each
- Merge with RRF
Next up: HyDE — search with a draft answer