RAG Explained: Indexing, Retrieval, Generation and Query Translation
LLMs answer with confidence even when their training data is stale or missing. RAG fixes that by retrieving the right documents at question time. This guide builds a RAG pipeline stage by stage in LangChain, then improves retrieval with four query translation techniques.
What is retrieval augmented generation?
Retrieval augmented generation, or RAG, is an architecture for optimizing the performance of an artificial intelligence (AI) model by connecting it with external knowledge bases. RAG helps large language models (LLMs) deliver more relevant responses at a higher quality.
Generative AI models are trained on large datasets and refer to this information to generate outputs. However, training datasets are limited to the information the AI developer can access: public domain works, internet articles, social media content and other publicly accessible data.
RAG allows generative AI models to access additional external knowledge bases, such as internal organizational data, scholarly journals and specialized datasets. By integrating relevant information into the generation process, chatbots and other natural language processing (NLP) tools can create more accurate, domain-specific content without needing further training.
RAG extends the already powerful capabilities of LLMs to specific domains or an organization's internal knowledge base, all without the need to retrain the model. It is a cost-effective approach to improving LLM output so it remains relevant, accurate and useful in various contexts.
Known challenges of LLMs include:
- Presenting false information when they do not have the answer.
- Presenting out-of-date or generic information when the user expects a specific, current response.
- Creating a response from non-authoritative sources.
- Creating inaccurate responses due to terminology confusion, where different training sources use the same terminology to talk about different things.
Note
You can think of a large language model as an over-enthusiastic new employee who refuses to stay informed with current events but will always answer every question with absolute confidence. Unfortunately, such an attitude can negatively impact user trust, and it is not something you want your chatbots to emulate.
RAG is one approach to solving some of these challenges. It redirects the LLM to retrieve relevant information from authoritative, predetermined knowledge sources. Organizations have greater control over the generated text output, and users gain insight into how the LLM generates the response.
The term comes from a 2020 paper by Patrick Lewis and colleagues, Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, presented at NeurIPS 2020.
RAG vs fine-tuning
One possible way to influence a model with our own data is fine-tuning: incorporating the data into the model's training process. This enables the model to construct responses that take the provided data into account. However, it is often not the optimal solution, for several reasons:
- Cost and effort. Fine-tuning or training a model takes compute resources and GPU access.
- Information is not valid forever. It might need to change, which calls for fine-tuning again every time it is modified.
- There is no mechanism to make the model forget what it has learned.
- Information that grows periodically is a poor fit, because each addition means another round of fine-tuning.
- The prompt is limited. A model can receive data in two ways, through fine-tuning and through the prompt, but the amount of information we can give it in the prompt is limited.
The solution
Use RAG, so that the model receives the information it needs for the specific question the user asks.
Private data or recent data may not be included in an LLM's training data, and since LLM context windows have become increasingly large, we can fit information from external sources into them. RAG is a popular technique for doing this, and it involves three general steps: indexing, retrieval and generation.
The three stages of RAG
External documents are indexed so that they can easily be retrieved based on an input query: we ask a question and retrieve the documents that are relevant to it. Those documents are fed into an LLM in the final generation stage to produce an answer that is grounded in them.
Indexing
Turn external documents into a searchable store, so the ones relevant to a question can be found quickly.
Retrieval
Embed the question the same way as the documents, and pull back the documents that sit closest to it.
Generation
Hand the retrieved documents and the question to the LLM, which writes an answer grounded in them.

From these three basic components, many interesting methods and tricks fan out, such as query transformation, routing and query construction.

