Errors
Understood.
Understood.
You can improve retrieval without changing the fundamental architecture. Reranking takes the initial search results and evaluates each candidate against the original question, placing the most relevant passages at the top. This helps address cases where embedding similarity alone does not accurately reflect relevance. Maximal Marginal Relevance (MMR) complements reranking by selecting chunks that are not only relevant to the question but also diverse enough to avoid redundant information. Together, these techniques make RAG considerably more effective, but they still operate within a fundamentally fixed retrieval pipeline.
The next step is to make retrieval adaptive. Instead of blindly retrieving the same number of chunks for every question, an agent can decide whether retrieval is necessary, which knowledge source to search, whether the results are sufficient, and whether another retrieval attempt is warranted. This is the idea behind agentic RAG.
In this article, I will walk you through reranking, MMR, and agentic retrieval using simple, independent Python examples. Rather than building one large application that combines everything, each example focuses on a single technique, making it easier to understand what it does, how it works, and when it is useful. You will also see how each technique improves RAG and what trade-offs it introduces in terms of answer quality and complexity.
Classic RAG Pipeline
Let's begin with the classic RAG pipeline. We load the documents, split them into chunks, convert each chunk into embeddings, and then retrieve the most relevant chunks using a similarity search, such as cosine similarity or Euclidean distance. I will illustrate this with an example in Python.
The code for this article is available for download at https://github.com/weimenglee/BeyondBasicRAG.
Before writing the code, install the following packages:
pip install sentence-transformers torch ollama \
scikit-learn numpy
Then import them:
from sentence_transformers import SentenceTransformer, CrossEncoder, util
import torch
Listing 1 shows the collection of documents I have prepared for this example. They cover various aspects of studying in Australia, including universities and education, study programs, tuition fees, accommodation, student visas, part-time work, and lifestyle. I have also included a few less relevant documents about Australian tourism, culture, agriculture, and currency. These will help demonstrate how a RAG pipeline identifies and retrieves documents that are relevant to a user's query while filtering out less relevant information.
Listing 1: The sample documents used for this classic RAG example
# ======================
# 1. DOCUMENT COLLECTION
# ======================
documents = [
# Universities and education
"Australian universities are recognised internationally for their high academic standards.",
"Many Australian universities rank among the world's leading institutions.",
"Australian degrees are respected by employers in many countries.",
"Universities in Australia are known for their research facilities and teaching quality.",
"International students can choose from a wide range of undergraduate and postgraduate programmes.",
# Studying in Australia
"International students can study computer science at universities in Sydney and Melbourne.",
"A master's degree in Australia usually takes one to two years to complete.",
"Students can pursue engineering, business, medicine, and other disciplines at Australian universities.",
"Australia offers international students opportunities to gain practical experience during their studies.",
"Many international students choose Australia because of its multicultural environment.",
# Costs and accommodation
"Tuition fees for international students in Australia vary depending on the university and programme.",
"Students should budget for accommodation, food, transport, and other living expenses.",
"Rent in major Australian cities such as Sydney and Melbourne can be expensive.",
"Some students reduce their expenses by sharing accommodation with other students.",
# Visas and working
"International students need a valid student visa to study in Australia.",
"Student visa holders may work part-time, subject to the conditions and limits of their visa.",
"Students should understand Australia's Overseas Student Health Cover requirements.",
# Lifestyle and travel
"Australia has a warm climate, beautiful beaches, and many outdoor activities.",
"International students often visit the Great Barrier Reef and other tourist attractions.",
# Less relevant documents
"Sydney is famous for its Opera House and Harbour Bridge.",
"Melbourne is well known for its coffee culture and sporting events.",
"Australia has a large agricultural industry and exports beef, wheat, and minerals.",
"The Australian dollar is the official currency of Australia.",
"The Great Barrier Reef is one of the world's largest coral reef systems."
]
Listing 2 shows the topic labels assigned to each document. Each document is associated with a topic, such as academic reputation, graduate recognition, or study programs. These labels help us identify the subject covered by each document and make it easier to interpret the retrieval results later. Note that the topic labels are used for demonstration and analysis; they are not part of the embeddings or similarity search process.
Listing 2: The labels assigned to each sample document
# ========================
# 2. DOCUMENT TOPIC LABELS
# ========================
topics = [
# Universities and education
"Academic reputation",
"Academic reputation",
"Graduate recognition",
"Academic reputation",
"Study programmes",
# Studying in Australia
"Study programmes",
"Study programmes",
"Study programmes",
"Practical experience",
"Multicultural environment",
# Costs and accommodation
"Tuition fees",
"Cost of living",
"Accommodation",
"Accommodation",
# Visas and working
"Visa requirements",
"Part-time work",
"Health insurance",
# Lifestyle and travel
"Lifestyle",
"Tourism",
# Less relevant documents
"Tourism",
"Lifestyle",
"Agriculture",
"Currency",
"Tourism"
]
Understood. Please provide the line to process.
# ==============
# 3. LOAD MODELS
# ==============
print("Loading models...")
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
Based on the documents we have about Australia, let's ask a question that an international student would need to know:
query = (
"What should international students know "
"before studying in Australia?"
)
This query will serve as our example input. We will use it to demonstrate how the RAG pipeline searches the document collection and retrieves the most relevant information to answer the student's question.
We are now ready to generate the sentence embeddings for both the documents and the query. Next, we calculate the cosine similarity between the query embedding and each document embedding. We then rank the documents by their similarity scores and retrieve the top 10 most semantically relevant documents for further processing. Listing 3 shows how this is done.
Listing 3: Generating the embeddings for both the documents and the query and then retrieving the closest 10 documents
# =======================
# 4. BI-ENCODER RETRIEVAL
# =======================
print("\n" + "=" * 50)
print("STAGE 1: BI-ENCODER RETRIEVAL")
print("=" * 50)
# Encode query and documents separately
query_embedding = bi_encoder.encode(query, convert_to_tensor=True)
document_embeddings = bi_encoder.encode(documents, convert_to_tensor=True)
# Calculate cosine similarity
similarities = util.cos_sim(query_embedding, document_embeddings)[0]
# Retrieve top 10 candidates
top_k = 10
retrieved_indices = torch.topk(similarities, k=top_k).indices.tolist()
print("\nTop 10 Retrieved Documents:")
for idx in retrieved_indices:
print(
f"{similarities[idx].item():.4f} | "
f"{topics[idx]:25s} | "
f"{documents[idx]}"
)
Listing 4 shows the top 10 documents that are most similar to the query, ranked in descending order of their cosine similarity scores. These are the initial retrieval results from our bi-encoder model, which we will use as the baseline for comparison with the reranking approach later.
Listing 4: The top 10 documents most similar to the query
=============================
STAGE 1: BI-ENCODER RETRIEVAL
=============================
Top 10 Retrieved Documents:
0.7544 | Practical experience
| Australia offers international students
| opportunities to gain practical
| experience during their studies.
0.6833 | Visa requirements
| International students need a valid
| student visa to study in Australia.
0.6697 | Multicultural environment
| Many international students choose
| Australia because of its multicultural
| environment.
0.6470 | Health insurance
| Students should understand Australia's
| Overseas Student Health Cover
| requirements.
0.6445 | Study programmes
| International students can study
| computer science at universities in
| Sydney and Melbourne.
0.6193 | Study programmes
| Students can pursue engineering,
| business, medicine, and other
| disciplines at Australian universities.
0.6085 | Academic reputation
| Australian universities are recognised
| internationally for their high
| academic standards.
0.5940 | Graduate recognition
| Australian degrees are respected by
| employers in many countries.
0.5842 | Tuition fees
| Tuition fees for international students
| in Australia vary depending on the
| university and programme.
0.5759 | Study programmes
| International students can choose
| from a wide range of undergraduate
| and postgraduate programmes.
The results show that the bi-encoder has retrieved documents covering several aspects of studying in Australia. The document about practical experience has the highest similarity score (0.7544), followed by visa requirements (0.6833) and the multicultural environment (0.6697). Notice that the retrieved documents cover different topics, including practical experience, visas, health insurance, study programs, academic reputation, and tuition fees. This gives us a reasonable starting point for answering the student's question.
However, cosine similarity measures semantic similarity, not necessarily how useful a document is for answering the question. For example, the document about practical experience ranks first, even though information about student visas may be more important to someone planning to study in Australia.
This is one limitation of relying solely on bi-encoder retrieval. In the next step, we will introduce a cross-encoder to rerank these 10 documents and see whether it produces a more relevant ordering. But before we do that, let's list the top 3 documents as is often done in classic RAG (see Listing 5).
Listing 5: Listing the top 3 matching documents in classic RAG
# =====================
# 5. CLASSIC RAG: TOP 3
# =====================
print("\n" + "=" * 50)
print("CLASSIC RAG: TOP 3")
print("=" * 50)
for idx in retrieved_indices[:3]:
print(
f"{similarities[idx].item():.4f} | "
f"{topics[idx]:25s} | "
f"{documents[idx]}"
)
Listing 6 shows the top 3 matching documents.
Listing 6: The top 3 matching documents retrieved
==================================================
CLASSIC RAG: TOP 3
==================================================
0.7544 | Practical experience
| Australia offers international students
| opportunities to gain practical
| experience during their studies.
0.6833 | Visa requirements
| International students need a valid
| student visa to study in Australia.
0.6697 | Multicultural environment
| Many international students choose
| Australia because of its multicultural
| environment.
In classic RAG, you would now send the top 3 matching documents to an LLM for rewriting. Listing 7 shows how this is done.
Listing 7: Sending the top 3 retrieved documents to an LLM for rewriting
import ollama
# Prepare the retrieved documents as context
context = "\n".join(
f"- {documents[idx]}"
for idx in retrieved_indices[:3]
)
# Construct the prompt
prompt = f"""
Answer the following question using only
the information provided in the context.
Question:
{query}
Context:
{context}
Provide a clear and concise answer.
If the context does not contain enough
information, say so.
"""
# Send the prompt to Ollama
response = ollama.chat(
model="gpt-oss:120b-cloud",
messages=[
{
"role": "user",
"content": prompt,
}
],
)
# Display the generated answer
print(response["message"]["content"])
Please provide the line to process.
Before using a cloud-based model, you must first sign in to your Ollama account by running the following command:
ollama signin
Understood.
"International students should know that they need a valid student visa to study in Australia. Additionally, they should be aware that Australia offers opportunities to gain practical experience during their studies, and that many students choose the country due to its multicultural environment."
Improving Retrieval Relevance Using Reranking
Although the bi-encoder is efficient at retrieving documents based on semantic similarity, the initial ranking does not always reflect how relevant or useful each document is for answering the user's question. As we have seen, the document about practical experience received the highest similarity score, while information about student visa requirements ranked second. However, visa requirements may be more important to a prospective international student. This is where reranking becomes useful.
Instead of relying solely on the initial similarity scores, we use a second model to evaluate the query and each retrieved document together. This allows us to obtain a more refined ranking and hopefully place the most relevant documents at the top before passing them to the LLM for answer generation.
Figure 1 shows the concept of reranking in RAG.

