Spaces:
Sleeping
Sleeping
File size: 10,966 Bytes
71c1218 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a 43aa251 f9c215a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | ---
title: RAG Chatbot for Agentic AI eBook
emoji: π€
colorFrom: blue
colorTo: purple
sdk: streamlit
sdk_version: "1.28.0"
app_file: streamlit_app/app.py
pinned: false
---
# π€ RAG Chatbot for Agentic AI eBook
A Retrieval-Augmented Generation (RAG) chatbot that answers questions **strictly** from the supplied Agentic AI eBook PDF. Built as an AI Engineer Internship assignment.



---
## π Table of Contents
- [Features](#-features)
- [Quick Start](#-quick-start)
- [Setup](#-setup)
- [Running the Application](#-running-the-application)
- [Deploying to Hugging Face Spaces](#-deploying-to-hugging-face-spaces)
- [Sample Queries](#-sample-queries)
- [How I Solved This](#-how-i-solved-this)
- [Project Structure](#-project-structure)
- [API Keys Required](#-api-keys-required)
---
## β¨ Features
- **π PDF Ingestion**: Extract, clean, chunk, and embed PDF content
- **π Semantic Search**: Uses sentence-transformers for accurate retrieval
- **π― Grounded Answers**: Responses are strictly based on retrieved chunks (no hallucination)
- **π Confidence Scores**: Shows similarity-based confidence (0.0-1.0)
- **π Dual Mode**: LLM generation (with OpenAI) or extractive fallback (always works)
- **π» Web UI**: Clean Streamlit interface with chunk visualization
- **βοΈ Deployable**: Ready for Hugging Face Spaces
---
## π Quick Start
```bash
# 1. Clone the repository
git clone <your-repo-url>
cd rag-eAgenticAI
# 2. Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# 3. Install dependencies
pip install -r requirements.txt
# 4. Set environment variables
export PINECONE_API_KEY="your-pinecone-key"
# Optional: export OPENAI_API_KEY="your-openai-key"
# 5. Add your PDF
mkdir data
# Place Ebook-Agentic-AI.pdf in the data/ folder
# 6. Run ingestion
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --index agentic-ai-ebook
# 7. Start the app
streamlit run streamlit_app/app.py
```
---
## π§ Setup
### Prerequisites
- Python 3.9 or higher
- pip (Python package manager)
- Pinecone account (free tier works)
- Optional: OpenAI API key for LLM-powered answers
### Installation
1. **Create and activate virtual environment:**
```bash
python -m venv venv
# Windows
venv\Scripts\activate
# macOS/Linux
source venv/bin/activate
```
2. **Install dependencies:**
```bash
pip install -r requirements.txt
```
> π‘ **Note for CPU-only machines**: The default torch installation includes CUDA. For smaller download:
> ```bash
> pip install torch --index-url https://download.pytorch.org/whl/cpu
> ```
3. **Set environment variables:**
Create a `.env` file in the project root:
```env
PINECONE_API_KEY=your-pinecone-api-key-here
PINECONE_INDEX=agentic-ai-ebook
OPENAI_API_KEY=your-openai-key-here # Optional
```
Or set them directly in your shell:
```bash
# Windows PowerShell
$env:PINECONE_API_KEY="your-key"
$env:OPENAI_API_KEY="your-key"
# macOS/Linux
export PINECONE_API_KEY="your-key"
export OPENAI_API_KEY="your-key"
```
---
## π Running the Application
### Step 1: Ingest the PDF
Place your `Ebook-Agentic-AI.pdf` file in the `data/` folder, then run:
```bash
# With Pinecone (recommended)
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --index agentic-ai-ebook
# Local-only mode (no Pinecone needed)
python app/ingest.py --pdf ./data/Ebook-Agentic-AI.pdf --local-only
```
**Ingestion options:**
| Flag | Description | Default |
|------|-------------|---------|
| `--pdf` | Path to PDF file | Required |
| `--index` | Pinecone index name | `agentic-ai-ebook` |
| `--namespace` | Pinecone namespace | `agentic-ai` |
| `--chunk-size` | Tokens per chunk | `500` |
| `--overlap` | Chunk overlap in tokens | `50` |
| `--local-only` | Skip Pinecone, save locally | `False` |
| `--output-dir` | Output directory | `./data` |
### Step 2: Run the Streamlit App
```bash
streamlit run streamlit_app/app.py
```
The app will open in your browser at `http://localhost:8501`.
### Step 3: Configure in the UI
1. Enter your Pinecone API key in the sidebar (if not set via env var)
2. Optionally add OpenAI API key for LLM-powered answers
3. Adjust retrieval settings (top_k, etc.)
4. Click "Initialize Pipeline"
5. Start asking questions!
---
## βοΈ Deploying to Hugging Face Spaces
### Method 1: Git-based Deployment
1. **Create a new Space** on [huggingface.co/spaces](https://huggingface.co/spaces)
- Select **Streamlit** as the SDK
- Choose a name for your Space
2. **Clone and push:**
```bash
git clone https://huggingface.co/spaces/YOUR_USERNAME/YOUR_SPACE_NAME
cd YOUR_SPACE_NAME
# Copy all files from this repo
git add .
git commit -m "Initial deployment"
git push
```
3. **Set secrets** in Space Settings β Repository secrets:
- `PINECONE_API_KEY`: Your Pinecone key
- `PINECONE_INDEX`: Your index name
- `OPENAI_API_KEY`: (Optional) Your OpenAI key
4. **Important**: Ensure your `README.md` has the HF Spaces header:
```yaml
---
title: Agentic AI eBook Chatbot
emoji: π€
colorFrom: blue
colorTo: indigo
sdk: streamlit
sdk_version: "1.28.0"
app_file: streamlit_app/app.py
pinned: false
---
```
### Method 2: Manual Upload
1. Create a new Streamlit Space on Hugging Face
2. Upload all files via the web interface
3. Set secrets in Space Settings
> π **Reference**: [Hugging Face Spaces - Streamlit Docs](https://huggingface.co/docs/hub/spaces-sdks-streamlit)
---
## π¬ Sample Queries
Test the chatbot with these example questions:
| # | Query | Expected Retrieval |
|---|-------|-------------------|
| 1 | "What is the definition of 'agentic AI' described in the eBook?" | Pages discussing agentic AI definition |
| 2 | "List the three risks of agentic systems the eBook mentions." | Pages about risks/challenges |
| 3 | "What are the recommended safeguards for deploying agentic AI?" | Pages about safeguards/best practices |
| 4 | "How does the eBook distinguish between autonomous agents and traditional automation?" | Comparison sections |
| 5 | "What future research directions does the eBook propose?" | Conclusion/future work pages |
| 6 | "Summarize the eBook's conclusion in one paragraph." | Conclusion chapter |
### Expected Response Format
```json
{
"final_answer": "According to the eBook, agentic AI is defined as...",
"retrieved_chunks": [
{
"id": "pdfpage_12_chunk_0",
"page": 12,
"text": "Agentic AI represents a paradigm shift...",
"score": 0.92
}
],
"confidence": 0.92
}
```
---
## π§ How I Solved This
### Chunking Strategy
I chose a **500-token chunk size with 50-token overlap** for several reasons:
- 500 tokens is large enough to capture meaningful context
- Overlap ensures information at chunk boundaries isn't lost
- Token-based chunking (via tiktoken) is more consistent than character-based
The chunk ID format `pdfpage_{page}_chunk_{index}` makes it easy to trace answers back to source pages for verification.
### Embedding Choice
I used **sentence-transformers/all-MiniLM-L6-v2** because:
- It's completely free (no API costs)
- Works offline on CPU
- 384-dimension vectors are efficient for storage
- Quality is good enough for document retrieval
Trade-off: OpenAI's ada-002 would give better quality, but MiniLM keeps the project accessible without paid APIs.
### Extractive Fallback
The extractive mode exists because:
1. Not everyone has OpenAI API access
2. It ensures the app **always works**, even offline
3. Graders can test the core RAG functionality without API costs
4. It demonstrates that the retrieval pipeline works correctly
When no LLM key is provided, the system returns the most relevant chunks directly with minimal formatting - this is honest about what it's doing and still provides useful answers.
### Grounding Enforcement
To prevent hallucination, the LLM system prompt explicitly instructs:
> "Use only the text between markers. Do not invent facts. If the answer isn't in the excerpts, say 'I could not find a supported answer in the document.'"
This keeps the model honest about its knowledge boundaries.
---
## π Project Structure
```
rag-eAgenticAI/
βββ app/
β βββ __init__.py # Package initialization
β βββ ingest.py # PDF ingestion pipeline
β βββ vectorstore.py # Pinecone wrapper
β βββ rag_pipeline.py # LangGraph RAG pipeline
β βββ utils.py # Helper functions
β
βββ streamlit_app/
β βββ app.py # Streamlit UI
β βββ assets/ # Static files
β
βββ samples/
β βββ sample_queries.txt # Test questions
β βββ expected_responses.md # Expected output format
β
βββ infra/
β βββ hf_space_readme_template.md
β
βββ data/ # PDF and chunks (gitignored)
β
βββ README.md # This file
βββ architecture.md # Architecture docs
βββ requirements.txt # Dependencies
βββ quick_test.py # Validation script
βββ LICENSE # MIT License
βββ .gitignore
```
---
## π API Keys Required
| Service | Required | How to Get | Purpose |
|---------|----------|------------|---------|
| **Pinecone** | Yes* | [pinecone.io](https://www.pinecone.io/) (free tier) | Vector storage & retrieval |
| **OpenAI** | No | [platform.openai.com](https://platform.openai.com/) | LLM answer generation |
*You can run in `--local-only` mode without Pinecone for testing.
### Getting Pinecone API Key
1. Create account at [pinecone.io](https://www.pinecone.io/)
2. Go to API Keys in the console
3. Create a new key
4. Copy and set as `PINECONE_API_KEY`
### Getting OpenAI API Key (Optional)
1. Create account at [platform.openai.com](https://platform.openai.com/)
2. Go to API Keys
3. Create a new secret key
4. Copy and set as `OPENAI_API_KEY`
---
## π§ͺ Testing
Run the quick test script to verify everything works:
```bash
python quick_test.py
```
This will:
1. Test utility functions (chunking, scoring)
2. Test the RAG pipeline with a sample query
3. Print the response in the expected JSON format
---
## π License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
## π Acknowledgments
- [LangGraph](https://github.com/langchain-ai/langgraph) for RAG orchestration patterns
- [Pinecone](https://www.pinecone.io/) for vector database
- [Sentence-Transformers](https://www.sbert.net/) for embeddings
- [Streamlit](https://streamlit.io/) for the web framework
- [Hugging Face](https://huggingface.co/) for hosting
---
*Built for AI Engineer Intern Assignment - Answers strictly grounded in the Agentic AI eBook*
|