Setting up
The code runs in a notebook such as Google Colab or Jupyter. It uses OpenAI for embeddings and for the LLM, Chroma as a local vector store, and LangSmith for tracing and for pulling a shared prompt.
!pip install -q langchain langchain-community langchain-openai langchain-chroma langchain-text-splitters langsmith beautifulsoup4 tiktoken
import os
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = "your-langsmith-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["USER_AGENT"] = "my-rag-app"Keep keys out of notebooks
Never paste a real key into a notebook you share or commit. Read keys from the environment or a secrets store (Colab has a Secrets panel for this), and rotate any key that has already been shared.
A complete RAG pipeline
Before taking each stage apart, here is the whole pipeline in one cell. It indexes Lilian Weng's blog post LLM Powered Autonomous Agents and answers a question about it.
import bs4
from langsmith import Client
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_chroma import Chroma
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
#### INDEXING ####
# Load Documents
loader = WebBaseLoader(
web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
bs_kwargs=dict(
parse_only=bs4.SoupStrainer(
class_=("post-content", "post-title", "post-header")
)
),
)
docs = loader.load()
# Split
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(docs)
# Embed
vectorstore = Chroma.from_documents(documents=splits,
embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()
#### RETRIEVAL and GENERATION ####
# Prompt (pulled from LangSmith's prompt hub)
client = Client()
prompt = client.pull_prompt("rlm/rag-prompt", dangerously_pull_public_prompt=True)
# LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Post-processing
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Chain
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
# Question
rag_chain.invoke("What is Task Decomposition?")This builds a small RAG pipeline in two stages:
Step 01: Indexing
The code downloads a blog post from the web and strips out just the article content (title, header and body) using BeautifulSoup. Since language models and embedding models can only handle so much text at once, the article is chopped into smaller, overlapping chunks of about 1,000 characters each. Each chunk is then converted into a vector, a list of numbers that captures its meaning, using OpenAI's embedding model. Those vectors are stored in Chroma, a local vector database, which acts as a searchable index of the document.
Step 02: Retrieval and generation
When a question comes in, the retriever compares the question's own vector against all the stored chunk vectors and pulls back the ones most similar in meaning. Those chunks are joined into a single block of text and inserted into a prompt template, pulled from LangSmith's prompt hub, alongside the original question. The combined prompt is sent to the LLM (
gpt-4o-mini), which reads the retrieved context and generates an answer grounded in it, rather than relying purely on what it memorized during training. The final line runs the whole chain end to end on the sample question "What is Task Decomposition?"
The core idea
Instead of hoping the model already knows the answer, you hand it the exact source material first, so its answer is more accurate and traceable back to a real document.
Why dangerously_pull_public_prompt=True
Recent versions of the LangSmith SDK refuse to pull a public prompt by owner/name, such as rlm/rag-prompt, unless you pass this flag, because a shared prompt can contain serialized LangChain objects and configuration that run inside your application. Set it only after reading the prompt yourself, and pin a specific commit of any public prompt you depend on.
Indexing

The first step in a RAG pipeline is indexing: taking a set of external documents and turning them into a searchable store that a retriever can later query. Given an input question, the retriever's job is to pull out the documents that are relevant to it. The most common way to judge relevance is by comparing numerical representations of text, since comparing vectors of numbers is far more efficient and scalable than comparing raw text directly.
Over the years, a number of approaches have been developed to compress text documents into these numerical representations, or vectors, so they can be searched quickly and accurately.

These approaches fall into two broad categories:
Statistical methods: sparse vectors
Methods such as TF-IDF and BM25 represent a document as a sparse vector. Each position corresponds to a word in a large vocabulary, and its value reflects how often that word appears in the document. Most positions are zero, because any single document uses only a small fraction of the vocabulary. These vectors are typically searched with an inverted index, a well-established and efficient method for keyword-based retrieval.
Machine-learned methods: dense embeddings
Embeddings use neural network models to compress a document into a dense, fixed-length vector that captures its semantic meaning rather than just its word frequencies. They are searched with approximate nearest neighbor (ANN) algorithms, which are built to find similar vectors efficiently, even across very large collections.
The best-known statistical weightings are TF-IDF and BM25. TF-IDF scores a word in a document by how often it appears there (term frequency), discounted by how many documents in the collection contain it (inverse document frequency), so a word that appears everywhere, like the, counts for almost nothing. BM25, the default ranking function in search engines such as Elasticsearch, refines this in two ways: each repeat of a word adds less to the score than the one before, and long documents are normalized so that they do not win simply by containing more words. For the formulas with worked examples, and for how dense embeddings are learned, see Vector Semantics and Embeddings.
In practice, many production systems combine both approaches, known as hybrid search, since sparse methods are strong at exact keyword matches while dense embeddings are better at capturing meaning and paraphrasing.
Before documents can be embedded, they need to be split into smaller pieces, or chunks, because embedding models can only process a limited amount of text at once. Chunking can be done by character count, document section, delimiter or semantic meaning, depending on the content and the desired granularity of retrieval. Each chunk is then passed through an embedding model and converted into a vector that represents its meaning.
At query time, the question is processed the same way: it is broken into tokens and converted into its own vector. With both the document chunks and the question represented as vectors, the system can use a similarity measure, such as cosine similarity, to identify which chunks are most relevant to the question.
Embeddings and cosine similarity in code
# Documents
question = "What kinds of pets do I like?"
document = "My favorite pet is a cat."
from langchain_openai import OpenAIEmbeddings
embd = OpenAIEmbeddings()
query_result = embd.embed_query(question)
document_result = embd.embed_query(document)
len(query_result)
import numpy as np
def cosine_similarity(vec1, vec2):
dot_product = np.dot(vec1, vec2)
norm_vec1 = np.linalg.norm(vec1)
norm_vec2 = np.linalg.norm(vec2)
return dot_product / (norm_vec1 * norm_vec2)
similarity = cosine_similarity(query_result, document_result)
print("Cosine Similarity:", similarity)This block shows embeddings and similarity directly. It takes a question and a single sentence, converts each into a dense vector using OpenAI's embedding model (the machine-learned approach, as opposed to a sparse, frequency-based method like TF-IDF or BM25), and checks the vector's length. That length is the embedding's fixed dimensionality, the same number whether the input is a short sentence or a full paragraph. With LangChain's default OpenAI model, text-embedding-ada-002, it is 1,536.
The cosine_similarity function then recreates the comparison step by hand: it measures how closely two vectors point in the same direction, as a proxy for how semantically related their original texts are. A higher score means the texts are more alike in meaning, even if they do not share the same words.
Which distance to use
OpenAI recommends cosine similarity for its embeddings. They are normalized to length 1, so cosine similarity equals the dot product, and cosine similarity and Euclidean distance produce identical rankings. That is why Chroma's default distance, squared L2, returns the same nearest neighbors for these vectors as cosine similarity would.
Loading, splitting and storing in code
#### INDEXING ####
# Load blog
import bs4
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader(
web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
bs_kwargs=dict(
parse_only=bs4.SoupStrainer(
class_=("post-content", "post-title", "post-header")
)
),
)
blog_docs = loader.load()
# Split
from langchain_text_splitters import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=300,
chunk_overlap=50)
# Make splits
splits = text_splitter.split_documents(blog_docs)
# Index
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(documents=splits,
embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever()This block builds the indexing pipeline. WebBaseLoader pulls in the external document, and the SoupStrainer filters out everything except the title, header and body content, so the pipeline is not indexing navigation bars or footers.
RecursiveCharacterTextSplitter.from_tiktoken_encoder then performs the chunking step. Since the embedding model can only handle a limited amount of text per call, the document is broken into overlapping chunks, sized in tokens (300 tokens per chunk, 50 tokens of overlap) rather than raw characters, which is closer to how models measure text. The overlap preserves context that would otherwise be cut off at a chunk boundary.
Finally, Chroma.from_documents runs each chunk through the same embedding model and stores the resulting vectors in a vector database: the searchable store. Wrapping it with .as_retriever() turns that store into an object that can take a new question, embed it the same way, and run a similarity search (an approximate nearest neighbor search under the hood) to find the chunks whose vectors are closest to the question's vector.
Count tokens the way your model does
from_tiktoken_encoder counts tokens with the GPT-2 encoding unless told otherwise. OpenAI's current embedding models use cl100k_base, so pass encoding_name="cl100k_base" if you want chunk sizes measured exactly as the embedding model sees them.
Indexing, in short, makes documents easy to retrieve.
Retrieval
Once documents have been embedded and indexed, retrieval is the step where the system actually finds the documents relevant to a given question.
Every embedding places a document at a point in a high-dimensional space, one dimension for each value in its vector. It helps to picture this with a toy example: if an embedding had only three dimensions, each document would land at a specific point in 3D space, positioned according to its semantic content rather than its exact wording. Documents with similar meaning end up close together in this space, while unrelated documents end up far apart.

This one idea, that proximity in vector space reflects similarity in meaning, is the foundation most modern vector stores and retrieval methods are built on. Real embedding models do not use three dimensions; they typically use hundreds or thousands, but the same geometric intuition holds.
To retrieve documents relevant to a question, the system embeds that question into the same n-dimensional space, using the same embedding model that was applied to the documents. It then searches for the vectors nearest to the question's vector, a nearest neighbor search within that space. Because proximity corresponds to semantic similarity, the nearest documents are the ones most likely to be relevant, and these are the documents the retriever returns.
In practice, this search is rarely done by comparing the question against every single vector one by one. It relies on the approximate nearest neighbor methods mentioned in the indexing section, which keep the search fast even across very large collections. Chroma, the store used here, builds an HNSW (hierarchical navigable small world) index, a graph-based ANN method.

To watch this search happen step by step, try the playground below. Ten short documents are the vector store: pick a query, a way of turning text into vectors and a distance measure, then follow the retriever as it embeds the query, scores every document and keeps the closest three. Vector Semantics and Embeddings explains each option in depth.
Vector search playground
An interactive 3D view of a small vector store: pick a query, a representation and a distance measure, and step through the search. It loads as you scroll here, and needs JavaScript.
Retrieval in code
# Index
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(documents=splits,
embedding=OpenAIEmbeddings())
retriever = vectorstore.as_retriever(search_kwargs={"k": 1})
docs = retriever.invoke("What is Task Decomposition?")
len(docs)This code puts retrieval into practice using the chunks (splits) produced during indexing. Chroma.from_documents embeds each chunk with OpenAI's embedding model and stores the resulting vectors, placing every chunk at a point in that high-dimensional space. vectorstore.as_retriever(search_kwargs={"k": 1}) wraps the vector store in a retriever configured to return just the single nearest neighbor for any query: k is literally the number of nearest neighbors to retrieve. Without it, the retriever returns four.
retriever.invoke("What is Task Decomposition?") is where the retrieval happens: the question is embedded into the same space, and the retriever finds whichever chunk sits closest to the question's vector. len(docs) confirms how many chunks came back, which is 1, matching k.
Generation
Generation is the final step in a RAG pipeline: taking the documents retrieved for a question and using them to produce an answer.
As a quick recap of the steps so far: documents are split into chunks, each chunk is embedded into a vector and stored in a vector store, and the question is embedded the same way. The system then searches that vector store, typically with a nearest neighbor method such as KNN (k-nearest neighbors), for the chunks whose vectors sit closest to the question's vector. Those nearby chunks are judged the most relevant, so they are the ones retrieved.
Once the relevant chunks are retrieved, they need to be handed to the LLM alongside the original question, so it can produce an answer grounded in that content.
Step 01: A prompt template with placeholders
The handover happens through a prompt template: a piece of text with placeholders, or variables, built into it. A typical RAG prompt has two, one for the context (the retrieved chunks) and one for the question, acting like empty slots waiting to be filled.
Step 02: A dictionary fills the template
The retrieved chunks and the question are gathered into a dictionary that maps each placeholder name to its value. That dictionary populates the template, producing a complete prompt with the actual context and question in place of the placeholders.
Step 03: The LLM answers
The filled-in prompt is sent to the LLM, which returns its response as a chat message.
Step 04: An output parser extracts the text
Since a chat message is a structured object rather than plain text, an output parser extracts just the text content, giving the final answer as a plain string.
A hand-written prompt in code
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Prompt
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
# LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Chain
chain = prompt | llm
# Run
chain.invoke({"context": format_docs(docs), "question": "What is Task Decomposition?"})This block builds a prompt template by hand. template is a plain string with two placeholders, {context} and {question}, the two slots described above. ChatPromptTemplate.from_template(template) turns that string into a reusable prompt object that knows how to fill them. chain = prompt | llm pipes the filled prompt straight into the model, and chain.invoke(...) supplies the actual values. format_docs joins the retrieved chunks into a single block of readable text, so the model receives clean context instead of raw Python objects.
A prompt from the hub, wired into one chain
from langsmith import Client
client = Client()
prompt_hub_rag = client.pull_prompt("rlm/rag-prompt", dangerously_pull_public_prompt=True)
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt_hub_rag
| llm
| StrOutputParser()
)
rag_chain.invoke("What is Task Decomposition?")This block swaps the hand-written prompt for one pulled from LangChain's prompt hub. client.pull_prompt("rlm/rag-prompt", ...) fetches a prompt template the LangChain community has already written and tested for retrieval question answering. It is not fundamentally different from the one written by hand above, and it still expects context and question variables, but it is a shared, battle-tested version rather than something built from scratch each time.
rag_chain then wires the whole pipeline together in one expression. retriever | format_docs retrieves the relevant chunks and immediately formats them into text, RunnablePassthrough() passes the incoming question through unchanged, and both are slotted into prompt_hub_rag. The filled prompt goes to the LLM, and StrOutputParser() strips the chat message down to plain text, so rag_chain.invoke("What is Task Decomposition?") returns the final answer as a string.
Why temperature=0
Temperature controls how much randomness the model injects into its output: higher values make responses more varied and creative, lower values make them more focused and deterministic. In a RAG setup, the goal is for the model to answer strictly from the retrieved context rather than improvise, so a low or zero temperature is generally preferred. It reduces the chance of the model wandering into unsupported claims, makes answers more consistent across runs, and is especially useful when testing or evaluating a pipeline, since you want to know the retrieved context is doing its job, not that the model got creative.
Query translation
Query translation sits at the front of an advanced RAG pipeline. Its job is to take the user's original question and reshape it in some way before it ever reaches the retriever, with the goal of getting better documents back.
The problem it solves is a practical one. Retrieval works by comparing the embedded question against embedded documents and pulling back whatever sits closest in that space. If a user's question is vague, oddly phrased, or simply worded very differently from how the source documents talk about the same topic, that comparison can miss the mark, and the retriever returns documents that are not actually the best match.
There are a few broad strategies for dealing with this, each pulling the question in a different direction:
Query rewriting
The question is reframed or restated from a different angle. Multi-query and RAG Fusion both fall into this category.
Query decomposition
A broad question is broken down into smaller, more specific sub-questions. Google's least-to-most prompting takes this approach.
Query abstraction
The opposite move: a specific question is generalized into a broader, higher-level one. This is the idea behind step-back prompting.

