Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

audit: fix agentic_rag_system - add env comment, README tagline, rewrite em dashes, add docstrings

Tiioluwani8b59f5bed909
diff --git a/ai_agents/agentic_rag_system/.env.example b/ai_agents/agentic_rag_system/.env.example
index 1885955..57fe371 100644
--- a/ai_agents/agentic_rag_system/.env.example
+++ b/ai_agents/agentic_rag_system/.env.example
@@ -1 +1,2 @@
+# Google Gemini API key used to authenticate requests to Gemma 4 and the Gemini Embedding model. Get yours free at https://aistudio.google.com
GEMINI_API_KEY=your_google_ai_studio_key_here
diff --git a/ai_agents/agentic_rag_system/README.md b/ai_agents/agentic_rag_system/README.md
index 8b9b209..270e078 100644
--- a/ai_agents/agentic_rag_system/README.md
+++ b/ai_agents/agentic_rag_system/README.md
@@ -1,26 +1,28 @@
# πŸ”„ Self-Reflective Agentic RAG
+> A LangGraph-powered RAG system that grades its own retrieved context, rewrites the search query when needed, and only generates an answer once the context passes validation.
+
![Self-Reflective Agentic RAG Demo](assets/demo.png)
## Overview
-Standard RAG pipelines retrieve context and generate an answer immediately β€” with no check on whether the retrieved chunks are actually relevant or sufficient. This leads to hallucinations when the retrieval misses the mark.
+Standard RAG pipelines retrieve context and generate an answer immediately, with no check on whether the retrieved chunks are actually relevant or sufficient. This leads to hallucinations when the retrieval misses the mark.
This project solves that by introducing an **iterative retrieval-validation loop** before generation. Instead of answering right away, the system uses a LangGraph-driven state machine to:
1. **Retrieve** context from the vector store
2. **Grade** the retrieved context for relevance, sufficiency, and consistency
-3. **Rewrite** the query if the context doesn't pass β€” and re-retrieve with a better search
+3. **Rewrite** the query if the context doesn't pass, then re-retrieve with a better search
4. **Generate** a grounded answer only once the context passes validation
-This loop runs up to 3 times, progressively refining the search query until the LLM is confident the context is good enough β€” or gracefully falls back to the best available context.
+This loop runs up to 3 times, progressively refining the search query until the LLM is confident the context is good enough, falling back gracefully to the best available context if the iteration limit is reached.
## Features
- **Self-Reflection Loop:** LLM grades each retrieval attempt with a structured `VERDICT / REASON / REFINED_QUERY` output before generation
-- **Query Rewriting:** On a `NO` verdict, the system rewrites the search query based on what the grader says is missing β€” not just re-running the same query
+- **Query Rewriting:** On a `NO` verdict, the system rewrites the search query based on what the grader says is missing, rather than re-running the same query
- **Iteration Cap:** Hard limit of 3 retrieval loops prevents infinite loops on ambiguous or unanswerable questions
-- **Hallucination Reduction:** Answer generation is strictly grounded β€” the prompt explicitly forbids the model from going beyond the validated context
+- **Hallucination Reduction:** Answer generation is strictly grounded because the prompt explicitly forbids the model from going beyond the validated context
- **Full Reflection Log:** The UI surfaces the complete per-iteration grading log so you can see exactly why the system looped or stopped
- **Clean Gradio UI:** Process/clear PDF controls, locked Ask button until a document is loaded, collapsible reflection accordion
@@ -33,7 +35,7 @@ This loop runs up to 3 times, progressively refining the search query until the
- [Gradio](https://www.gradio.app/): Interactive web UI
**Models (via Google AI / Gemini API):**
-- **LLM:** [`gemma-4-26b-a4b-it`](https://ai.google.dev/gemma/docs/core/gemma_on_gemini_api) β€” used for retrieval grading, query rewriting, and answer generation
+- **LLM:** [`gemma-4-26b-a4b-it`](https://ai.google.dev/gemma/docs/core/gemma_on_gemini_api), used for retrieval grading, query rewriting, and answer generation
- **Embeddings:** [`gemini-embedding-001`](https://ai.google.dev/gemini-api/docs/embeddings) with `retrieval_document` task type
## How It Works
@@ -55,10 +57,10 @@ This loop runs up to 3 times, progressively refining the search query until the
```
**Nodes:**
-- **`retrieve`** β€” Fetches the top-4 most similar chunks using the current query (original or rewritten)
-- **`grade_retrieval`** β€” Prompts Gemma to return a structured `VERDICT: YES/NO`, `REASON`, and `REFINED_QUERY`
-- **`rewrite_query`** β€” Parses `REFINED_QUERY` from the grader output and updates the state
-- **`generate`** β€” Produces the final answer, instructed to stay strictly within the validated context
+- **`retrieve`**: Fetches the top-4 most similar chunks using the current query (original or rewritten)
+- **`grade_retrieval`**: Prompts Gemma to return a structured `VERDICT: YES/NO`, `REASON`, and `REFINED_QUERY`
+- **`rewrite_query`**: Parses `REFINED_QUERY` from the grader output and updates the state
+- **`generate`**: Produces the final answer, instructed to stay strictly within the validated context
**Router logic:**
- `VERDICT: YES` β†’ go to `generate`
@@ -109,7 +111,7 @@ uv run main.py
Navigate to `http://127.0.0.1:7860` in your browser.
1. **Upload a PDF** using the Document panel on the left
-2. Click **βš™οΈ Process** β€” the status shows how many chunks were indexed
+2. Click **βš™οΈ Process**; the status shows how many chunks were indexed
3. Type a question in the Ask a Question panel and click **πŸ” Ask**
4. Expand the **Self-Reflection Loop** accordion to see the per-iteration grading logs
5. Read the grounded answer in the Answer section below
@@ -120,7 +122,7 @@ Navigate to `http://127.0.0.1:7860` in your browser.
```text
agentic_rag_system/
β”œβ”€β”€ main.py # Gradio UI and PDF processing logic
-β”œβ”€β”€ rag_graph.py # LangGraph state machine β€” nodes, edges, router
+β”œβ”€β”€ rag_graph.py # LangGraph state machine with nodes, edges, and router
β”œβ”€β”€ assets/
β”‚ └── demo.png # App screenshot
β”œβ”€β”€ .env.example # API key template
@@ -135,7 +137,7 @@ Contributions are welcome! Please feel free to submit a Pull Request.
## License
-This project is licensed under the MIT License β€” see the [LICENSE](../../LICENSE) file for details.
+This project is licensed under the MIT License. See the [LICENSE](../../LICENSE) file for details.
---
diff --git a/ai_agents/agentic_rag_system/main.py b/ai_agents/agentic_rag_system/main.py
index b5cf9c3..e197a75 100644
--- a/ai_agents/agentic_rag_system/main.py
+++ b/ai_agents/agentic_rag_system/main.py
@@ -1,3 +1,5 @@
+"""Gradio UI and PDF processing logic for the Self-Reflective Agentic RAG system."""
+
import gradio as gr
import os
import shutil
@@ -10,6 +12,7 @@ from rag_graph import app, embeddings, CHROMA_DB_PATH
# ── PDF Processing ─────────────────────────────────────────────────────────────
def process_pdf(file):
+ """Load, chunk, and index a PDF into the ChromaDB vector store."""
if file is None:
return (
gr.update(value="⚠️ No file selected. Please upload a PDF first."),
@@ -41,6 +44,7 @@ def process_pdf(file):
def clear_pdf():
+ """Delete the current ChromaDB vector store and reset the UI to its initial state."""
if os.path.exists(CHROMA_DB_PATH):
shutil.rmtree(CHROMA_DB_PATH)
return (
@@ -53,6 +57,7 @@ def clear_pdf():
# ── Question Answering ─────────────────────────────────────────────────────────
def ask_question(question):
+ """Run the RAG graph on the given question and return the reflection log and final answer."""
if not question or not question.strip():
return gr.update(value=""), gr.update(value="*Ask a question to get started.*")
@@ -92,6 +97,7 @@ def ask_question(question):
def clear_question():
+ """Clear the question input, reflection log, and answer output."""
return "", gr.update(value=""), gr.update(value="*Ask a question to get started.*")
diff --git a/ai_agents/agentic_rag_system/rag_graph.py b/ai_agents/agentic_rag_system/rag_graph.py
index d76e5b3..499ca77 100644
--- a/ai_agents/agentic_rag_system/rag_graph.py
+++ b/ai_agents/agentic_rag_system/rag_graph.py
@@ -51,6 +51,8 @@ def extract_text(response) -> str:
class GraphState(TypedDict):
+ """Shared state passed between every LangGraph node throughout the retrieval-validation loop."""
+
question: str # Original user question β€” never mutated
refined_query: str # Current search query (rewritten if needed)
context: str # Retrieved chunks joined as string
@@ -61,6 +63,7 @@ class GraphState(TypedDict):
def get_db() -> Chroma:
+ """Open and return the persistent ChromaDB vector store."""
return Chroma(persist_directory=CHROMA_DB_PATH, embedding_function=embeddings)