Implementing Multi-Query RAG to Improve Retrieval Quality
Imagine: your RAG system returns irrelevant answers for 20% of queries just because of poor phrasing. As engineers with deep experience in AI/ML, we've encountered this problem dozens of times. For example, the query 'how to dismiss an employee' and 'procedure for termination of employment contract' are the same, but the system sees different vectors and loses half the relevant documents. RAG (Retrieval-Augmented Generation) is a technique that improves retrieval by automatically paraphrasing the original query in several ways. Each variant is run through the search, and the results are merged. This reduces the dependency of answer quality on the specific query formulation and increases retrieval completeness. In our practice, this gave a 38% recall gain with a moderate increase in latency.
How Multi-Query RAG Increases Retrieval Completeness
The same information can be described using different terms. For example, in a corporate knowledge base, the query 'how to book leave' might find applications, 'procedure for obtaining annual leave' might find regulations, and 'rules for granting vacation days' might find HR policy. Multi-Query combines all three and obtains a more complete context, which is critical for business processes. According to RAG in practice research, the recall improvement can reach 38%.
Implementation with LangChain
from langchain.retrievers.multi_query import MultiQueryRetriever
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import Qdrant
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.3)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = Qdrant.from_existing_collection(
embeddings=embeddings,
collection_name="knowledge_base",
url="http://localhost:6333",
)
retriever = MultiQueryRetriever.from_llm(
retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
llm=llm,
include_original=True,
)
# Usage
docs = retriever.invoke("what is the procedure for approving a major transaction")
# Internally LangChain generates 3 paraphrases + original,
# searches with each and deduplicates results
This is the basic variant — we use it for quick prototypes. In production, a custom prompt adapted to the client's specifics is often required.
Custom Multi-Query with Prompt Control
The default LangChain prompt can be replaced with a specialized one:
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import BaseOutputParser
class LineListOutputParser(BaseOutputParser):
"""Parses a list of questions from the LLM response"""
def parse(self, text: str) -> list[str]:
lines = text.strip().split("\n")
return [line.strip().lstrip("123456789.-) ") for line in lines if line.strip()]
MULTI_QUERY_PROMPT = PromptTemplate(
input_variables=["question"],
template="""You are an AI assistant for document retrieval. Your task is to generate
5 different variants of the following question to improve search in a vector database.
Rules:
- Use synonyms and alternative phrasings
- One variant should be more specific, one more general
- Preserve the meaning of the original question
- Each question on a new line, without numbering
Original question: {question}
Variants:"""
)
custom_retriever = MultiQueryRetriever(
retriever=vectorstore.as_retriever(search_kwargs={"k": 4}),
llm_chain=MULTI_QUERY_PROMPT | llm | LineListOutputParser(),
include_original=True,
)
Our experience shows that a custom prompt yields 5-10% better recall, as it is adapted to the client's domain.
Parallel Multi-Query with Deduplication
To reduce latency, we run the search for all variants in parallel:
import asyncio
from openai import AsyncOpenAI
async def multi_query_search(
original_query: str,
vectorstore,
n_variants: int = 4,
top_k_per_query: int = 5,
) -> list[str]:
"""Parallel multi-query retrieval"""
async_client = AsyncOpenAI()
# Generate query variants
response = await async_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{
"role": "user",
"content": f"Generate {n_variants} paraphrases of the question:\n{original_query}\nOne question per line."
}],
temperature=0.5,
)
variants = response.choices[0].message.content.strip().split("\n")
all_queries = [original_query] + variants[:n_variants]
# Parallel search
search_tasks = [
asyncio.to_thread(vectorstore.similarity_search, q, k=top_k_per_query)
for q in all_queries
]
results_per_query = await asyncio.gather(*search_tasks)
# Deduplication by content
seen_texts = set()
unique_docs = []
for docs in results_per_query:
for doc in docs:
text_hash = hash(doc.page_content[:100])
if text_hash not in seen_texts:
seen_texts.add(text_hash)
unique_docs.append(doc)
return unique_docs
This approach keeps latency within 700-800 ms even with 5 query variants.
From Our Practice: A Legal Firm Case
We recently implemented Multi-Query RAG for a client in the legal sector. Dataset: corporate knowledge base (3200 documents). Test set — 200 queries with labeled relevant documents.
| Configuration | Recall@10 | Precision@5 | Latency (avg) |
|---|---|---|---|
| Single query, k=5 | 0.61 | 0.71 | 280ms |
| Single query, k=15 | 0.72 | 0.58 | 310ms |
| Multi-query (4 variants), k=5 | 0.84 | 0.69 | 680ms |
| Multi-query + Reranker | 0.84 | 0.81 | 920ms |
Multi-query lifted recall from 0.61 to 0.84 (+38%) with a moderate increase in latency (×2.4). After adding a reranker, precision also recovered to 0.81.
Comparison with alternatives: HyDE (Hypothetical Document Embeddings) in our test showed Recall@10 = 0.71 but required an extra step of generating a hypothetical document. Multi-Query is 18% better than HyDE in recall and simpler to implement.
| Method | Recall@10 | Latency (avg) | Implementation complexity |
|---|---|---|---|
| Single query | 0.61 | 280 ms | Low |
| HyDE | 0.71 | 450 ms | Medium |
| Multi-Query | 0.84 | 680 ms | Medium |
The table shows that Multi-Query provides the best recall with acceptable latency increase.
Why Multi-Query Is More Effective Than HyDE?
HyDE generates one hypothetical document and searches based on it, which yields an improvement but less than Multi-Query. The reason: multiple query variants cover more semantic variations than a single document. Moreover, Multi-Query is simpler to implement — no extra document generation step is needed.
How We Implement Multi-Query RAG: Step by Step
- Audit the current RAG system and dataset. Analyze query and document structure.
- Select the model for generating variants (GPT-4o-mini, Claude Haiku, LLaMA 3). Determine the number of variants (usually 3-5).
- Customize the prompt for the domain. Test on a representative sample.
- Integrate parallel search and deduplication. Optimize latency.
- A/B test on your queries. Compare with the current system.
- Document and train the team. Hand over code and instructions.
The entire cycle takes 1 week. Cost is calculated individually: typical range $5,000-$15,000 depending on complexity. It pays off in 2-3 months through time savings for users. According to client estimates, time savings on information search can be substantial for a large company, often exceeding $100,000 annually.
When to Implement Multi-Query and When Not?
Multi-Query is optimal if:
- user queries are varied and contain synonyms;
- the knowledge base has more than 5000 documents;
- latency up to 1 second is acceptable.
It is not needed when:
- latency requirements are below 200 ms;
- users strictly follow a single terminology;
- the dataset is small (single query already gives high recall).
What Is Included in Our Implementation Work
We implement Multi-Query RAG turnkey:
- Audit of the current RAG system and dataset.
- Selection of the model for generating variants (GPT-4o-mini, Claude Haiku, LLaMA 3).
- Customization of the prompt for the domain.
- Integration of parallel search and deduplication.
- A/B testing on your queries.
- Documentation and team training.
- Delivery: full source code, configuration files, deployment guide, test results report, and access to our support team for 30 days post-implementation.
With over 5 years of experience in AI/ML and 50+ successful RAG implementations, we guarantee a recall improvement of at least 30% or your money back. Our team holds certifications in OpenAI and LangChain.
Example prompt for generating variants
You are an AI assistant for document retrieval. Generate 5 different variants of the following question to improve search in a vector database.
Rules:
- Use synonyms and alternative phrasings
- One variant should be more specific, one more general
- Preserve the meaning of the original question
- Each question on a new line, without numbering
Original question: {question}
Variants:
Timeline and Cost
Estimated timeline:
- Implementation of Multi-Query Retriever: 2-3 days;
- Prompt tuning and number of variants: 2-3 days;
- Testing on dataset: 2-3 days;
- Total: 1 week.
Cost is calculated individually, but due to accelerated information search, the system pays for itself in 2-3 months. For a preliminary assessment of your scenario, contact us — we will analyze your dataset for free and recommend the optimal configuration. Order Multi-Query RAG implementation and get a recall improvement of up to 38% within a week. Get a consultation with an implementation engineer.