Multi-query
The multi-query approach is a form of query rewriting. The core intuition is simple: a single way of phrasing a question might not land close to the right document once both are embedded, even if that document genuinely answers the question. Embedding models are not perfect, and small differences in wording can shift a question's position in the embedding space just enough to miss its intended neighbor. So instead of relying on one phrasing, multi-query generates several reworded versions of the same question, each approaching it from a slightly different angle.


Each of these reworded questions is then run through retrieval separately, and the results are pooled together. Even if any single phrasing misses the target document, the chance that at least one of several differently worded variants lands close enough to retrieve it goes up considerably. It is a bit of a shotgun approach: cast the question out in a few different forms, gather everything that comes back, and let that broader net catch documents a single query might have missed. Once that combined set of documents is in hand, the pipeline proceeds with retrieval augmented generation as usual.

Multi-query in code
The query translation code reuses retriever from the indexing section: the blog post split into 300-token chunks and stored in Chroma, returning the default four chunks per query rather than the single chunk of the k=1 example.
from langchain_core.prompts import ChatPromptTemplate
# Multi Query: Different Perspectives
template = """You are an AI language model assistant. Your task is to generate five
different versions of the given user question to retrieve relevant documents from a vector
database. By generating multiple perspectives on the user question, your goal is to help
the user overcome some of the limitations of the distance-based similarity search.
Provide these alternative questions separated by newlines. Original question: {question}"""
prompt_perspectives = ChatPromptTemplate.from_template(template)
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
generate_queries = (
prompt_perspectives
| ChatOpenAI(model="gpt-4o-mini", temperature=0)
| StrOutputParser()
| (lambda x: x.split("\n"))
)generate_queries takes the original question and asks the LLM to produce five reworded variants, then splits the model's output on newlines into a plain list of question strings.
from langchain_core.load import dumps, loads
def get_unique_union(documents: list[list]):
""" Unique union of retrieved docs """
# Flatten list of lists, and convert each Document to string
flattened_docs = [dumps(doc) for sublist in documents for doc in sublist]
# Get unique documents
unique_docs = list(set(flattened_docs))
# Return
return [loads(doc) for doc in unique_docs]
# Retrieve
question = "What is task decomposition for LLM agents?"
retrieval_chain = generate_queries | retriever.map() | get_unique_union
docs = retrieval_chain.invoke({"question":question})
len(docs)retrieval_chain = generate_queries | retriever.map() | get_unique_union is a three-stage pipeline. retriever.map() applies the retriever to every item in the list of questions rather than to a single string. .map() is what makes this fan-out possible: instead of retrieving once for one question, it runs the same retriever independently across all five rewritten questions and returns a list of results per question. The overall output is a list of lists of documents: five separate small sets, one per reworded query. LangChain runs those five retrievals in parallel, on a thread pool.
Since the same document can easily show up in more than one of those five result sets, get_unique_union merges everything into one deduplicated list. It flattens the list of lists into one long list, removes duplicates, and returns a clean list of unique documents. The tricky part is that Document objects are not hashable, so they cannot be put into a Python set() as they are. That is why dumps and loads are used: dumps converts each Document into a JSON string first (strings are hashable, so set() can deduplicate them), and once duplicates are removed, loads converts each surviving string back into a Document.
len(docs) is the total number of distinct documents retrieved across all five rewritten queries combined. It is typically smaller than five times the retriever's usual result count, since different phrasings often surface some of the same chunks.
from operator import itemgetter
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnablePassthrough
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# RAG
template = """Answer the following question based on this context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
final_rag_chain = (
{"context": retrieval_chain | format_docs,
"question": itemgetter("question")}
| prompt
| llm
| StrOutputParser()
)
final_rag_chain.invoke({"question":question})final_rag_chain is where everything comes together into an answer. It starts with a dictionary of two keys. "context" is retrieval_chain | format_docs: the whole multi-query retrieval runs first, and its deduplicated documents are joined into one block of plain text. "question" is pulled straight from the input with itemgetter("question"), unchanged. Both values fill the prompt's {context} and {question} placeholders, the completed prompt goes to the LLM, and StrOutputParser() converts the chat message into a plain string.
The result is a single text answer generated from a broader, deduplicated pool of context, gathered from five different phrasings of the same question.
Filter empty lines
x.split("\n") keeps empty strings when the model leaves blank lines between its questions, and each empty string costs an extra retrieval call. Adding [q for q in x.split("\n") if q.strip()] to the lambda drops them.
RAG Fusion
RAG Fusion builds directly on multi-query and shares the exact same starting point: take the original question, generate a handful of differently worded versions of it, and run retrieval separately for each one. The only thing that changes is what happens after retrieval: how those separate result lists are combined.
In multi-query, the retrieved lists were merged with a simple union: gather every document from every list into one set and drop the duplicates. That plain union treats every retrieved document equally, whether it showed up once at the bottom of a list or repeatedly near the top of several. RAG Fusion replaces it with a smarter combination step called reciprocal rank fusion, or RRF.
The idea behind RRF is that a document's position within each ranked list tells you more about its relevance than any raw similarity score does. Raw scores from different queries are not always directly comparable, since each query produces its own ranking on its own scale, but a document's rank (first, second, third) is directly comparable across different result lists. For every document that shows up in any of the lists, RRF computes a score from how highly it ranked in each list it appeared in, then adds those scores together:
score(doc) = 1/(k + rank in list 1) + 1/(k + rank in list 2) + ...
one term for every list the document appears inA document that lands near the top of several lists ends up with a much higher combined score than one that appears once near the bottom. The result is a single reranked list, where the documents that multiple differently worded queries agreed were highly relevant rise to the top.
So the input side of RAG Fusion, generating alternate phrasings and retrieving for each one, is identical to multi-query. What is new is the ranking step: instead of just deduplicating retrieved documents, RAG Fusion reorders them based on how consistently, and how highly, they showed up across all the searches.
RRF itself predates RAG by more than a decade. Gordon Cormack, Charles Clarke and Stefan Büttcher introduced it at SIGIR 2009, where k = 60 was fixed during a pilot study and found to be near-optimal, though the exact value was not critical. Adrian Raudaschl combined it with LLM-generated queries as RAG Fusion in 2023.
RAG Fusion in code
from langchain_core.prompts import ChatPromptTemplate
# RAG-Fusion: Related
template = """You are a helpful assistant that generates multiple search queries based on a single input query. \n
Generate multiple search queries related to: {question} \n
Output (4 queries):"""
prompt_rag_fusion = ChatPromptTemplate.from_template(template)
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
generate_queries = (
prompt_rag_fusion
| ChatOpenAI(model="gpt-4o-mini", temperature=0)
| StrOutputParser()
| (lambda x: x.split("\n"))
)prompt_rag_fusion asks the model to act as an assistant whose job is to generate multiple search queries related to a single input question, and explicitly asks for four of them this time rather than five. It is structurally the same idea as the multi-query prompt, with one placeholder for the original {question}, but the wording and count are tuned slightly differently.
generate_queries follows the same pattern as before: the prompt is filled with the question, passed to the LLM, and the response is parsed with StrOutputParser() into a plain string. The final step, (lambda x: x.split("\n")), splits that string on newlines, turning one block of text into a list of separate query strings.
from langchain_core.load import dumps, loads
def reciprocal_rank_fusion(results: list[list], k=60):
""" Reciprocal_rank_fusion that takes multiple lists of ranked documents
and an optional parameter k used in the RRF formula """
# Initialize a dictionary to hold fused scores for each unique document
fused_scores = {}
# Iterate through each list of ranked documents
for docs in results:
# Iterate through each document in the list, with its rank (position in the list)
for rank, doc in enumerate(docs):
# Convert the document to a string format to use as a key (assumes documents can be serialized to JSON)
doc_str = dumps(doc)
# If the document is not yet in the fused_scores dictionary, add it with an initial score of 0
if doc_str not in fused_scores:
fused_scores[doc_str] = 0
# Retrieve the current score of the document, if any
previous_score = fused_scores[doc_str]
# Update the score of the document using the RRF formula: 1 / (rank + k)
fused_scores[doc_str] += 1 / (rank + k)
# Sort the documents based on their fused scores in descending order to get the final reranked results
reranked_results = [
(loads(doc), score)
for doc, score in sorted(fused_scores.items(), key=lambda x: x[1], reverse=True)
]
# Return the reranked results as a list of tuples, each containing the document and its fused score
return reranked_results
retrieval_chain_rag_fusion = generate_queries | retriever.map() | reciprocal_rank_fusion
docs = retrieval_chain_rag_fusion.invoke({"question": question})
len(docs)Why you end up with a list of lists. retriever.map() applies the retriever to every query in the list independently. For each of the four generated queries, the retriever runs its own similarity search and returns its own ranked list of matching documents. The output of generate_queries | retriever.map() is therefore a list containing four separate ranked lists, the same shape as in multi-query.
Why reciprocal rank fusion fits. At this point you hold several independently ranked lists that all relate to the same underlying question but came from different phrasings. Pooling them and removing duplicates, as multi-query does, throws away useful information: how highly each document ranked within its own list. RRF is built for exactly this situation, combining multiple ranked lists into a single ranking using each document's position in each list, without requiring the underlying similarity scores to be on the same scale.
Walking through reciprocal_rank_fusion. The function loops over each retrieved list in turn. Within each list, it walks through the documents in order with enumerate, so rank is each document's position: 0 for the top result, 1 for the next, and so on. Since Document objects cannot be used as dictionary keys, each one is converted to a JSON string with dumps, and that string becomes the key in fused_scores. Every time a document is seen in any list, its score increases by 1 / (rank + k), where k (60 here) softens the effect of rank, so the difference between first and second place does not dominate everything. Once every list has been processed, the dictionary is sorted by score from highest to lowest, each string is converted back into a Document with loads, and the function returns (document, score) tuples, ordered from most to least relevant.
Here is that scoring on four illustrative documents, with k = 60, ranks counted from 0 as in the code, and the retriever's default of four results per query:
| Document | Where it was retrieved | Fused score |
|---|---|---|
| B | Third (rank 2) in all four lists | 4 × 1/62 = 0.0645 |
| C | First (rank 0) in two lists | 2 × 1/60 = 0.0333 |
| A | First (rank 0) in one list | 1/60 = 0.0167 |
| D | Fourth (rank 3) in one list | 1/63 = 0.0159 |
Document B never tops a single list, yet it ranks first overall, because every query agreed it was relevant. That consensus is what a plain union cannot see.
len(docs) is the number of distinct documents across all four retrieved lists, the same count as multi-query's union, except that this list is ordered by fused score rather than arbitrarily.
from operator import itemgetter
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnablePassthrough
def format_docs(docs):
return "\n\n".join(doc.page_content for doc, _score in docs)
# RAG
template = """Answer the following question based on this context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
final_rag_chain = (
{"context": retrieval_chain_rag_fusion | format_docs,
"question": itemgetter("question")}
| prompt
| llm
| StrOutputParser()
)
final_rag_chain.invoke({"question":question})final_rag_chain ties everything together. "context": retrieval_chain_rag_fusion | format_docs runs the entire fan-out, retrieve and fuse process, then strips each (document, score) tuple down to its page_content and joins them into one block of text, since the LLM needs only the content, not the internal ranking scores. "question": itemgetter("question") passes the original question through unchanged. Both fill the prompt, the completed prompt goes to the LLM, and StrOutputParser() converts the response into a plain string: an answer built from the documents that reciprocal rank fusion found most consistently relevant across all four phrasings.
Decomposition
Query translation, as a whole, is about reshaping a user's question before it reaches the retriever, so that retrieval has a better shot at finding the right information. Query decomposition is one particular way of doing that: instead of rewording the question, you break it apart into smaller pieces.
Think of it the way you would approach a big, messy task at work. If someone asks you to "plan our company's product launch", you do not tackle that as one giant blob. You split it into smaller, answerable pieces: who is the audience, what is the timeline, what is the budget, who owns each part. You handle each piece on its own, and once you have those answers, the bigger question starts to answer itself. Query decomposition applies the same instinct to a question you hand to an AI system: break a big, hard-to-answer question into a handful of smaller sub-questions that are each easier to answer on their own.
One well-known example comes from Least-to-Most Prompting, a paper by Denny Zhou and colleagues at Google (ICLR 2023). It illustrates the idea with a simple puzzle, last-letter concatenation: given the words "think, machine, learning", take the last letter of each word and string them together. Instead of solving that in one leap, the approach breaks it into a sequence of smaller problems: first "think", then "think, machine", then the full "think, machine, learning". Each smaller problem is solved using the answer to the one before it. Solving "think, machine" means taking the last letter of "think" (k) and the last letter of "machine" (e) and joining them into "ke". To solve the full problem, "ke" is extended with the last letter of "learning" (g), giving the final answer, "keg". It is a bit like climbing a staircase: each step only makes sense once you are standing on the one below it.