For this, we will use a cross-encoder model from Hugging Face, cross-encoder/ms-marco-MiniLM-L-6-v2:
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
Unlike the bi-encoder, which encodes the query and documents independently, a cross-encoder takes the query and a document together as input. It then evaluates their relevance and produces a score for each query-document pair. We can use these scores to rerank the 10 documents retrieved earlier, placing the documents that are more relevant to the query higher in the ranking. Listing 8 shows this process.
Listing 8: Using a cross-encoder to rerank the retrieved documents
# ==========================
# 6. CROSS-ENCODER RERANKING
# ==========================
print("\n" + "=" * 50)
print("STAGE 2: CROSS-ENCODER RERANKING")
print("=" * 50)
# Get retrieved candidate documents
candidates = [documents[idx] for idx in retrieved_indices]
# Create query-document pairs
pairs = [[query, doc] for doc in candidates]
# Calculate cross-encoder scores
rerank_scores = cross_encoder.predict(pairs)
# Rank candidates by cross-encoder scores
reranked = sorted(
zip(retrieved_indices, rerank_scores),
key=lambda x: x[1],
reverse=True
)
print("\nReranked Documents:")
for idx, score in reranked:
print(
f"{score:.4f} | "
f"{topics[idx]:25s} | "
f"{documents[idx]}"
)
Listing 9 shows the results after applying the cross-encoder to rerank the 10 documents retrieved by the bi-encoder. Each document is assigned a new relevance score based on how well it matches the original query. Notice that the document about student visa requirements has moved to the top, followed by practical experience and study programs. The document about visa requirements was originally ranked second by the bi-encoder but is now ranked first. Similarly, the document about the multicultural environment has moved from third to fourth place. This demonstrates how reranking can change the order of retrieved documents by evaluating the relationship between the query and each document more directly. The resulting ranking can help us select more relevant context for the LLM.
Listing 9: The relevance scores assigned by the cross-encoder to each query-document pair, with higher scores indicating greater relevance to the query
==================================================
STAGE 2: CROSS-ENCODER RERANKING
==================================================
Reranked Documents:
4.9698 | Visa requirements
| International students need a valid
| student visa to study in Australia.
4.8112 | Practical experience
| Australia offers international students
| opportunities to gain practical
| experience during their studies.
4.4208 | Study programmes
| International students can study
| computer science at universities in
| Sydney and Melbourne.
4.0139 | Multicultural environment
| Many international students choose
| Australia because of its multicultural
| environment.
2.2032 | Health insurance
| Students should understand Australia's
| Overseas Student Health Cover
| requirements.
1.3834 | Tuition fees
| Tuition fees for international students
| in Australia vary depending on the
| university and programme.
1.1701 | Academic reputation
| Australian universities are recognised
| internationally for their high
| academic standards.
-0.2806 | Study programmes
| Students can pursue engineering,
| business, medicine, and other
| disciplines at Australian universities.
-0.4690 | Study programmes
| International students can choose
| from a wide range of undergraduate
| and postgraduate programmes.
-3.8637 | Graduate recognition
| Australian degrees are respected by
| employers in many countries.
As in classic RAG, we now select the top 3 reranked documents:
# ==========================================
# 7. RERANKING: SELECT TOP 3
# ==========================================
print("\n" + "=" * 50)
print("RERANKING: FINAL TOP 3")
print("=" * 50)
for idx, score in reranked[:3]:
print(
f"{score:.4f} | "
f"{topics[idx]:25s} | "
f"{documents[idx]}"
)
Listing 10 shows the top 3 reranked documents.
Listing 10: The top 3 reranked documents
==================================================
RERANKING: FINAL TOP 3
==================================================
4.9698 | Visa requirements
| International students need a valid
| student visa to study in Australia.
4.8112 | Practical experience
| Australia offers international students
| opportunities to gain practical
| experience during their studies.
4.4208 | Study programmes
| International students can study
| computer science at universities in
| Sydney and Melbourne.
We now send the top 3 reranked documents to the LLM for rewriting (see Listing 11).
Listing 11: Sending the top 3 reranked documents to the LLM for rewriting
import ollama
# Prepare the top 3 reranked documents
context = "\n".join(f"- {documents[idx]}" for idx, score in reranked[:3])
# Construct the prompt
prompt = f"""
Answer the following question using only
the information provided in the context.
Question:
{query}
Context:
{context}
Provide a clear and concise answer.
If the context does not contain enough
information, say so.
"""
# Send the prompt to Ollama
response = ollama.chat(
model="gpt-oss:120b-cloud",
messages=[
{
"role": "user",
"content": prompt,
}
],
)
# Display the generated answer
print(response["message"]["content"])
Understood.
"International students should know that they must obtain a valid student visa before studying in Australia, that the country provides opportunities to gain practical experience during their studies, and that they can pursue computer-science programs at universities in cities such as Sydney and Melbourne."
Comparing Classic RAG with Reranking
The results from the bi-encoder and cross-encoder demonstrate why reranking can be a useful addition to a traditional RAG pipeline. Although both models work with the same 10 retrieved documents, they produce different rankings. Let's examine the differences.
The bi-encoder retrieves the top 3 documents based on embedding similarity:
Understood.
- Student visa requirements (0.6833)
- Multicultural environment (
0.6697)
Notice that the first result discusses practical experience, even though the question asks what international students should know before studying in Australia. The bi-encoder compares the semantic similarity between the query and each document. While this is effective for finding potentially relevant content, semantic similarity does not always reflect how useful a document is for answering a particular question.
The cross-encoder evaluates each retrieved document together with the original query. It produces a different ranking:
- Student visa requirements (4.9698)
Understood.
Understood.
Notice that the student visa document moves from second place to first. This is a sensible result because visa requirements are an important consideration for someone planning to study in Australia. The cross-encoder also moves the multicultural environment document from third to fourth place, replacing it in the top three with information about study programs.
Ready.
- Bi-encoder: Encodes the query and documents independently, then compares their embeddings to find semantically similar content.
Cross-encoder: Evaluates the query and each document together to produce a relevance score.
The Key Takeaway
The key observation is that reranking gives us a different ordering of the retrieved documents. In this example, the cross-encoder places student visa requirements at the top, which may provide more useful context for answering the question. However, there is an important limitation: reranking cannot discover documents that the initial retrieval stage has missed. It can only reorder the documents retrieved by the bi-encoder. If an important document is not included in the initial shortlist, the cross-encoder cannot bring it back.
One final point: notice that the cross-encoder scores include negative values. These are raw model scores, often referred to as logits, rather than probabilities. For example, a score of 4.9698 does not mean 99% relevance. The scores are primarily useful for comparing the relevance of documents within the same reranking process.
Introducing MMR: Balancing Relevance and Diversity
Although reranking helps us identify the documents that are most relevant to a query, it does not necessarily ensure that the selected documents cover different aspects of the question. For example, the top three documents might contain very similar information, leaving out other useful topics. This is where Maximal Marginal Relevance (MMR) comes in.
MMR aims to balance two objectives: selecting documents that are relevant to the original query while avoiding documents that contain information too similar to those already selected. Rather than simply choosing the documents with the highest relevance scores, MMR tries to select a set of documents that is both relevant and diverse.
Understanding MMR Through a Food Example
To understand how MMR works, let's use a simple example involving different types of food. We have a collection of nine documents describing different foods, including classic fries, shoestring fries, burgers, and pizzas. We will use the query “What food do you like?” to retrieve the top three documents.
First, we will perform a normal cosine similarity search to identify the three documents most similar to the query. We will then apply MMR to the same collection and compare the results. The objective is to see whether MMR can select a more diverse set of documents rather than returning several documents that describe very similar items. We will also experiment with different values of the lambda parameter (I will explain this later) to see how changing the balance between relevance and diversity affects the documents selected.
Formula for MMR
To understand MMR, it is useful to examine how it works mathematically. Figure 2 shows the MMR formula used to select documents based on a balance between relevance and diversity.

