RAG workshop series. I prepared these notebooks for the RAG day of AI Innovation & Product Development, a three-day workshop I ran for final-year B.Tech AI & Data Science students.
- When to use RAG, and when a long context window is enough
- Basic RAG from scratch
- Hybrid search: BM25, embeddings and a reranker
- RAG on real documents: query rewriting, chunking, metadata and Chroma
- Agentic RAG: corrective, adaptive and ReAct
All notebooks: github.com/Zilch123/ai-workshop
Every pipeline so far ran once, in a fixed order: retrieve, then answer. The last notebook of the RAG day turns retrieval into a loop with decisions:
- Corrective RAG (CRAG): check whether the retrieved chunks are relevant. If they aren’t, rewrite the query and try again.
- Adaptive RAG: decide whether a question needs retrieval at all.
- Agentic RAG (ReAct): let the model decide, step by step, whether to search again or answer.
All three reuse the hybrid search and reranker from Part 3, over a slightly bigger corpus: 8 AWS services, now including API Gateway, SNS, CloudWatch and IAM. The LLM is still Llama 3.1 8B Instruct. A small model makes the failures easy to see, which is useful when teaching.
Corrective RAG
First, ask the LLM to grade the retrieval:
def evaluate_retrieval(question, results):
context = "\n\n".join(r["text"] for r in results)
prompt = f"""
You are evaluating whether retrieved documents are useful for answering
a user's question. Even one relevant sentence counts as relevant.
Question:
{question}
Retrieved documents:
{context}
Return ONLY one of these:
RELEVANT
NOT_RELEVANT
"""
response = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": prompt}],
max_tokens=50,
temperature=0,
)
return response.choices[0].message.content.strip()If the grade is NOT_RELEVANT, rewrite the query (the rewriter from Part 4) and search again:
def corrective_rag(question):
results = rerank(question, hybrid_search(question, top_k=5), top_k=3)
if "NOT_RELEVANT" in evaluate_retrieval(question, results):
rewritten = rewrite_query(question)
results = rerank(rewritten, hybrid_search(rewritten, top_k=5), top_k=3)
return resultsOn an in-domain question, “How can I make two services work independently so one doesn’t have to wait for the other?”, the grade was RELEVANT, with SQS first, then API Gateway and Lambda.
On “Why is sky blue?”, the grade was NOT_RELEVANT. It rewrote the query, searched again, and returned… S3, SNS and Lambda.
That’s the gap in this simple version. Rewriting a query can’t find an answer that isn’t in the knowledge base. A full CRAG setup does something else when the grade fails: falls back to web search, or says “I don’t know”. Our version detected the problem correctly and then returned irrelevant chunks anyway. Grading is only useful if a failed grade changes what happens next.
Adaptive RAG: routing
Some questions don’t need retrieval. A router decides before any search happens:
def route_question(question):
prompt = f"""
You are a query router. Our knowledge base contains information about
AWS services, including Amazon S3, Amazon SQS, AWS Lambda, Amazon DynamoDB,
Amazon API Gateway, Amazon SNS, and AWS IAM.
Return ONLY: RAG or DIRECT
Use RAG if the question is about information covered by the knowledge base.
Use DIRECT if the question is unrelated to the knowledge base.
Question:
{question}
"""
...DIRECT questions go straight to the LLM. RAG questions go through hybrid search and reranking first. It routed all four test questions correctly:
| Question | Route |
|---|---|
| What is AWS SQS? | RAG |
| What is the capital of France? | DIRECT |
| How does Lambda handle incoming requests? | RAG |
| What is 25 multiplied by 4? | DIRECT |
One thing I noticed while writing this up: the router’s description of the knowledge base leaves out CloudWatch, even though it’s in the corpus. A CloudWatch question could get routed DIRECT and answered from the model’s memory. The router only knows what you tell it, so generate that description from the corpus instead of typing it by hand.
Agentic RAG: a ReAct loop
ReAct (reason plus act) lets the model choose its next action. Here there are only two actions:
SEARCH: <search query>
ANSWER: <final answer>
The loop runs a search when asked, appends the results to the conversation, and asks again, up to max_steps:
# simplified from the notebook
for step in range(max_steps):
decision = llm(conversation)
if decision.startswith("SEARCH:"):
query = decision.removeprefix("SEARCH:").strip()
results = rerank(query, hybrid_search(query, top_k=5), top_k=3)
conversation += [
{"role": "assistant", "content": decision},
{"role": "user", "content": f"Search results:\n\n{join_chunks(results)}\n\n"
"Decide whether you have enough information. "
"If not, search again."},
]
elif decision.startswith("ANSWER:"):
return decision.removeprefix("ANSWER:").strip()
return "I could not find enough information."First run: it never answered
Question: “How can AWS services communicate asynchronously without requiring one service to wait for another?”
Step 1: SEARCH: asynchronous communication in AWS services
Step 2: SEARCH: AWS services asynchronous communication without waiting for another service
Step 3: SEARCH: AWS services asynchronous communication example
Final Answer: I could not find enough information.
The SQS chunk answers this almost word for word, but the model kept searching, with slightly different queries, until it ran out of steps. “If not, search again” was apparently enough of a hint for an 8B model to keep searching.
Two things saved this run. max_steps is not optional. Without it, this loop would run forever. And the fallback message is honest, not made up.
Second run: it answered, and added things
The second version tightened the prompt (“You may ONLY use facts explicitly stated in the search results”, “Do not search again if the answer can be supported by the results”) and stopped the loop if the model repeated an earlier query:
if query.lower() in [q.lower() for q in previous_queries]:
return "The agent could not find enough information."
previous_queries.append(query)This time it searched once and answered on step 2:
AWS services can communicate asynchronously without requiring one service to wait for another by using Amazon SQS, AWS Lambda, and Amazon API Gateway. Amazon SQS allows producers to send messages to a queue and consumers to process those messages independently, decoupling distributed applications. […] Amazon API Gateway can route incoming HTTP requests to backend services such as AWS Lambda, enabling asynchronous communication between services.
The SQS part is right and comes straight from the chunk. The API Gateway part isn’t. The chunk says it routes HTTP requests to Lambda. “Enabling asynchronous communication” is the model’s own addition, and it went against the prompt that told it not to.
Two lessons from this:
- A grounding instruction in the prompt isn’t a guarantee. If grounding matters, check it: a second LLM call or a citation check that compares each claim against the retrieved text.
- The repeat check only catches exact repeats. The first run’s three queries were all different strings, so this check wouldn’t have stopped them. Near-duplicate queries need a similarity check, or just a small
max_steps.
What the RAG day added up to
Across the five notebooks, the students went from a 20-line retriever to an agent that decides when to search. The habit that ties it all together isn’t any single technique. It’s printing the intermediate steps: the chunks, the scores, the grades, the agent’s decisions. Every surprise in this series (Lambda beating SQS, the question mark in BM25, the agent that never answered) showed up only because the notebooks printed what happened inside.
Day 2 of the workshop moved on to building software with a coding agent, and Day 3 was a hands-on build of a proof-of-concept web app.
Notebook: agentic_RAG.ipynb · Open in Colab
The full RAG day in one notebook: RAG.ipynb, with the outputs from the workshop run.