A related idea, from IRCoT (Interleaving Retrieval with Chain-of-Thought), a paper by Harsh Trivedi and colleagues at Stony Brook University and the Allen Institute for AI (ACL 2023), takes this a step further by combining it with retrieval. Rather than reasoning through each sub-question using only what the model already knows, the system looks up fresh information relevant to that specific sub-question before answering it, much like a detective working a case: asking one question at a time and gathering new evidence for each, rather than trying to solve everything from a single pile of clues gathered up front. The answer to each sub-question is then carried forward and used as context for the next one. With GPT-3, the paper reports retrieval up to 21 points better and question answering up to 15 points better on four multi-step question answering datasets.

The underlying idea across both papers is the same: answer one sub-question, use what you learned to help answer the next one, and build understanding step by step, rather than expecting a single pass to get you all the way to the answer.
Generating sub-questions in code
from langchain_core.prompts import ChatPromptTemplate
# Decomposition
template = """You are a helpful assistant that generates multiple sub-questions related to an input question. \n
The goal is to break down the input into a set of sub-problems / sub-questions that can be answered in isolation. \n
Generate multiple search queries related to: {question} \n
Output (3 queries):"""
prompt_decomposition = ChatPromptTemplate.from_template(template)
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
# LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Chain
generate_queries_decomposition = (prompt_decomposition | llm | StrOutputParser() | (lambda x: x.split("\n")))
# Run
question = "What are the main components of an LLM-powered autonomous agent system?"
questions = generate_queries_decomposition.invoke({"question": question})
questionsprompt_decomposition instructs the model to take one input question and generate three smaller, self-contained sub-questions that each cover a piece of it, rather than trying to answer the whole thing at once. generate_queries_decomposition runs that prompt through the LLM and splits the response into a list, so questions holds three narrower questions that together cover different angles of the original one: the same spirit as the "think", "think, machine", "think, machine, learning" breakdown, applied to a real question instead of a word puzzle.
There are two ways to answer those sub-questions.
Answering recursively