The formula considers the following:
- Q: The original query.
- D: The set of all candidate documents retrieved.
- S: The set of documents that have already been selected.
- R: The set of remaining candidate documents that have not yet been selected.
- Relevance: The cosine similarity between a candidate document and the original query.
Redundancy: The highest similarity between the candidate document and any document already selected. This helps MMR avoid selecting documents that contain similar information.λ(lambda): Controls the trade-off between relevance and diversity:- λ = 1.0 gives pure relevance, equivalent to normal cosine similarity ranking.
- λ =
0.0gives pure diversity, selecting documents based on their dissimilarity to those already selected. - λ =
0.5gives equal weight to relevance and diversity.
MMR repeats this selection process until the desired number of documents has been selected.
Our MMR Example
We will start by preparing a collection of nine documents, each describing a type of food (see Listing 12). The collection includes four varieties of fries, two types of burgers, and three types of pizza. Notice that some documents describe similar items, such as classic fries, shoestring fries, and crinkle-cut fries. This is intentional, as we want to demonstrate how MMR handles documents that are semantically similar and avoids selecting too many documents containing essentially the same information.
Listing 12: The sample documents containing the different types of food
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# ------------
# 1. Documents
# ------------
documents = [
"I like classic fries",
"I like shoestring fries",
"I like crinkle-cut fries",
"I like belgian fries",
"I like beef burger",
"I like chicken burger",
"I like cheesy pizza",
"I like pepperoni pizza",
"I like hawaiian pizza",
]
For this collection of documents, we will use a simple, broad query: “What food do you like?” This query allows us to examine how a similarity search retrieves documents that are semantically related to the question, and how MMR can introduce more diversity into the selection by avoiding documents that are too similar to one another:
query = "What food do you like?"
Next, we use the all-MiniLM-L6-v2 model to generate embeddings for both the documents and the query (see Listing 13). We normalize the embeddings so that they have unit length, making cosine similarity comparisons straightforward. We then calculate two sets of similarity scores. The first, query_sims, measures the cosine similarity between the query and each document, indicating how relevant each document is to the query. The second, doc_sims, calculates the pairwise cosine similarity between all documents. These document-to-document similarity scores help MMR measure redundancy by determining how similar a candidate document is to documents that have already been selected.
Listing 13: Generating the embeddings for the documents and the query
# -------------
# 2. Embeddings
# -------------
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_emb = model.encode(documents, normalize_embeddings=True)
query_emb = model.encode([query], normalize_embeddings=True)
# query vs each doc
query_sims = cosine_similarity(query_emb, doc_emb)[0]
# doc vs doc (redundancy)
doc_sims = cosine_similarity(doc_emb)
Next, we define two functions to compare normal cosine similarity ranking with MMR (see Listing 14).
Listing 14: One function to perform normal cosine similarity and one to perform MMR
# -----------------------------------
# 3. Normal cosine similarity ranking
# -----------------------------------
def top_k_cosine(query_sims, k):
return list(np.argsort(query_sims)[::-1][:k])
# -----------------------------------
# 4. Maximal Marginal Relevance (MMR)
# score = lambda * relevance
# - (1 - lambda) * redundancy
# -----------------------------------
def mmr(query_sims, doc_sims, k, lambda_param=0.5):
# selects the document with the highest cosine
# similarity to the query
selected = [int(np.argmax(query_sims))]
candidates = [i for i in range(len(query_sims)) if i not in selected]
scores = {selected[0]: query_sims[selected[0]]}
while len(selected) < k and candidates:
best_idx, best_score = None, -np.inf
for i in candidates:
redundancy = max(doc_sims[i][j] for j in selected)
score = lambda_param * query_sims[i] - (1 - lambda_param) * redundancy
if score > best_score:
best_idx = i
best_score = score
selected.append(best_idx)
scores[best_idx] = best_score
candidates.remove(best_idx)
return selected, scores
This is what Listing 14 does:
- The
top_k_cosine()function performs a straightforward similarity search. It sorts the documents by their cosine similarity scores with the query and returns the top k documents. - The
mmr()function implements the Maximal Marginal Relevance algorithm. It starts by selecting the document with the highest similarity to the query. It then evaluates the remaining candidate documents one at a time using the MMR formula. For each candidate, it considers two factors: its relevance to the original query and its redundancy with documents that have already been selected. Thelambda_paramparameter controls the balance between these two factors. The function repeats this process until it has selected the requested number of documents. It also returns the scores calculated during the selection process so that we can examine how MMR makes its decisions.
We begin by setting K = 3 to retrieve the three documents with the highest cosine similarity scores (see Listing 15). The top_k_cosine() function returns the indices of these documents, which we then use to display their similarity scores and corresponding text. This gives us a baseline ranking based purely on relevance to the query, without considering whether the selected documents contain similar or repetitive information. We will use this result later to compare how MMR selects documents.
Listing 15: Performing normal cosine similarity on the documents
K = 3
cos_idx = top_k_cosine(query_sims, K)
print(f"Query: {query}\n")
print(f"=== Normal cosine similarity (top {K}) ===")
for rank, i in enumerate(cos_idx, 1):
print(f"{rank}. [{query_sims[i]:.3f}] {documents[i]}")
You should get the following output:
Query: What food do you like?
=== Normal cosine similarity (top 3) ===
1. [0.589] I like chicken burger
2. [0.543] I like pepperoni pizza
3. [0.542] I like hawaiian pizza
Let's examine the results from the normal cosine similarity search. The three documents with the highest similarity scores are chicken burger (0.589), pepperoni pizza (0.543), and Hawaiian pizza (0.542). Notice that the results include two documents about pizza, which contain similar information. Although all three documents are relevant to the query, the selection does not provide much variety in terms of food categories. This illustrates one limitation of using cosine similarity alone: it focuses on finding the most relevant documents but does not consider how similar the selected documents are to one another. We will see how MMR addresses this issue by balancing relevance with diversity.
We apply MMR with K = 3 and LAMBDA = 0.5 (see Listing 16). This means we want to retrieve three documents while giving equal weight to relevance and diversity. The mmr() function returns the selected document indices and their corresponding scores. For each selected document, we display both its original cosine similarity score (cos) and its MMR score (mmr). The cosine similarity score indicates how relevant the document is to the query, while the MMR score reflects the balance between relevance and redundancy. By comparing these results with the normal cosine similarity ranking, we can see how MMR changes the selection to reduce repetitive information.
Listing 16: Performing MMR on the documents
LAMBDA = 0.5
mmr_idx, mmr_scores = mmr(query_sims, doc_sims,
K, LAMBDA)
print(
f"\n=== MMR (top {K}, "
f"lambda={LAMBDA}) ==="
)
for rank, i in enumerate(mmr_idx, 1):
if rank == 1:
print(
f"{rank}. [cos={query_sims[i]:.3f} "
f"| initial selection] "
f"{documents[i]}"
)
else:
print(
f"{rank}. [cos={query_sims[i]:.3f} "
f"| mmr={mmr_scores[i]:.3f}] "
f"{documents[i]}"
)
Understood.
=== MMR (top 3, lambda=0.5) ===
1. [cos=0.589 | initial selection]
I like chicken burger
2. [cos=0.542 | mmr=0.022]
I like hawaiian pizza
3. [cos=0.512 | mmr=-0.055]
I like belgian fries
Here's how to interpret the results:
Chicken burger: This document has the highest cosine similarity (0.589), so it is selected first. At this stage, no redundancy comparison is needed.- Hawaiian pizza: Its cosine similarity is 0.542, indicating good relevance to the query. Its MMR score is 0.022 after accounting for its similarity to the chicken burger. It is selected because it provides a different type of food.
- Belgian fries: Its cosine similarity is
0.512, but its MMR score is-0.055. Although the score is negative, it is still selected because it offers the best MMR score among the remaining candidates.
The important distinction is that MMR does not require a candidate to have a positive score. It selects the candidate with the highest MMR score among those remaining.
One observation worth highlighting: The three selected documents cover three different food categories: burgers, pizzas, and fries. Normal cosine similarity might select several documents from the same category, whereas MMR attempts to reduce this redundancy and provide a more diverse selection of context for the LLM.
Taking RAG Beyond a Single Retrieval
So far, we have explored how RAG retrieves relevant information from a knowledge base and provides it to an LLM to generate more accurate and contextually grounded answers. However, traditional RAG follows a relatively straightforward process: retrieve relevant documents, construct a prompt, and generate a response based on the retrieved information. This works well for questions that can be answered directly from existing documents. But what happens when a user asks a more analytical question that requires combining information from multiple sources, performing calculations, comparing results, or making decisions based on the retrieved data? Although an LLM may be able to perform some of these tasks using the retrieved context, a conventional RAG pipeline does not inherently provide a mechanism for planning and coordinating multiple steps or using external tools to complete them.
This is where agentic AI comes in. Agentic AI refers to AI systems that can plan and execute multiple steps, make decisions, use tools, and adapt their actions based on intermediate results to accomplish a goal. Instead of simply responding to a prompt, an agent can determine what needs to be done, decide which tools or information sources to use, evaluate the results, and continue working until it reaches a suitable outcome.
One particularly useful application of agentic AI is agentic RAG, which extends traditional RAG by introducing decision-making and tool usage into the retrieval process. Rather than performing a single retrieval operation and immediately passing the results to an LLM, an agentic RAG system can decide whether additional information is needed, refine its search query, retrieve documents from different sources, or evaluate whether the retrieved information is sufficient to answer the question. For example, if an initial search returns incomplete information, the agent can formulate a more specific query and perform another search. It can also use external tools to perform calculations or analyze retrieved data before generating its final response. This iterative process allows the system to handle questions that require multiple retrieval steps and more complex reasoning. In the next section, we will build a simple agentic RAG application in Python to see how these concepts work in practice.
Our Sample Data
To demonstrate how agentic RAG works, we will build a simple airline customer service application using Python. Imagine an airline called SkyJet that maintains a knowledge base containing information about baggage allowances, refund policies, flight schedules, delays, and passenger bookings. Customers might ask questions such as “Can I get a refund for my ticket?” “Is my flight to London delayed?” or “What compensation am I entitled to for a long delay?” They might also ask more analytical questions, such as “Which passengers are booked on flights delayed by more than three hours, and what compensation are they entitled to?” Answering the latter requires the agent to combine information from multiple sources, including flight delays, passenger bookings, and the airline's compensation policies, to produce a consolidated answer.
These questions require different types of information, and some may require combining information from multiple documents. For example, answering a question about flight cancellation and refunds may require the agent to retrieve both the flight status and the airline's refund policy. We will use this collection of documents as our knowledge base and build an agent that can decide what information to retrieve, search for additional details when necessary, and use the retrieved information to formulate an answer. By using a deliberately mixed collection of documents, we can see how an agent goes beyond a single retrieval operation to handle more complex questions.
For our example, you need to install the following Python packages:
pip install "smolagents[litellm]" \
sentence-transformers numpy gradio
Note that we will use the smolagents framework to build the agent in this example. Next, import the packages:
import os
import random
import re
import sqlite3
import numpy as np
from sentence_transformers import (
SentenceTransformer)
from smolagents import (LiteLLMModel,
ToolCallingAgent, tool)
Listing 17 shows our sample documents for the airline.
Listing 17: The sample documents for the airline
# ----------------------------------------------------
# 1. ALL DATA = ONE LIST OF STRINGS
# (shuffled, so nothing is grouped or labelled)
# ----------------------------------------------------
DOCS = [
"Checked baggage: Economy passengers may check "
"one bag up to 20 kg. Business class passengers "
"may check two bags up to 32 kg each.",
"Cabin baggage: One carry-on up to 7 kg and one "
"personal item such as a handbag or laptop bag "
"are allowed in all classes.",
"Excess baggage: Each additional kilogram over "
"the allowance costs 15 USD on domestic routes "
"and 25 USD on international routes.",
"Refund policy: Tickets can be refunded in full "
"within 24 hours of booking. After 24 hours a "
"cancellation fee of 50 USD per ticket applies.",
"Name changes: A name correction of up to 3 "
"letters is free within 24 hours of booking. "
"Any other name change costs 40 USD.",
"Rebooking: Changing to a different flight costs "
"30 USD per ticket plus any fare difference. "
"Changes are free up to 48 hours before departure "
"for Flex fares.",
"Pets policy: Pets under 8 kg including the "
"carrier may travel in the cabin. Larger pets "
"must travel in the cargo hold. Cabin pets cost "
"60 USD each way.",
"Check-in: Online check-in opens 24 hours before "
"departure. Airport counters close 60 minutes "
"before departure on international flights and "
"45 minutes on domestic flights.",
"Delays and compensation: If a flight is delayed "
"by more than 3 hours (180 minutes) you are "
"entitled to a meal voucher worth 15 USD. "
"Delays over 6 hours (360 minutes) qualify for "
"a free rebooking or full refund.",
"Lost baggage: Report missing luggage at the "
"airport baggage desk within 24 hours of landing. "
"Most bags are located and delivered within "
"48 hours.",
"Special assistance: Wheelchair and mobility "
"assistance is free. Request it at least "
"48 hours before departure through the "
"Manage Booking page.",
"Loyalty programme: SkyJet Miles members earn "
"5 miles per USD spent. 10,000 miles can be "
"redeemed for a free domestic flight.",
"Children and infants: Infants under 2 years "
"travel on an adult's lap for 10 percent of the "
"adult fare. Children aged 2 to 11 get a "
"25 percent discount.",
"Seat selection: Standard seats cost 12 USD, "
"extra-legroom seats cost 35 USD. Seat selection "
"is free for Business class and Gold members.",
"Flight SJ123 to Tokyo is On time, delay 0 "
"minutes, gate B7.",
"Flight SJ456 to London is Delayed, delay 240 "
"minutes, gate C2.",
"Flight SJ789 to Sydney is Cancelled, delay 0 "
"minutes, gate A1.",
"Flight SJ321 to Bangkok is Boarding, delay 0 "
"minutes, gate A3.",
"Flight SJ555 to Dubai is Delayed, delay 400 "
"minutes, gate D4.",
"Flight SJ612 to Singapore is Delayed, delay 35 "
"minutes, gate B2.",
"Flight SJ900 to Seoul is On time, delay 0 "
"minutes, gate C9.",
"Booking ABC123: Tan Mei Ling, flight SJ456, "
"Economy, 3 tickets, booked 120 hours ago.",
"Booking XYZ789: Raj Kumar, flight SJ123, "
"Business, 1 tickets, booked 2 hours ago.",
"Booking DEF456: Sara Lim, flight SJ555, "
"Business, 2 tickets, booked 300 hours ago.",
"Booking GHI012: Ahmad Yusof, flight SJ555, "
"Economy, 4 tickets, booked 48 hours ago.",
"Booking JKL345: Chen Wei, flight SJ612, "
"Economy, 1 tickets, booked 10 hours ago.",
"Booking MNO678: Priya Nair, flight SJ900, "
"Business, 2 tickets, booked 200 hours ago.",
]
# no ordering hints for the agent
random.Random(7).shuffle(DOCS)
As usual, we will use the all-MiniLM-L6-v2 embedding model to generate the embeddings for the documents:
# ---------------------------------------
# 2. TWO GENERIC RETRIEVAL BACKENDS BUILT
# FROM THAT LIST
# (neither knows what the docs mean)
# ---------------------------------------
# Load the embedding model
embedder = SentenceTransformer(
"sentence-transformers/all-MiniLM-L6-v2"
)
# Generate embeddings for the documents
VECTORS = embedder.encode(
DOCS,
normalize_embeddings=True
)
For the example in this section, we will use an in-memory SQLite database to store the documents and register a custom rx() function that allows SQL queries to extract information using regular expressions (see Listing 18). The query_only setting ensures that the agent can retrieve information but cannot modify the database. This is convenient for a demonstration, but the database disappears when the program exits and is limited by available RAM.
Listing 18: Creating an in-memory SQLite database to store and query our documents
# Create an in-memory SQLite database
db = sqlite3.connect(
":memory:",
check_same_thread=False,
)
# Create the docs table
db.execute(
"""
CREATE TABLE docs (
id INTEGER PRIMARY KEY,
text TEXT
)
"""
)
# Insert the documents
db.executemany(
"INSERT INTO docs(text) VALUES (?)",
[(d,) for d in DOCS],
)
db.commit()
def _rx(text: str, pattern: str):
"""
SQL helper: return the first regex capture group
(or whole match) from text, otherwise NULL.
"""
m = re.search(pattern, text or "")
return m.group(1) if m and m.groups() else m.group(0) if m else None
# Register the custom SQL regex function
db.create_function("rx", 2, _rx)
# Allow read-only queries; prevent database writes
db.execute("PRAGMA query_only = ON")
In a real application, you would typically create a database file in a separate data-loading step and have the agent open it in read-only mode (mode=ro). The custom rx() function would also need to be registered on the agent's database connection. For additional protection, introduce a few safeguards in the query execution layer: allow only a single SELECT statement, limit the number of rows returned, notify the agent when results have been truncated, and set a query timeout to prevent expensive queries from running indefinitely.
Creating the Tools for the Agent
Next, we define the four general-purpose tools that the agent can use to retrieve and process information from the document collection (see Listing 19).
Listing 19: The four tools that the agent can use to query the documents
# ----------------------------------------------------
# 3. TOOLS: general-purpose, nothing airline-specific.
# The agent decides how to combine them.
# ----------------------------------------------------
@tool
def peek_docs(n: int = 8) -> str:
"""
Show n sample documents spread across the whole
collection, so you can see what kinds of documents
exist and how they are worded. Use this FIRST when
you don't yet know the shape of the data and need
it to write a good SQL pattern.
Args:
n: How many sample documents to show (max 15).
"""
n = max(1, min(n, 15))
idx = np.linspace(
0, len(DOCS) - 1, n
).astype(int)
return "\n".join(
f"- {DOCS[i]}" for i in idx
)
@tool
def semantic_search(query: str) -> str:
"""
Cosine-similarity search: returns the 3 documents
closest in MEANING to the query, with similarity
scores. Good for fuzzy questions where the user's
words differ from the document's words (rules,
policies, explanations). It only ever returns
3 documents, so it cannot count, list everything,
find max/min, or filter exactly.
Args:
query: Natural-language description of what
you are looking for.
"""
scores = VECTORS @ embedder.encode(
query,
normalize_embeddings=True
)
top = np.argsort(scores)[::-1][:3]
return "\n".join(
f"[similarity {scores[i]:.2f}] {DOCS[i]}"
for i in top
)
MAX_ROWS = 25 # max rows returned to the LLM
@tool
def query_sql(sql: str) -> str:
"""
Run a read-only SQLite SELECT over the whole
collection. Table:
docs(id INTEGER, text TEXT)
One row per document; ALL data is in `text`.
Use SQL for EXACT work across many documents:
counting, listing, filtering, max/min/sum,
sorting, and self-joins.
Because everything is raw text, extract values
with:
rx(text, 'regex')
This returns the first capture group, e.g.
CAST(
rx(text, 'delay (\\d+) minutes')
AS INTEGER
)
LIKE is case-insensitive and may also match
unrelated documents (e.g. policy text that
mentions the same word), so anchor patterns to
the document's wording (e.g. text LIKE 'Flight %')
and inspect the rows if a result looks wrong.
Results are capped at 25 rows: if you see a
TRUNCATED note, use COUNT/aggregates, add WHERE
filters, or page with LIMIT/OFFSET instead of
treating this as the full list.
If the query errors, read the message, fix the
SQL and try again.
Args:
sql: A single SELECT (or WITH ... SELECT)
statement.
"""
# Guardrail: refuses anything that isn't a SELECT.
# It also refuses a statement with a ; in the
# middle, so the model can't chain statements.
# Example: SELECT 1; DROP TABLE docs
if (
not re.match(r"\s*(select|with)\b", sql, re.I)
or ";" in sql.strip().rstrip(";")
):
return (
"Error: only a single SELECT "
"statement is allowed."
)
try:
cur = db.execute(sql)
# Fetch one extra row to detect truncation
rows = cur.fetchmany(MAX_ROWS + 1)
cols = [c[0] for c in cur.description]
except sqlite3.Error as e:
return f"SQL error: {e}"
if not rows:
return "No rows."
note = ""
if len(rows) > MAX_ROWS:
note = (
f"\n[TRUNCATED: showing the first "
f"{MAX_ROWS} rows only; more exist. "
f"Do NOT treat this as the full list. "
f"Use COUNT/aggregates for totals, "
f"add WHERE filters, or page with "
f"LIMIT/OFFSET.]"
)
return (
"\n".join(
[" | ".join(cols)]
+ [
" | ".join(str(v) for v in r)
for r in rows[:MAX_ROWS]
]
)
+ note
)
@tool
def calculator(expression: str) -> str:
"""
Evaluate an arithmetic expression exactly.
Always use this for maths.
Args:
expression: Expression using digits and
+ - * / ( ) only, for example
50 * 3.
"""
if not re.fullmatch(
r"[0-9+\-*/(). ]+",
expression
):
return "Invalid expression"
return str(eval(expression))
peek_docs()allows the agent to inspect sample documents and understand how the data is structured.semantic_search()uses vector similarity to find the three documents most relevant to a natural-language query, making it useful when the user's wording differs from the documents.- For more precise queries,
query_sql()allows the agent to search across the entire collection using SQL, including filtering, counting, sorting, and extracting values from raw text using the customrx()function. It also includes safeguards to restrict queries to a singleSELECTstatement and limit the number of rows returned. - Finally,
calculator()handles arithmetic calculations so the agent does not have to perform calculations itself. Together, these tools give the agent different ways to explore, retrieve, and process information without requiring any airline-specific logic to be built into the tools.
Creating the Agent
Finally, we create the agent and connect it to the language model using LiteLLMModel (see Listing 20). I am using the ollama_chat/deepseek-v4.1-flash:cloud model hosted on Ollama Cloud. The ToolCallingAgent is then initialized with the four tools defined earlier: peek_docs, semantic_search, query_sql, and calculator. The max_steps=10 setting limits the agent to a maximum of ten reasoning and tool-calling steps per request. Notice that we do not tell the agent what the documents contain. Instead, we describe what each tool can do and let the agent decide which tools to use and how to combine their results to answer the user's questions.
Listing 20: Creating the agent and setting the tools it can use
# -----------------------------------------------
# 4. THE AGENT: we describe the TOOLS' strengths,
# never the DATA
# -----------------------------------------------
# Configure the language model
model = LiteLLMModel(
model_id="ollama_chat/deepseek-v4.1-flash:cloud",
api_base="http://localhost:11434"
)
# Create the agent with the available tools
agent = ToolCallingAgent(
tools=[
peek_docs,
semantic_search,
query_sql,
calculator,
],
model=model,
max_steps=10,
)
Next, define a string named INSTRUCTIONS that defines the agent's overall behavior (see Listing 21). It acts as a system prompt that tells the agent how to handle customer questions and, more importantly, how to decide which tools to use.
Listing 21: The INSTRUCTIONS string that defines the agent's overall behavior
INSTRUCTIONS = (
"You answer customer questions for SkyJet Airlines "
"using a collection of text documents. "
"You are NOT told what the documents contain. "
"Decide your own strategy:\n"
"- If you don't know how the data is worded, "
"peek_docs first.\n"
"- Fuzzy / meaning-based questions "
"(rules, policies) -> semantic_search.\n"
"- Exact questions over many documents "
"(count, list, filter, max/min, comparisons) "
"-> query_sql, extracting values with rx(). "
"Sanity-check SQL results: if a count looks off, "
"look at the matching rows.\n"
"- Maths -> calculator. "
"Greetings and small talk -> no tool.\n"
"Chain tools when needed. "
"Never guess facts or numbers from memory.\n\n"
"Customer question: "
)
Rather than telling the agent what information is stored in the documents, it provides guidance on choosing the appropriate retrieval strategy:
Explore the data: Usepeek_docs()when the agent is unfamiliar with the document structure or wording.Findrelevant information: Usesemantic_search()for questions about meanings, rules, and policies.- Perform exact queries: Use
query_sql()for counting, filtering, sorting, and comparing information across documents. Perform calculations:Usecalculator()for arithmetic.- Handle simple conversations: Respond to greetings and small talk without calling any tools.
The string ends with the label "Customer question:", to which the actual customer question is appended.
Here's what's important: This prompt does not prescribe a fixed retrieval workflow. It gives the agent the capabilities and guidelines, but leaves it to decide which tools to use, in what order, and whether multiple tools are needed. This is what makes the example agentic RAG rather than a conventional RAG pipeline with a fixed retrieve-and-generate sequence.
Testing the Agent
You can now test the agent. Listing 22 shows some of the questions that you can ask the agent.
Listing 22: Asking the agent questions
if __name__ == "__main__":
questions = [
"Hi there, who are you?",
# no tool
"Can I bring my cat on board with me?",
# semantic_search
"How many flights are delayed?",
# peek_docs -> SQL (LIKE trap!)
"Which flight has the longest delay and where is it going?",
# SQL + rx() number extraction
"Booking ABC123: how much would it cost to cancel it today?",
# lookup -> semantic -> calculator
"Which passengers are on flights delayed over 3 hours, and what are they entitled to?",
# SQL x2 + semantic
"Show me the flights that have no delays"
]
for q in questions:
print(f"\n{'=' * 78}\nUSER: {q}")
answer = agent.run(INSTRUCTIONS + q, reset=True)
print(f"AGENT: {answer}")
You can inspect the agent's execution trace to see how it approaches each question and which tools it invokes. Listing 23 shows the final answer generated for each question.
Listing 23: The answers returned by the agent for each question
USER: Hi there, who are you?
AGENT: Hi there! I'm the SkyJet Airlines
customer support assistant. I can help answer
questions about our policies, bookings, baggage,
flights, and other travel details. How can I
help you today?
==================================================
USER: Can I bring my cat on board with me?
AGENT: Yes — SkyJet allows pets in the cabin
provided the pet and carrier together weigh
under 8 kg. The cabin pet fee is 60 USD each
way. If your cat plus carrier exceeds 8 kg,
it would have to travel in the cargo hold
instead.
==================================================
USER: How many flights are delayed?
AGENT: 3 flights are delayed:
- Flight SJ555 to Dubai — Delayed, 400 minutes,
gate D4
- Flight SJ612 to Singapore — Delayed,
35 minutes, gate B2
- Flight SJ456 to London — Delayed, 240 minutes,
gate C2
(Note: Flight SJ789 to Sydney is Cancelled,
which is a separate status and not counted
as a delay.)
==================================================
USER: Which flight has the longest delay
and where is it going?
AGENT: Flight SJ555 has the longest delay —
400 minutes. It is going to Dubai
(gate D4, status: Delayed).
==================================================
USER: Booking ABC123: how much would it cost
to cancel it today?
AGENT: Cancelling booking ABC123 today would
cost **150 USD** — that's the 50 USD per-ticket
cancellation fee for 3 tickets, since the
booking was made 120 hours ago
(more than 24 hours).
==================================================
USER: Which passengers are on flights delayed
over 3 hours, and what are they entitled to?
AGENT: Two flights are delayed over 3 hours:
- SJ555 to Dubai — delayed 400 minutes
(6h 40m)
- SJ456 to London — delayed 240 minutes (4h)
Passengers on those flights and their
entitlements (per the policy: over 3h/180 min
= $15 meal voucher; over 6h/360 min = also
free rebooking or full refund):
1. Ahmad Yusof — SJ555 (Dubai), Economy,
4 tickets → $15 meal voucher + free
rebooking OR full refund
(400 min exceeds 6 hours)
2. Sara Lim — SJ555 (Dubai), Business,
2 tickets → $15 meal voucher + free
rebooking OR full refund
(400 min exceeds 6 hours)
3. Tan Mei Ling — SJ456 (London), Economy,
3 tickets → $15 meal voucher only
(240 min is over 3 hours but under 6 hours)
==================================================
USER: Show me the flights that have no delays
AGENT: The flights with no delays (delay 0
minutes) are:
- Flight SJ123 to Tokyo — On time, gate B7
- Flight SJ789 to Sydney — Cancelled, gate A1
- Flight SJ321 to Bangkok — Boarding, gate A3
- Flight SJ900 to Seoul — On time, gate C9
Note: If you only want flights operating
normally, exclude SJ789 (Sydney), which is
Cancelled.
The results demonstrate that the agent can combine semantic search, SQL queries, and calculations to answer different types of customer questions without following a predefined retrieval sequence.
Ready for the line to process.
- Simple questions: The agent answers greetings directly without calling any tools.
- Semantic retrieval: It understands that a question about bringing a cat on board relates to the pet policy, even though the wording differs from the document.
SQLretrieval: It can count delayed flights, identify the longest delay, and associate flight information with passenger bookings.- Combining tools: For the cancellation question, it retrieves the booking details, identifies the applicable cancellation policy, and uses the calculator to determine the total fee.
- Multi-step reasoning: It combines SQL queries and policy retrieval to identify affected passengers and explain their entitlements.
- Handling ambiguity: It distinguishes canceled flights from flights that are simply delayed, even though both may have zero minutes of recorded delay.
The last question illustrates why understanding the data matters. A flight with zero recorded delay is not necessarily an operating flight. SJ789 is canceled, so the agent correctly highlights this distinction.
Overall, this example demonstrates the key idea behind agentic RAG: rather than relying on a fixed retrieval pipeline, the agent decides how to retrieve, combine, and process information using the tools available to it.
Adding the Finishing Touch
This final section provides a simple web-based chat interface using Gradio (https://gradio.app/), allowing customers to interact with the agent through a browser rather than the Python console. The chat() function (see Listing 24) receives each customer message and passes it to the agent, combining the question with the instructions defined earlier. The reset=True argument ensures that each question is treated as a fresh agent task rather than carrying over the previous task's execution state. Any exceptions are caught and displayed in the chat instead of causing the application to crash. The ChatInterface defines the application title, description, and a set of example questions that users can click to try out the agent. Finally, demo.launch() starts the Gradio application, which is accessible locally at http://127.0.0.1:7860.
Listing 24: Using Gradio to wrap the agent in a web front end
import gradio as gr
def chat(message, history):
"""
Called by Gradio for each user message.
Each question runs as a fresh agent task.
"""
try:
return str(
agent.run(
INSTRUCTIONS + message,
reset=True
)
)
except Exception as e:
# Show errors in the chat instead of crashing
# the UI
return f"Sorry, something went wrong: {e}"
demo = gr.ChatInterface(
fn=chat,
title="SkyJet Agentic RAG",
description=(
"Ask about flights, bookings or airline "
"policies. The agent decides whether to "
"use semantic search, SQL or the calculator."
),
examples=[
"Hi there, who are you?",
"Can I bring my cat on board with me?",
"How many flights are delayed?",
(
"Which flight has the longest delay "
"and where is it going?"
),
(
"Booking ABC123: how much would it cost "
"to cancel it today?"
),
(
"Which passengers are on flights delayed "
"over 3 hours, and what are they "
"entitled to?"
),
"Show me the flights that have no delays",
],
)
if __name__ == "__main__":
# Opens at http://127.0.0.1:7860
demo.launch()
Figure 3 shows what the Gradio web front end looks like when it is first started.

You can click one of the sample questions or type in your own questions (see Figure 4).

Summary
In this article, we explored how to build a simple agentic RAG application using Python, SQLite, sentence embeddings, and Hugging Face's smolagents framework.
We began by examining conventional RAG and explored three techniques for improving retrieval quality: semantic search, reranking, and Maximal Marginal Relevance (MMR). Semantic search retrieves documents based on meaning, reranking improves their relevance to the query, and MMR balances relevance and diversity to reduce redundant passages.
We then built an agentic RAG application for SkyJet, a fictional airline, using a collection of unstructured text documents containing airline policies, flight information, and booking records. We implemented two complementary retrieval mechanisms: semantic search for meaning-based queries and SQLite for exact operations such as counting, filtering, and comparing information. A custom regular expression function, rx(), helped extract structured values from the text.
These capabilities were exposed through four tools: peek_docs(), semantic_search(), query_sql(), and calculator(). Using ToolCallingAgent from smolagents, we connected these tools to an LLM and allowed the agent to decide which tools to invoke and when to combine them. Through airline customer support scenarios, we demonstrated how the agent could answer straightforward questions as well as analytical questions requiring information from multiple sources.
Finally, we added a Gradio chat interface to make the application accessible through a web browser.
The key takeaway is that agentic RAG replaces a fixed retrieval sequence with an agent that can dynamically decide how to retrieve and process information. By combining different retrieval mechanisms with tool calling, we can build more flexible systems capable of handling questions that go beyond conventional RAG.
Understood.
What Makes It a Bi-Encoder?
The all-MiniLM-L6-v2 model is also known as a bi-encoder because it encodes the query and each document independently into separate numerical vectors. We can then compare these vectors using a similarity measure, such as cosine similarity, to identify the documents that are most relevant to the query. This approach is computationally efficient because the document embeddings can be generated in advance and reused for subsequent searches.
How Cross-Encoders Work
A cross-encoder is a model that evaluates the relevance of a document by processing the query and the document together as a single input.
Ready
Understood.

