22. Agentic RAG — Revision Guide#
Overview: This guide distills how to build a multi-agent Retrieval-Augmented Generation (RAG) system using CrewAI and DeepSeek (via OpenRouter in the cloud or Ollama locally). Starting from plain RAG, it builds up to an agentic team that routes questions between a private PDF and the live web, checks its own answers for relevance and hallucinations, and falls back to web search whenever a check fails.
Big Picture: End-to-End Architecture#
Revision Notes#
Think of the system as a metro network. A user's question enters at the Router junction and takes either the library line (the private PDF) or the web line (the live internet). Two inspectors (the graders) audit the retrieved answer before it reaches the user. If either check fails, a fallback line triggers a fresh web search.
- System footprint: 5 specialist agents, 5 sequential tasks, 2 tools (
rag_toolandweb_search_tool), and 2 LLMs (a reasoning orchestrator + a fast RAG summarizer) running inside one CrewAI Crew.
The Router dispatches questions semantically between the local ChromaDB PDF index and live Tavily web search, while Answer and Hallucination Graders audit relevance and faithfulness before synthesis or web fallback.
Code Reference#
import os
import sys
import time
import urllib.request
from datetime import datetime
from crewai import Crew, Process
import config
from agents import (
create_answer_generator_agent,
create_answer_grader_agent,
create_hallucination_grader_agent,
create_retriever_agent,
create_router_agent,
)
from llms import clean_text
from tasks import (
create_answer_task,
create_grader_task,
create_hallucination_task,
create_retriever_task,
create_router_task,
)
from tools import create_rag_tool, web_search_tool
DEFAULT_QUESTION = "What is the self-attention mechanism in Transformers?"
def download_pdf(url: str, save_path: str) -> None:
"""Download the PDF only if we don't already have it."""
# Idempotent cache check: avoids re-downloading and re-indexing the PDF on every run
if os.path.exists(save_path):
print(f"PDF already present: {save_path}")
return
os.makedirs(os.path.dirname(save_path) or ".", exist_ok=True)
print(f"Downloading PDF from {url} ...")
# arXiv and several academic hosts reject default Python urllib User-Agents with 403
request = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(request, timeout=60) as response, open(save_path, "wb") as f:
f.write(response.read())
print(f"Saved to {save_path}")
def build_crew() -> Crew:
# ---- 1. TOOLS ---------------------------------------------------------
# Build (or load from disk) the local vector index before wiring agents so the
# Retriever agent can invoke it as a CrewAI tool during execution.
rag_tool = create_rag_tool(config.PDF_PATH) # builds the vector DB (indexing)
# ---- 2. AGENTS --------------------------------------------------------
# Five single-responsibility agents separate routing, retrieval, relevance grading,
# hallucination checking, and final synthesis so each step can be audited independently.
router = create_router_agent()
retriever = create_retriever_agent()
grader = create_answer_grader_agent()
hallucination_grader = create_hallucination_grader_agent()
answer_generator = create_answer_generator_agent()
# ---- 3. TASKS (each one can read the output of the ones before it) ----
# Explicit `context` dependencies form a deterministic pipeline:
# Router decides PDF vs. web -> Retriever fetches evidence using the chosen tool ->
# Grader checks chunk relevance -> Hallucination Grader verifies faithfulness against
# both the retrieved context and the grader's verdict before final answer synthesis.
router_task = create_router_task(router)
# -> Task output: "vectorstore" | "websearch" (here -> "vectorstore")
retriever_task = create_retriever_task(retriever, router_task, rag_tool, web_search_tool)
# -> Task output: "SOURCE: document\n..." + 4 retrieved PDF chunks
grader_task = create_grader_task(grader, retriever_task)
# -> Task output: "yes" | "no" (here -> "yes", chunks define self-attention)
hallucination_task = create_hallucination_task(hallucination_grader, retriever_task, grader_task)
# -> Task output: "yes" | "no" (here -> "yes", claims grounded in chunks)
# ... (see full file: main.py)
$ python main.py "What is the self-attention mechanism in Transformers?"
PDF already present: data/attention_is_all_you_need.pdf
[Router Agent] Decision: vectorstore (question matches Transformer paper scope)
[Retriever Agent] Called rag_tool -> retrieved 4 relevant chunks from PDF
[Answer Grader] Verdict: YES (chunks directly define scaled dot-product self-attention)
[Hallucination Check] Verdict: YES (every claim is grounded in retrieved chunks)
======================================================================
QUESTION : What is the self-attention mechanism in Transformers?
ANSWER : Self-attention relates different positions of a single sequence
to compute a representation of the sequence. For each token,
the model projects its embedding into Query (Q), Key (K), and
Value (V) vectors, computes scaled dot products QK^T / sqrt(d_k),
applies softmax to obtain attention weights, and produces a
weighted sum of the Values.
ROUTE : vectorstore
TIME : 8.4 seconds (5 agent steps)
======================================================================
Why RAG Exists#
Revision Notes#
Concept#
An LLM trained on public text knows broad domains (finance, Python, Transformers) but has never seen your private documents (internal reports, HR policies, contracts, class notes). When asked about private material, it either refuses or hallucinates—confidently inventing plausible-sounding falsehoods.
RAG (Retrieval-Augmented Generation) solves this without retraining or fine-tuning. Read the acronym backwards:
- Generation: The LLM writes an answer.
- Augmented: First, we inject relevant external context into its prompt.
- Retrieval: That context is fetched dynamically from our own document store.
Key Mental Models#
- Open-book exam: The LLM already knows how to reason and write, but performs far better when handed the textbook opened to the exact right page.
- Why not paste the entire PDF into the prompt? Long documents (hundreds of pages) are slow, expensive, noisy, and often exceed the model's context window. RAG sends only the few most relevant excerpts.
Traditional RAG: Two-Phase Pipeline#
Revision Notes#
Concept#
Plain RAG splits into two phases: index the library once, then retrieve and generate for every incoming question.
Phase 1: Indexing (Done Once)#
- Load: Ingest documents (PDFs, Word files, web pages, text). This project uses Attention Is All You Need (the original Transformer paper).
- Split into chunks: Break text into small pieces (roughly 1,000–2,000 characters) with overlap between neighboring chunks so sentences cut across boundaries are not lost.
- Embed (text to numbers): Pass each chunk through an embedding model (
BAAI/bge-small-en-v1.5, producing 384 numbers per chunk). Texts with similar meaning map to nearby vectors even when phrased differently (e.g., "How do I cancel my order?" and "Steps to stop a purchase"). This enables semantic search—searching by meaning rather than exact keywords. - Store in a vector database: Save each vector alongside its original text in ChromaDB, which persists locally to disk so indexing only runs once.
Phase 2: Retrieval + Generation (Per Question)#
- Embed the question using the exact same embedding model.
- Similarity search: Query ChromaDB for the top-k closest chunks (
TOP_K=4). - Prompt & generate: Pass the question and retrieved chunks to the LLM to synthesize an answer.
Trade-Offs & Pitfalls#
- Chunk size trade-off: Smaller chunks yield sharper retrieval precision but carry less surrounding context; larger chunks carry more context but introduce more noise.
- Unbreakable embedding rule: Always embed documents and queries with the same embedding model. Different models produce incompatible vector spaces, making similarity distances meaningless.
- Why a vector DB instead of SQL? Text is broken into tokens and represented as high-dimensional vectors (384 numbers per chunk here). SQL excels at exact lookups ("find customer 42") but is poorly suited for finding the 4 nearest neighbors in 384-dimensional space; vector databases are purpose-built and indexed for similarity search.
- Bridge to Agentic RAG: In the agentic architecture, this entire traditional RAG pipeline is wrapped inside a single callable tool (
rag_tool).
Code Reference#
import sys
import time
import config
from llms import clean_text, get_rag_llm
from main import download_pdf
from tools import RAG_PROMPT, create_pdf_search_tool
def plain_rag(question: str) -> str:
# 1. INDEXING (only slow the first time; the vectors are saved on disk)
# Reuses the persisted Chroma/embedding store so repeated queries skip chunking & embedding.
library = create_pdf_search_tool(config.PDF_PATH)
# 2. RETRIEVAL: get the top-k most similar chunks
# Plain RAG always searches the local PDF blindly—there is no Router to detect out-of-scope
# questions and no Grader to discard irrelevant chunks before generation.
chunks = library.run(query=question)
# -> "3.2.2 Multi-Head Attention\nInstead of performing a single attention..." (top-4)
print("\n----- CHUNKS FOUND (first 600 characters) -----")
print(chunks[:600], "...")
# 3. GENERATION: one LLM call with question + chunks
# Uses the fast RAG helper LLM (e.g. Groq) and strips any <think>...</think> reasoning tags
# via clean_text() so downstream checks like "NOT_FOUND_IN_DOCUMENT" match reliably.
llm = get_rag_llm()
answer = clean_text(llm.call(RAG_PROMPT.format(context=chunks, question=question)))
# -> "Multi-head attention linearly projects queries, keys, and values h times..."
return answer
if __name__ == "__main__":
# Fail fast before downloading or indexing if Groq mode is selected without credentials
if config.RAG_LLM_MODE == "groq" and not config.GROQ_API_KEY:
sys.exit("GROQ_API_KEY is empty. Add it to .env, or set RAG_LLM_MODE=same.")
question = " ".join(sys.argv[1:]).strip() or "What is multi-head attention?"
download_pdf(config.PDF_URL, config.PDF_PATH)
start = time.time()
answer = plain_rag(question)
print("\n" + "=" * 70)
print("QUESTION :", question)
print("ANSWER :", answer)
print(f"TIME : {time.time() - start:.1f} seconds (1 LLM call)")
print("=" * 70)
# Sentinel string instructed by RAG_PROMPT when retrieved chunks do not contain the answer;
# demonstrates the exact limitation that Agentic RAG (main.py) solves via web-search fallback.
if "NOT_FOUND_IN_DOCUMENT" in answer:
print("Plain RAG had nowhere else to look. Agentic RAG (main.py) would\n"
"route this question to the web instead.")
$ python step1_plain_rag.py "What is multi-head attention?"
PDF already present: data/attention_is_all_you_need.pdf
----- CHUNKS FOUND (first 600 characters) -----
3.2.2 Multi-Head Attention
Instead of performing a single attention function with d_model-dimensional keys,
values and queries, we found it beneficial to linearly project the queries, keys
and values h times with different, learned linear projections to d_k, d_k and d_v
dimensions, respectively. On each of these projected versions of queries, keys and
values we then perform the attention function in parallel, yielding d_v-dimensional
output values. These are concatenated and once again projected, resulting in the
final values... ...
======================================================================
QUESTION : What is multi-head attention?
ANSWER : Multi-head attention linearly projects queries, keys, and values
h times in parallel (h = 8 in the paper), runs scaled dot-product
attention on each projection so the model can attend to different
representation subspaces simultaneously, then concatenates and
projects the outputs back to d_model dimensions.
TIME : 1.3 seconds (1 LLM call)
======================================================================
Where Plain RAG Struggles vs. Agentic RAG#
Revision Notes#
Concept#
Plain RAG executes the same fixed pipeline on every query, even when that path makes no sense. In the baseline script (step1_plain_rag.py), a single LLM call answers PDF questions well ("What is multi-head attention?") but hits a dead end (NOT_FOUND_IN_DOCUMENT) on live questions ("What is the weather in Delhi today?") because it has nowhere else to look.
Four Failure Modes of Plain RAG#
- Retrieval misses: The top-k chunks are only loosely related, causing the LLM to answer from the wrong material.
- Blind document lookup: Every query—even live weather or news—still searches the static PDF and produces a poor or empty answer.
- Residual hallucination: RAG drastically reduces fabrication, yet the LLM can still sneak in facts unsupported by the retrieved chunks.
- Zero verification: The generated answer goes straight to the user with no quality gate.
Key Mental Models#
- Fixed bus route vs. metro network: Plain RAG is a bus locked to one route. Agentic RAG is a metro system where a station controller (Router) picks the right line and inspectors (Graders) verify the train before it reaches the final station.
Plain RAG forces every query down one blind PDF lookup without verification, whereas Agentic RAG dynamically routes across private and live sources and enforces two independent quality gates.
The Agentic RAG Team: Agents, Tools & Dual-LLM Design#
Revision Notes#
Concept#
An agent is an LLM given a specific role, a goal, and permission to use tools. Instead of one monolithic prompt, the work is divided across five narrow specialists, two tools, and two LLMs.
The Five Specialist Agents#
- Router (Hospital reception desk): Decides whether the answer lives in the PDF or on the internet. Outputs
vectorstoreorwebsearch. - Retriever (Librarian): Calls the tool chosen by the Router and brings back the retrieved answer along with raw supporting evidence.
- Answer Grader (Teacher: "Did you answer what was asked?"): Filters out irrelevant retrievals by checking whether the answer addresses the question. Outputs
yesorno. - Hallucination Grader (Auditor: "Show me the receipt"): Checks whether every important claim is supported by the retrieved source text. Outputs
yes(grounded/safe) orno. - Answer Generator (News anchor): If both checks pass, polishes the answer into a concise final response. If either fails, runs a fresh web search and answers from those results.
The Two Tools#
rag_tool: Wraps the entire traditional RAG pipeline (ChromaDB retrieval + fast LLM synthesis) into one function.web_search_tool: Queries the live web via Tavily and returns the top 3 clean text results.
- Extensibility: Because tools are plain functions, you can easily plug in a SQL database, a graph database for customer relationships, a calculator, or internal company APIs later.
The Dual-LLM Architecture#
- Main LLM (DeepSeek via OpenRouter): Powers all five agents and orchestrates routing, tool use, grading, and final synthesis. Reasoning strength matters most here.
- RAG LLM (Fast model on Groq): Lives exclusively inside
rag_toolto turn retrieved chunks into a concise draft answer. Because summarization sits mid-flow, ultra-low latency keeps the overall run snappy.
Trade-Offs & Pitfalls#
- Core trade-off: Moving from a hard-coded pipeline to runtime LLM routing and double verification trades latency and cost for smarter routing and significantly fewer wrong answers.
Code Reference#
import math
import re
from collections import Counter
# ---------------------------------------------------------------------------
# Our tiny "private PDF" (in real life this is a long document)
# ---------------------------------------------------------------------------
# Five short paragraphs simulate a multi-page technical document so you can trace
# chunking, vector similarity, routing, and grading without any API keys or downloads.
DOCUMENT = """
The Transformer is a neural network architecture based entirely on attention.
It removes recurrence and convolutions completely, so it trains much faster.
Self-attention lets each word in a sentence look at every other word and decide
how much attention to pay to it. This is how the model understands context.
Attention uses three vectors for every word: a query, a key and a value.
The score between two words is the dot product of the query and the key,
scaled and passed through a softmax.
Multi-head attention runs several attention operations in parallel so the model
can focus on different kinds of relationships at the same time.
Transformers have no recurrence, so positional encodings are added to the
input embeddings to tell the model the order of the words.
"""
# Fake "internet" for the web search tool — simulates an external fallback source
# used when the Router decides a query is outside the private PDF's scope.
FAKE_WEB = {
"weather": "Web result: Today in Bengaluru it is 24 degrees C with light rain.",
"cricket": "Web result: India won yesterday's match by 6 wickets.",
"multi-head": "Web result: Multi-head attention splits attention into several "
"'heads' that each learn a different relationship, then joins them.",
}
# Filtering high-frequency function words prevents bag-of-words cosine similarity
# from scoring unrelated paragraphs highly just because both contain "the" or "is".
STOP_WORDS = set("the a an is of to and in it its for on what how does do are with by "
"that this be at as from can each every".split())
def words(text: str) -> list[str]:
"""Lower-case, drop common words, and cut a plural 's' (transformers -> transformer)."""
out = []
for w in re.findall(r"[a-z]+", text.lower()):
if w in STOP_WORDS:
continue
# Lightweight stemming: strip trailing 's' (avoiding words like 'loss' or 'pass')
# so singular queries match plural document terms in our zero-dependency retriever.
if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
w = w[:-1]
out.append(w)
return out
# -> e.g. words("How does self-attention work?") -> ["self", "attention", "work"]
# ---------------------------------------------------------------------------
# INDEXING: split -> embed -> store (done once)
# ---------------------------------------------------------------------------
def split_into_chunks(text: str) -> list[str]:
"""Simplest chunking strategy: one paragraph = one chunk."""
# Splitting on blank lines preserves semantic boundaries; normalizing internal
# whitespace makes each chunk clean for display and token counting.
paragraphs = text.strip().split("\n\n")
# -> 5 raw paragraph strings from DOCUMENT
return [" ".join(p.split()) for p in paragraphs if p.strip()]
# -> ["The Transformer is a neural network architecture...",
# "Self-attention lets each word in a sentence...", ... (5 chunks total)]
# ... (see full file: step0_simulate_flow.py)
$ python step0_simulate_flow.py
Indexed 5 chunks from DOCUMENT.
--- Question 1: "How does self-attention work?" ---
[Router] -> vectorstore (domain keywords matched)
[Retriever] -> top chunk (score=0.58): "Self-attention lets each word in a sentence..."
[Grader] -> RELEVANT (term overlap >= threshold)
[Hallucination] -> GROUNDED (answer uses only retrieved chunk)
[Final Answer] -> Self-attention lets each word in a sentence look at every other word...
--- Question 2: "What is the weather in Bengaluru today?" ---
[Router] -> web_search (out of PDF scope)
[Retriever] -> Web result: Today in Bengaluru it is 24 degrees C with light rain.
[Grader] -> RELEVANT
[Final Answer] -> Today in Bengaluru it is 24 degrees C with light rain.
Tracing a Question End to End#
Revision Notes#
Concept#
Execution works like a relay race: each agent runs one lap and hands its structured output (the baton) to the next agent.
Path A — Library Line ("What is self-attention?")#
- Router compares the question against the one-line
PDF_TOPICdescription and outputsvectorstore. - Retriever calls
rag_toolwith the full question and returnsSOURCE: document, the draft answer, and the 4 source chunks. - Answer Grader outputs
yes(on topic). - Hallucination Grader inspects the draft answer against the 4 chunks and outputs
yes(every claim traces to a chunk). - Answer Generator polishes the draft into a clean final answer with no mention of routing or grading.
Path B — Web Line ("Who won yesterday's cricket match?")#
- Router outputs
websearch(a static research paper cannot know yesterday's score). - Retriever calls
web_search_tooland returnsSOURCE: webplus the top 3 web results (titles, links, snippets). - Both graders pass, and Answer Generator writes a concise answer from the web results.
Path C — Failure / Fallback Line (Hallucination Caught)#
- Router selects
vectorstore, and Retriever fetches good chunks, but the draft RAG answer invents a date not present in the chunks. - Answer Grader outputs
yes(it is on topic), but Hallucination Grader outputsno(the date lacks evidence). - Answer Generator sees a
no, rejects the untrusted draft, runs a fresh web search, and builds the final answer from the web results.
Cost & Performance Comparison (Per Question)#
- LLM calls: Plain RAG makes 1 call; Agentic RAG makes ~7–8 calls (5 agents, tool calls, and the inner RAG LLM).
- Latency: Plain RAG takes a few seconds; Agentic RAG takes ~15–30 seconds on fast cloud providers, or several minutes on slow free tiers (up to ~10 minutes worst case) or local Ollama.
- Monetary cost: Plain RAG is practically zero; Agentic RAG on DeepSeek V4 Flash is well under ₹1 per question.
- Live knowledge: Plain RAG has none; Agentic RAG supports live queries via web search.
- Self-checks: Plain RAG has none; Agentic RAG runs two independent checks (relevance + grounding).
Real-World Use Cases & When to Choose Agentic RAG#
Revision Notes#
Concept#
Across industries, the architecture repeats the same split: private documents on the library line, live/external data on the web or API line, and graders wherever mistakes carry real risk.
Production Patterns#
- Bank customer support:
- Library line: Loan, FD, and credit-card policies plus fee schedules.
- Live line: Current repo rate news or active offers (web or bank API).
- Why checks matter: A fabricated foreclosure penalty triggers customer complaints and regulatory fines (e.g., "FD closed after 8 months: penalty?").
- Hospital help desk:
- Library line: Visiting rules, admission checklists, insurance/cashless policies.
- Live line: Real-time doctor availability via an appointment system tool.
- Why checks matter: A hallucinated fasting instruction can directly harm a patient (e.g., "Documents for cashless admission?").
Decision Guide: Plain RAG vs. Agentic RAG#
- Start simple: Build plain RAG first, measure its actual failure modes on real queries, and add routing or grading only for the failures you observe.
CrewAI Core Primitives & Prompt Engineering#
Revision Notes#
Concept#
Four primitives make any CrewAI codebase readable:
- Agent (Employee) — Who does the work. Configured with
role(job title),goal(success criteria),backstory(persona and reasoning style),llm(brain),allow_delegation=False(no handing off work),max_iter=5(loop safety brake), andverbose=True(observable thought trace). - Task (To-do list item) — What gets done. Configured with
description(instructions with{question}placeholder),expected_output(exact output shape),agent(assignee),context(earlier tasks whose outputs it can read), andtools. - Tool (Equipment like a phone or library card) — With what the agent acts (a Python function plus a clear docstring).
- Crew (The team + work order) — How everything runs together.
Prompt Engineering Is the Real Work#
Agent backstories and task descriptions are prompts, refined through testing. Real-world fixes from this project:
- Keyword-matching Router: Router matched surface words instead of intent → Fix: Instruct it to route based on the semantic meaning of the question, not keyword matching.
- Chatty Graders: Graders wrote long explanations that confused downstream agents → Fix: Enforce exactly one word:
yesorno, with no explanation or punctuation. - Process-leaking Generator: Final answer narrated how it routed and graded → Fix: Instruct it to output only the answer, never how it was found.
- Debugging rule of thumb: When an agent misbehaves, read its terminal trace and tighten its
backstory,description, orexpected_outputbefore rewriting code.
Core Terms#
- Inference: Running a trained model to generate an output.
- Token: A small chunk of text (often part of a word) used to measure pricing and context limits.
- Tool calling (function calling): An LLM's ability to emit a structured request to run a specific function with specific arguments.
System Modules & Architecture Decisions#
Revision Notes#
The project separates concerns across six clean modules (config.py, llms.py, tools.py, agents.py, tasks.py, main.py).
A. Configuration & Brains (config.py and llms.py)#
- Three-way brain switch (
LLM_MODE):openrouter(default): Runs DeepSeek V4 Flash in the cloud. Pay-as-you-go (a small credit lasts long), good speed; best for learning the real DeepSeek setup.groq: Runs a fast open model on Groq (not DeepSeek). Free tier, very fast; best for zero-cost practice.ollama: Runs DeepSeek-R1 8B locally on your laptop. Free and private, slower on CPU-only laptops (needs ~8 GB free RAM).
- RAG brain switch (
RAG_LLM_MODE): Set togroqfor fast cloud summarization, orsameto reuse the main LLM without needing a Groq key. - Tool-calling requirement: The main model must support function calling so the Retriever and Answer Generator can invoke tools.
- Settings beat hard-coding: Model providers frequently retire endpoints (for example, Groq stopped serving DeepSeek models in October 2025, and OpenRouter had no free DeepSeek tier at the time of writing). Keeping every model ID in
.envallows instant swaps without touching code. - Routing hint (
PDF_TOPIC): A one-line summary of the PDF. The Router never opens the PDF—it makes an educated guess fromPDF_TOPIC+ the question. Always updatePDF_TOPICwhen swapping PDFs. - Safety limits:
TOP_K=4(PDF chunks),WEB_RESULTS=3(Tavily results), andMAX_RPM=10(team-wide rate governor to respect strict free-tier limits). - Universal connector & caching (
llms.py):- CrewAI's
LLM(...)uses the prefix before the first slash (openrouter/...,ollama/...,openai/...) to select the provider. - Low temperatures (
temperature=0.1for main,temperature=0.0for Groq) keep routing and grading deterministic. @lru_cache(maxsize=1)instantiates the brain once and shares it across all five agents.clean_text()strips<think>...</think>reasoning blocks emitted by models like DeepSeek-R1 so downstream agents only see the clean answer.
- CrewAI's
B. Hands of the Agents (tools.py)#
- Isolated vector shelves (
create_pdf_search_tool): Uses CrewAI'sPDFSearchToolfor loading, chunking, localsentence-transformerembedding (~130 MB one-time Hugging Face download), and ChromaDB persistence. Eachcollection_nameis built from<pdf stem>_<embedding model>(sanitized and truncated to 60 characters) so switching PDFs or embedding models never mixes incompatible vectors. - RAG tool flow (
create_rag_tool):
Five sequential CrewAI tasks pass explicit context=[...] outputs forward while isolating tools on Retriever and Answer Generator, pairing a tool-capable DeepSeek brain with a low-latency Groq RAG summarizer.
- Decorated with
@tool("rag_tool"). The docstring is an instruction to the LLM, not decoration—it tells the agent when and how to call the tool. RAG_PROMPTenforces strict grounding: use ONLY the context, answer in 3–6 clear sentences, or reply exactlyNOT_FOUND_IN_DOCUMENT.- Returns both the answer and the raw chunks—the chunks act as receipts for the Hallucination Grader.
- Graceful web search (
web_search_tool): Calls Tavily (max_results=3) inside atry/exceptblock. On failure (offline, bad key, quota hit), it returnsWEB_SEARCH_FAILED: <error>instead of crashing the crew. - Real-world tool-calling bug: When an agent called
web_search_toolwith no arguments ("missing 1 required positional argument"), the fix was purely instructional: state in the docstring that input must be the user's full question, and repeat in the task description to pass{question}.
C. Specialists & Task Wiring (agents.py and tasks.py)#
- Tools live on tasks, not agents, so the same agent definition can be reused with different toolsets.
max_iter=5caps think-and-act loops per agent to prevent runaway credit burn.context=[...]lets a task read earlier tasks' outputs without re-running them or inheriting their tools.
Solid arrows show execution order; dashed arrows show additional task outputs passed via context.
- Task 1 (
route— Router): Context: none. Tools: none. Output: exactly one word (vectorstorefor doc topics even with different wording;websearchfor live/real-time or out-of-scope topics). - Task 2 (
retrieve— Retriever): Context:[router_task]. Tools:[rag_tool, web_search_tool]. Output:SOURCE: documentorSOURCE: web, the answer, and supporting text copied verbatim. Ifrag_toolreturnsNOT_FOUND_IN_DOCUMENT, it automatically retries on the web with the full question. - Task 3 (
grade— Answer Grader): Context:[retriever_task]. Tools: none. Output: one word (yesif relevant, elseno). - Task 4 (
hallucination— Hallucination Grader): Context:[retriever_task, grader_task]. Tools: none. Output: one word (yes= grounded/safe,no= unsupported claims/invented numbers or names). - Task 5 (
answer— Answer Generator): Context:[retriever_task, grader_task, hallucination_task]. Tools:[web_search_tool]. Output: clean 3–6 sentence answer. If both grades areyes, polish the retrieved answer; if either isno, run a fresh web search and answer from it.
- Critical distinctions:
- Relevance ≠ Grounding: An answer can be on-topic yet fabricated, or factually grounded yet off-topic—hence two separate graders.
- Hallucination
yesmeans SAFE:yesmeans "grounded, no hallucination"—not "yes, there is a hallucination."
D. Orchestration & Execution (main.py)#
main.pyholds no intelligence; it assembles the crew and starts execution.- Fail-fast validation:
config.check_keys()runs before any expensive indexing or API calls. - Sequential execution:
Process.sequentialruns the 5 tasks in order (simple and debuggable), governed bymax_rpm=config.MAX_RPM. - Journey telemetry: After
crew.kickoff(inputs={"question": ...}), every task's output remains accessible, allowing a single summary line (route=... relevant=... grounded=... time=...s). - Modes of running: Keyless dry-run simulation (
step0_simulate_flow.pydemonstrating a caught hallucination), single-question CLI runs, and persistent--chatmode (indexes the PDF once, then answers interactively untilexit/quit).
Code Reference#
import os
from dotenv import load_dotenv
# Read the .env file and put every line into "environment variables".
# Loading once at import time ensures every module sees the same configuration
# without needing to pass keys or model names through function signatures.
load_dotenv()
# ---------------------------------------------------------------------------
# 1) API KEYS (see the study guide for where to get each one)
# ---------------------------------------------------------------------------
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "") # DeepSeek in the cloud
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") # very fast cloud models
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY", "") # web search
# ---------------------------------------------------------------------------
# 2) WHICH "BRAIN" DO THE 5 AGENTS USE?
# "openrouter" -> DeepSeek in the cloud (default). Pay-as-you-go, but a
# question costs a tiny fraction of a rupee.
# "groq" -> a fast open model on Groq's free tier (not DeepSeek).
# Good for practising without any payment.
# "ollama" -> DeepSeek running on your own laptop. Free and private,
# but slow, and needs about 8 GB of free RAM.
# ---------------------------------------------------------------------------
# Normalizing with .strip().lower() prevents subtle .env bugs like trailing spaces or "GROQ".
LLM_MODE = os.getenv("LLM_MODE", "openrouter").strip().lower()
# DeepSeek model on OpenRouter. It must support "tools" (function calling),
# because our Retriever agent calls tools. Check openrouter.ai/models.
OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4-flash")
# DeepSeek on your laptop via Ollama (run: ollama pull deepseek-r1:8b)
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "deepseek-r1:8b")
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
# ---------------------------------------------------------------------------
# 3) THE SECOND, FAST LLM - used only inside the RAG tool to turn the
# retrieved PDF chunks into a short answer.
# "groq" -> very fast cloud inference (needs GROQ_API_KEY)
# "same" -> reuse the main brain above (no Groq key needed)
# ---------------------------------------------------------------------------
# Splitting the "reasoning brain" from the "fast RAG summarizer" cuts latency and
# token cost while keeping tool-calling reliability high for the 5 agents.
RAG_LLM_MODE = os.getenv("RAG_LLM_MODE", "groq").strip().lower()
# One Groq model name, used for the RAG LLM (and for the brain if LLM_MODE=groq)
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
# ---------------------------------------------------------------------------
# 4) EMBEDDINGS - the model that turns text into numbers (vectors).
# Runs locally on your laptop. Downloaded once from Hugging Face.
# ---------------------------------------------------------------------------
# BAAI/bge-small-en-v1.5 (384 dims, ~130 MB) gives strong retrieval quality on CPU
# with zero per-token embedding API cost.
EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL", "BAAI/bge-small-en-v1.5")
# ---------------------------------------------------------------------------
# 5) OUR KNOWLEDGE BASE (the private document)
# ---------------------------------------------------------------------------
PDF_PATH = os.getenv("PDF_PATH", "data/attention_is_all_you_need.pdf")
PDF_URL = os.getenv("PDF_URL", "https://arxiv.org/pdf/1706.03762")
# One line that tells the Router agent WHAT is inside the PDF.
# ... (see full file: config.py)
$ python -c "import config; print(config.LLM_MODE, '|', config.RAG_LLM_MODE, '|', config.EMBEDDING_MODEL)"
openrouter | groq | BAAI/bge-small-en-v1.5
import re
from functools import lru_cache
from crewai import LLM
import config
@lru_cache(maxsize=1) # build it once, then reuse the same object across all 5 agents
def get_main_llm() -> LLM:
"""The brain shared by every agent."""
if config.LLM_MODE == "ollama":
# DeepSeek running on YOUR laptop. Before running:
# 1) install Ollama from ollama.com
# 2) in a terminal: ollama pull deepseek-r1:8b
return LLM(
model=f"ollama/{config.OLLAMA_MODEL}",
base_url=config.OLLAMA_BASE_URL,
temperature=0.1, # low temperature keeps routing and grading decisions deterministic
)
if config.LLM_MODE == "groq":
# Free-tier practice mode: a fast open model on Groq (not DeepSeek).
return _groq_llm()
# Default: DeepSeek in the cloud through OpenRouter.
# The "openrouter/" prefix tells CrewAI's LiteLLM backend which provider to call.
return LLM(
model=f"openrouter/{config.OPENROUTER_MODEL}",
# -> "openrouter/deepseek/deepseek-v4-flash"
api_key=config.OPENROUTER_API_KEY,
temperature=0.1, # low temperature = calm, consistent answers
)
def get_rag_llm() -> LLM:
"""The fast helper LLM used only inside the RAG tool."""
if config.RAG_LLM_MODE == "groq":
return _groq_llm()
# "same" -> reuse the main brain so users only need one API key
return get_main_llm()
@lru_cache(maxsize=1)
def _groq_llm() -> LLM:
# Groq exposes an OpenAI-compatible REST API, so the "openai/" prefix plus
# custom base_url avoids needing a separate provider SDK.
# temperature=0.0 enforces strict faithfulness to the retrieved PDF chunks.
return LLM(
model=f"openai/{config.GROQ_MODEL}",
# -> "openai/llama-3.3-70b-versatile"
base_url=config.GROQ_BASE_URL,
api_key=config.GROQ_API_KEY,
temperature=0.0,
)
def clean_text(text) -> str:
"""Reasoning models like DeepSeek-R1 sometimes print their private
'thinking' inside <think> ... </think>. We only want the final answer."""
# Coerce CrewOutput or other wrapper objects to plain str before regex stripping
text = str(text)
# -> "<think>check chunk 2</think>Self-attention weighs every token against all others."
# ... (see full file: llms.py)
>>> from llms import get_main_llm, get_rag_llm, clean_text
>>> get_main_llm().model
'openrouter/deepseek/deepseek-v4-flash'
>>> get_rag_llm().model
'openai/llama-3.3-70b-versatile'
>>> clean_text("<think>check chunk 2</think>Self-attention weighs every token against all others.")
'Self-attention weighs every token against all others.'
Toolbox, Local Execution & Production Deployment#
Revision Notes#
The Core Toolbox#
- CrewAI: Python orchestration framework for multi-agent crews, tasks, and tools.
- DeepSeek: Open LLM family strong at reasoning and agentic tool use at low cost (DeepSeek V4 Flash in cloud, DeepSeek-R1 locally).
- OpenRouter: Unified API gateway providing one key for hundreds of models across providers.
- Groq: Cloud inference on custom LPU chips for ultra-fast generation (used inside
rag_tool). - Ollama: Free local runtime to download and serve LLMs offline.
- Tavily: AI-native search API returning clean, structured text rather than raw HTML.
- ChromaDB: Lightweight local vector database with disk persistence.
Running DeepSeek Locally (Ollama)#
- Uses
deepseek-r1:8b(~5 GB download, ~8 GB free RAM), served locally on port11434. Only Tavily web search requires internet access. - Trade-off: Full privacy and zero API cost for the brain, but noticeably slower and less accurate on consumer laptops. Local 8B is great for learning; production self-hosting requires a GPU.
- Model size pitfall: Avoid tiny models like 1.5B—they download quickly but frequently fail structured tool calling, causing the Retriever to stall. Use 8B or larger.
Production & Enterprise Deployment#
- Router evolution: Because the default Router relies on
PDF_TOPIC(an educated guess backed by Retriever fallback and graders), a stronger production design gives the Router a quick "peek" tool to probe vector similarity scores first. - Scaling architecture: Start on a cloud VM (e.g., AWS EC2, adding a GPU only if self-hosting the LLM). For multi-user traffic, run multiple replicas behind a load balancer and put long-running agent jobs behind a message queue (since answers take seconds to minutes).
- API vs. Self-hosting: Cloud APIs are fastest to ship; self-hosting wins on strict data privacy and high-volume unit economics, at the cost of infrastructure maintenance.
- Company documents: Point to a folder or build one vector library per department, validate manually against 20–30 real user questions before launch, and use Ollama or a company-approved provider for confidential data.
Troubleshooting, Pitfalls & Quick Reference#
Revision Notes#
Common Failure Modes & Fixes#
- "Please fix your .env file first": A required API key is empty or the file is still named
.env.example. Rename to.envin the project directory with no quotes or spaces around=. Never commit.env(add it to.gitignore). - HTTP 404 (model not found): Provider retired or renamed the model ID. Update
OPENROUTER_MODELorGROQ_MODELin.envwith a current ID. - HTTP 429 (rate limit): Free-tier quota exceeded. Wait, lower
MAX_RPM, or switch to a paid model. WEB_SEARCH_FAILED: No internet, invalid Tavily key, or quota reached. Fix the key/network; the rest of the crew stays alive.- Embedding dimension mismatch: Existing ChromaDB collection was built with a different embedding model. Because the shelf name embeds the model name, changing
EMBEDDING_MODELcreates a fresh shelf automatically; if manually renamed, use a new collection/PDF name.
High-Signal Pitfalls to Avoid#
- Embedding queries and documents with different models → meaningless similarity scores.
- Swapping the PDF without updating
PDF_TOPIC→ misrouted questions. - Misreading Hallucination Grader's
yesas "hallucinated" → it means grounded/safe. - Vague tool docstrings → agents omit required arguments.
- Allowing verbose grader outputs → confuses downstream agents (always force one word).
- Running tiny local models (1.5B) → broken tool calling (use ≥ 8B).
- Expecting plain RAG to answer live questions → it can only return
NOT_FOUND_IN_DOCUMENT.
Key Numbers & Defaults#
- Retrieval & limits:
TOP_K=4,WEB_RESULTS=3,MAX_RPM=10,max_iter=5. - Embeddings:
BAAI/bge-small-en-v1.5, 384 dimensions, ~130 MB local download. - Temperatures:
0.1(main LLM),0.0(Groq RAG LLM). - Cost & latency: Plain RAG = 1 call; Agentic RAG = ~7–8 calls (~15–30 s fast cloud, minutes on free/local).
- Local Ollama:
deepseek-r1:8b, ~5 GB disk, ~8 GB RAM, port11434. - Pre-launch eval: Manually test 20–30 real user questions.
- Default
.envprofile:LLM_MODE=openrouter(deepseek/deepseek-v4-flash),RAG_LLM_MODE=groq(llama-3.3-70b-versatile),EMBEDDING_MODEL=BAAI/bge-small-en-v1.5,PDF_PATH=data/attention_is_all_you_need.pdf.
How All Building Blocks Connect#
Revision Notes#
Every layer in this system exists to cover a specific weakness of the layer beneath it:
- Embeddings + ChromaDB turn static private PDFs into fast semantic lookup shelves, solving the LLM's lack of private knowledge without fine-tuning.
- Wrapping plain RAG as
rag_toolpaired withweb_search_toolgives agents interchangeable hands—and a fast Groq model insiderag_toolprevents mid-pipeline summarization from becoming a bottleneck. - The Router +
PDF_TOPICreplaces plain RAG's blind lookup with semantic routing, while the Retriever'sNOT_FOUND_IN_DOCUMENTfallback catches cases where the Router guessed wrong. - Dual Graders (Answer Grader + Hallucination Grader) enforce two orthogonal quality gates—relevance and factual grounding—using the raw chunks returned by the Retriever as auditable receipts.
- The Answer Generator closes the loop: polishing verified answers silently when both gates pass, or triggering an automatic fresh web search when either gate fails.
- CrewAI's sequential wiring (
context,expected_output,max_iter,MAX_RPM) keeps five autonomous prompts predictable, rate-limited, and debuggable via prompt tuning rather than brittle glue code.
Quick Self-Check Questions#
Self-Check Questions#
Why must you always embed user questions and PDF chunks with the exact same embedding model?
Different embedding models map text into completely different vector spaces (and often different dimensions). Comparing vectors from two different models yields meaningless similarity distances or a dimension mismatch error.
Why does the system use two separate graders—an Answer Grader and a Hallucination Grader—instead of just one?
Relevance and grounding are independent properties. An answer can be completely on-topic while inventing facts not in the source (relevant = yes, grounded = no), or strictly faithful to the source while failing to answer what the user actually asked (relevant = no, grounded = yes).
In the Hallucination Grader task, what does an output of yes mean?
yes means the answer is grounded and safe (no hallucination detected). A no means unsupported facts were found and triggers the Answer Generator's web-search fallback.
How does the Router decide between vectorstore and websearch without reading the PDF, and what protects the system if it guesses wrong?
It compares the semantic meaning of the question against the one-line PDF_TOPIC hint. If it mistakenly routes to vectorstore, the Retriever falls back to web_search_tool upon receiving NOT_FOUND_IN_DOCUMENT, and the two graders + Answer Generator provide a second fallback net.
Why does this architecture use two different LLMs instead of one?
Different roles have different priorities. The five orchestrating agents need strong reasoning and reliable tool calling (DeepSeek), whereas the inner rag_tool only summarizes retrieved chunks mid-flow, where a fast Groq model keeps total latency down.
Why does rag_tool return both the synthesized answer and the 4 raw chunks?
The raw chunks serve as verifiable "receipts" passed via task context to the Hallucination Grader so it can check whether every claim in the draft answer is actually supported by the source text.
When an agent calls a tool with missing arguments or outputs rambling text that breaks the next step, what should you fix first?
Fix the prompts—specifically the tool's docstring, the agent's backstory, and the task's description and expected_output (e.g., enforcing one-word grader outputs and explicitly telling the agent to pass {question})—before rewriting Python code.
When should you stick with Plain RAG instead of building Agentic RAG?
Stick with Plain RAG when all answers live strictly inside static documents, you need 1–2 second responses at near-zero cost, and occasional mistakes are low-stakes. Upgrade to Agentic RAG when you need live/external data or when hallucinations are costly (finance, healthcare, legal).