def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Prompt
template = """Here is the question you need to answer:
\n --- \n {question} \n --- \n
Here is any available background question + answer pairs:
\n --- \n {q_a_pairs} \n --- \n
Here is additional context relevant to the question:
\n --- \n {context} \n --- \n
Use the above context and any background question + answer pairs to answer the question: \n {question}
"""
decomposition_prompt = ChatPromptTemplate.from_template(template)
from operator import itemgetter
def format_qa_pair(question, answer):
"""Format Q and A pair"""
formatted_string = ""
formatted_string += f"Question: {question}\nAnswer: {answer}\n\n"
return formatted_string.strip()
q_a_pairs = ""
for q in questions:
rag_chain = (
{"context": itemgetter("question") | retriever | format_docs,
"question": itemgetter("question"),
"q_a_pairs": itemgetter("q_a_pairs")}
| decomposition_prompt
| llm
| StrOutputParser())
answer = rag_chain.invoke({"question": q, "q_a_pairs": q_a_pairs})
q_a_pair = format_qa_pair(q, answer)
q_a_pairs = q_a_pairs + "\n---\n" + q_a_pair
answerAnswering recursively means each sub-question is answered with the help of everything learned from the ones before it. decomposition_prompt accepts three things at once: the current sub-question, the background question and answer pairs collected so far, and fresh context retrieved specifically for this sub-question.
Inside the loop, each sub-question triggers its own retrieval, its retrieved context is combined with the running history of previous questions and answers, and the model answers with all of that in view. After each answer, format_qa_pair records it and appends it to q_a_pairs, so by the time the next sub-question is answered, the model already has the full trail of everything answered so far. The final answer belongs to the last sub-question, written with all the earlier answers in view. This mirrors the IRCoT idea directly: retrieval happens fresh at each step, and each answer builds on the ones before it rather than starting from scratch.
Answering individually

from langsmith import Client
from langchain_core.runnables import RunnablePassthrough
# RAG prompt
client = Client()
prompt_rag = client.pull_prompt("rlm/rag-prompt", dangerously_pull_public_prompt=True)
def retrieve_and_rag(question, prompt_rag, sub_question_generator_chain):
"""RAG on each sub-question"""
# Use our decomposition chain to generate sub-questions
sub_questions = sub_question_generator_chain.invoke({"question": question})
# Initialize a list to hold RAG chain results
rag_results = []
for sub_question in sub_questions:
# Retrieve documents for each sub-question
retrieved_docs = retriever.invoke(sub_question)
# Use retrieved documents and sub-question in RAG chain
answer = (prompt_rag | llm | StrOutputParser()).invoke({"context": format_docs(retrieved_docs),
"question": sub_question})
rag_results.append(answer)
return rag_results, sub_questions
answers, questions = retrieve_and_rag(question, prompt_rag, generate_queries_decomposition)
def format_qa_pairs(questions, answers):
"""Format Q and A pairs"""
formatted_string = ""
for i, (question, answer) in enumerate(zip(questions, answers), start=1):
formatted_string += f"Question {i}: {question}\nAnswer {i}: {answer}\n\n"
return formatted_string.strip()
context = format_qa_pairs(questions, answers)
# Prompt
template = """Here is a set of Q+A pairs:
{context}
Use these to synthesize an answer to the question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
final_rag_chain = (
prompt
| llm
| StrOutputParser()
)
final_rag_chain.invoke({"context": context, "question": question})This takes a different, simpler approach for comparison: each sub-question is answered completely independently, with its own retrieval and its own answer, and no awareness of the other sub-questions or their answers. retrieve_and_rag loops through the sub-questions, retrieves relevant documents for each one, and produces a standalone answer for each.
Only once every sub-question has been answered does format_qa_pairs gather the question and answer pairs into one block of text. That block becomes the context for a final prompt that asks the model to synthesize everything into a single, coherent answer to the original question. Where the recursive approach threads context through step by step, this approach answers everything separately first and combines the pieces only at the very end.
Step-back prompting
Step-back prompting, another approach from Google researchers, takes the opposite direction from decomposition. Where decomposition breaks a question into smaller, more specific pieces, step-back does the reverse: it takes a specific question and first generates a broader, more general version of it.
A good way to picture this is standing too close to a painting. Right up against the canvas, all you can see are individual brushstrokes, hard to make sense of on their own. Step back a few paces and the whole scene comes into view, which makes it easier to understand what those details were part of in the first place. Step-back prompting applies the same idea to questions. A very specific question can be hard to answer well on its own, especially if the information needed to ground it does not come up easily in a direct search. But if you first ask a broader question about the same topic, the answer to that broader question often supplies background that makes the original, narrower question easier to answer.
The paper, Take a Step Back by Huaixiu Steven Zheng and colleagues at Google DeepMind (ICLR 2024), gets the model to do this through few-shot prompting. Instead of just telling the model to "ask a more general question", it shows the model a handful of worked examples, each pairing a specific question with its broader, step-back version. One example from the paper: a question about which country someone was born in becomes a question about that person's personal history. After seeing a few examples like this, the model picks up the pattern and can generate its own step-back version of a question it has never seen.
In practice, both versions of the question are used. The original, specific question retrieves information as normal, and the new, broader step-back question runs a separate retrieval of its own. Both sets of retrieved information are handed to the model together when it writes the final answer, so the answer benefits from both the precise facts and the broader context that helps make sense of them. In the paper, step-back prompting improved PaLM-2L's performance on MMLU Physics and Chemistry by 7% and 11%, on TimeQA by 27%, and on MuSiQue by 7%.
Step-back prompting in code
# Few Shot Examples
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
examples = [
{
"input": "Could the members of The Police perform lawful arrests?",
"output": "what can the members of The Police do?",
},
{
"input": "Jan Sindel's was born in what country?",
"output": "what is Jan Sindel's personal history?",
},
]
# We now transform these to example messages
example_prompt = ChatPromptTemplate.from_messages(
[
("human", "{input}"),
("ai", "{output}"),
]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"""You are an expert at world knowledge. Your task is to step back and paraphrase a question to a more generic step-back question, which is easier to answer. Here are a few examples:""",
),
# Few shot examples
few_shot_prompt,
# New question
("user", "{question}"),
]
)generate_queries_step_back = prompt | ChatOpenAI(model="gpt-4o-mini", temperature=0) | StrOutputParser()
question = "What is task decomposition for LLM agents?"
generate_queries_step_back.invoke({"question": question})The first part sets up the few-shot examples that teach the model how to step back. examples is a small list of specific-to-generic question pairs, both taken from the paper's appendix: a question about whether the members of The Police can perform lawful arrests becomes a question about what the members of The Police can do in general, and a question about where someone was born becomes a question about their personal history.
example_prompt turns each pair into a mock human and AI exchange, and FewShotChatMessagePromptTemplate stitches them into a block of message history. That block is inserted into the main prompt, right after a system message telling the model its job is to paraphrase a question into a more generic, easier-to-answer version, and right before the placeholder for the real question. So by the time the model sees your question, it has already seen two worked examples of the exact transformation you want. generate_queries_step_back pipes that prompt into the LLM and StrOutputParser(), so invoking it with a question returns the step-back version as plain text.
# Response prompt
response_prompt_template = """You are an expert of world knowledge. I am going to ask you a question. Your response should be comprehensive and not contradicted with the following context if they are relevant. Otherwise, ignore them if they are not relevant.
# {normal_context}
# {step_back_context}
# Original Question: {question}
# Answer:"""
response_prompt = ChatPromptTemplate.from_template(response_prompt_template)
chain = (
{
# Retrieve context using the normal question
"normal_context": RunnableLambda(lambda x: x["question"]) | retriever | format_docs,
# Retrieve context using the step-back question
"step_back_context": generate_queries_step_back | retriever | format_docs,
# Pass on the question
"question": lambda x: x["question"],
}
| response_prompt
| ChatOpenAI(model="gpt-4o-mini", temperature=0)
| StrOutputParser()
)
chain.invoke({"question": question})The second part puts the two versions of the question to work. response_prompt_template takes three inputs: context retrieved for the original question (normal_context), context retrieved for the step-back question (step_back_context), and the question itself. It asks the model to answer comprehensively using both contexts, but only where they are actually relevant.
The chain assembles those three inputs as a dictionary. normal_context runs the original question straight through the retriever. step_back_context runs the question through generate_queries_step_back first, then through the retriever. question is passed along unchanged. The filled prompt goes to the LLM, and the answer comes back as a string, grounded in both the specific and the broader context.
Query translation at a glance
| Technique | What happens to the question | How the results are used |
|---|---|---|
| Multi-query | Rewritten into five versions | The unique union of everything retrieved becomes the context |
| RAG Fusion | Rewritten into four related search queries | The ranked lists are fused with reciprocal rank fusion |
| Decomposition, recursive | Broken into three sub-questions | Each answer feeds the next sub-question |
| Decomposition, individual | Broken into three sub-questions | Answered separately, then synthesized into one answer |
| Step-back prompting | Generalized into one broader question | Context for both questions is given to the model together |
Further reading
- Patrick Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020.
- Gordon Cormack, Charles Clarke and Stefan Büttcher, Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods, SIGIR 2009.
- Denny Zhou et al., Least-to-Most Prompting Enables Complex Reasoning in Large Language Models, ICLR 2023.
- Harsh Trivedi et al., Interleaving Retrieval with Chain-of-Thought Reasoning for Knowledge-Intensive Multi-Step Questions, ACL 2023.
- Huaixiu Steven Zheng et al., Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models, ICLR 2024.
- LangChain, RAG From Scratch: the notebooks and video series this code builds on.
- Kylie: my WhatsApp agent, which stores conversations as embeddings in Qdrant and retrieves them as long-term memory.
- Lilian Weng, LLM Powered Autonomous Agents: the post indexed throughout.