File size: 12,560 Bytes
2ed406a
 
 
 
 
 
 
 
 
 
 
bc10808
2ed406a
bc10808
2ed406a
bc10808
2ed406a
bc10808
2ed406a
 
 
 
 
 
 
 
bc10808
2ed406a
 
 
bc10808
2ed406a
 
 
 
 
 
 
 
 
 
 
 
 
bc10808
 
2ed406a
 
 
 
 
 
 
 
 
 
 
 
 
 
bc10808
2ed406a
bc10808
2ed406a
 
 
bc10808
2ed406a
bc10808
 
2ed406a
 
bc10808
2ed406a
bc10808
 
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
bc10808
 
2ed406a
 
bc10808
2ed406a
 
 
bc10808
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
bc10808
 
2ed406a
bc10808
2ed406a
 
 
 
bc10808
2ed406a
bc10808
2ed406a
bc10808
2ed406a
 
 
 
 
 
 
bc10808
2ed406a
bc10808
2ed406a
 
 
 
 
 
 
bc10808
2ed406a
bc10808
2ed406a
 
 
 
 
 
 
bc10808
2ed406a
bc10808
 
2ed406a
bc10808
 
2ed406a
bc10808
 
 
 
 
 
 
2ed406a
 
bc10808
 
2ed406a
 
bc10808
 
 
 
 
2ed406a
 
 
 
bc10808
 
 
2ed406a
bc10808
 
2ed406a
 
 
 
bc10808
 
 
 
2ed406a
 
 
 
 
 
 
 
 
 
bc10808
 
2ed406a
bc10808
 
 
 
 
 
 
2ed406a
 
 
bc10808
 
 
2ed406a
bc10808
 
 
 
2ed406a
 
 
bc10808
 
 
 
2ed406a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
bc10808
2ed406a
bc10808
 
2ed406a
 
bc10808
2ed406a
 
 
 
 
 
 
 
 
bc10808
 
2ed406a
bc10808
2ed406a
 
bc10808
2ed406a
 
 
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
bc10808
2ed406a
 
bc10808
2ed406a
bc10808
2ed406a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
 
bc10808
2ed406a
 
 
 
 
bc10808
2ed406a
bc10808
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
 
bc10808
2ed406a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc10808
7d187af
 
2ed406a
 
 
 
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
---
title: Graph RAG Chatbot
emoji: πŸ€–
colorFrom: blue
colorTo: purple
sdk: docker
sdk_version: "1.0"
python_version: "3.11"
app_file: app.py
pinned: false
---

# πŸ€– Graph RAG Chatbot

A production-ready **Retrieval-Augmented Generation (RAG) chatbot** with **Knowledge Graph visualization**, powered by Groq's fast LLM API and built with Flask.

## ✨ Features

- πŸ“€ **Document Upload**: Support for PDF, CSV, and TXT files (up to 50MB)
- πŸ“Š **Knowledge Graph Building**: Automatic graph construction from documents using NetworkX
- πŸ“ˆ **Graph Visualization**: Interactive visualization of knowledge graphs with Matplotlib
- πŸ’¬ **RAG-Powered Chat**: Query documents using semantic search + Groq Mixtral LLM
- ⚑ **Real-time Updates**: Background processing with live progress tracking
- πŸ“± **Responsive UI**: Modern, mobile-friendly interface (tested on all devices)
- πŸ” **Secure**: API keys managed via environment secrets (never exposed)
- πŸš€ **Production Ready**: Docker containerized, health checks enabled

## 🎯 How It Works

### Document Processing Pipeline
```
Upload Document
    ↓
Text Extraction (PDF/CSV/TXT)
    ↓
Text Chunking (Recursive character splitting)
    ↓
Knowledge Graph Building (NetworkX)
    ↓
Graph Visualization (Matplotlib PNG)
    ↓
Chunk Embeddings (SentenceTransformers)
    ↓
Document Ready for Queries
```

### Query Processing with RAG
```
User Question
    ↓
Embed Query
    ↓
Find Similar Document Chunks (Cosine similarity)
    ↓
Send Top-3 Chunks + Question to Groq
    ↓
LLM Generates Answer
    ↓
Return Answer + Sources + Confidence
```

## πŸš€ Quick Start

### Prerequisites
- Groq API Key (free at https://console.groq.com)
- Docker (optional, but recommended)

### Option 1: Docker Compose (Recommended) ⭐

```bash
# Clone or download the repository
cd graph-rag-chatbot

# Create environment file
cp .env.example .env

# Edit .env and add your GROQ_API_KEY
# GROQ_API_KEY=gsk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Start the application
docker-compose up -d

# Access at http://localhost:7860
```

### Option 2: Python Virtual Environment

```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Set API key
export GROQ_API_KEY="your_groq_api_key"  # On Windows: set GROQ_API_KEY=...

# Run the application
python app.py

# Access at http://localhost:7860
```

### Option 3: Hugging Face Spaces (Already Deployed)

If running on HF Spaces:
1. The app is already running at this Space URL
2. GROQ_API_KEY is configured as a repository secret
3. Just upload a document and start asking questions!

## πŸ“š Usage Guide

### Uploading Documents

1. Click the **Upload Zone** or drag & drop files
2. Supported formats: PDF, CSV, TXT
3. Maximum file size: 50MB
4. Status progression:
   - 🟑 **queued** β†’ Processing will start soon
   - 🟠 **processing** β†’ Building graph and embeddings
   - 🟒 **ready** β†’ Ready for queries, graph available

### Viewing Knowledge Graphs

1. Once document status is "ready", click **"πŸ“ˆ View Full Graph"**
2. Or switch to the **"Knowledge Graph"** tab
3. Select the document from the dropdown
4. Graph shows:
   - πŸ”΅ Blue nodes = Document chunks
   - 🟒 Green nodes = Extracted entities (keywords)
   - Edges = Relationships between chunks and entities

### Asking Questions

1. Select a document from the dropdown
2. Type your question in the chat box
3. Press **Enter** or click **Send**
4. Bot responds with:
   - Answer based on document content
   - Source chunks used
   - Confidence score

## πŸ”Œ API Endpoints

### `GET /`
Serves the main web interface (HTML/CSS/JS)

### `GET /api/documents`
Get list of all documents and their status
```json
{
  "documents": {
    "example.pdf": {
      "status": "ready",
      "chunks": 15,
      "entities": 42,
      "graph_image": "/graph-image/example.pdf",
      "progress": 100
    }
  },
  "api_key_set": true,
  "timestamp": "2024-06-27T10:30:00"
}
```

### `POST /api/upload`
Upload documents for processing
```bash
curl -X POST \
  -F "files=@document.pdf" \
  http://localhost:7860/api/upload
```

Response:
```json
{
  "success": true,
  "message": "βœ… 1 file(s) queued for processing",
  "successful": 1,
  "failed": 0,
  "files": ["document.pdf"]
}
```

### `POST /api/query`
Query a document with RAG
```bash
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the main topic?",
    "document": "example.pdf"
  }' \
  http://localhost:7860/api/query
```

Response:
```json
{
  "answer": "The main topic is...",
  "sources": ["Chunk 1", "Chunk 3"],
  "confidence": 0.92
}
```

### `GET /graph-image/{filename}`
Download the graph visualization PNG for a document

### `DELETE /api/delete/{filename}`
Delete a document and its graph data

## βš™οΈ Configuration

### Environment Variables

```env
GROQ_API_KEY=your_groq_api_key_here    # Required: LLM API access
PORT=7860                              # Optional: Application port (default: 7860)
FLASK_ENV=production                   # Optional: Flask environment mode
```

### Customizable Parameters (in app.py)

**Chunk Size** (line ~66):
```python
chunk_size=500,        # Size of text chunks in characters
chunk_overlap=100      # Overlap between chunks for context
```

**Embedding Model** (line ~27):
```python
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# Lightweight, fast model (~27MB)
# Change to 'all-mpnet-base-v2' for higher quality (slower)
```

**LLM Configuration** (line ~153):
```python
model="mixtral-8x7b-32768",  # Fast, powerful open model
max_tokens=500               # Response length
```

**Similarity Threshold** (line ~164):
```python
if similarities[i] > 0.3  # Increase for stricter matching
```

## πŸ§ͺ Testing

Run the test suite to verify all features:

```bash
# Upload a test document
# Check if status changes to "ready"
# View the knowledge graph
# Ask a question and verify response
# Delete the document
```

See `TESTING.md` for 15+ comprehensive test cases with procedures.

## πŸ“¦ Technology Stack

| Component | Technology | Purpose |
|-----------|-----------|---------|
| Backend | Flask 2.3.3 | Web framework |
| LLM | Groq Mixtral 8x7b | Language model for answers |
| Embeddings | SentenceTransformers | Document/query embeddings |
| Graphs | NetworkX 3.1 | Graph algorithms |
| Visualization | Matplotlib 3.7.2 | Graph visualization |
| Frontend | HTML5/CSS3/JavaScript | Web interface |
| Containerization | Docker 20.10+ | Deployment |
| Orchestration | Docker Compose 1.29+ | Multi-container management |

## πŸ“Š Performance

### Processing Speed
| Operation | Time |
|-----------|------|
| App startup (cold) | 30-60s (first run, model download) |
| App startup (warm) | 2-3s |
| Small file upload (<5MB) | 5-10s |
| Medium file (5-20MB) | 15-30s |
| Large file (20-50MB) | 30-60s |
| Query response | 2-5s |
| Graph visualization | <1s |

### Resource Requirements
- **CPU**: 2 vCPU recommended
- **RAM**: 4GB minimum, 8GB recommended
- **Disk**: 10GB for models + data
- **Network**: 100Mbps+ for first setup

### Concurrent Processing
- Multiple documents: 3+ simultaneous uploads
- Multiple queries: 5+ concurrent requests
- UI responsiveness: Always responsive

## πŸ” Security

βœ… **API Key Protection**
- GROQ_API_KEY stored in environment (never in code)
- Never exposed to frontend
- Injected at runtime

βœ… **Data Privacy**
- Files stored server-side only
- No data sent to third parties (except Groq for queries)
- User queries only sent to Groq

βœ… **Container Security**
- Minimal Python slim base image
- No root user privileges required
- Health checks enabled
- Resource limits supported

βœ… **Input Validation**
- File type verification
- File size limits (50MB)
- Sanitized error messages

## πŸ› Troubleshooting

### "GROQ_API_KEY not configured"
**Solution**: 
- Check `.env` file has your API key
- In HF Spaces: Verify secret is added in Settings
- Restart the application

### Port 7860 already in use
**Solution**:
```bash
# Use different port
PORT=8000 python app.py

# Or find and stop the process
lsof -i :7860  # Mac/Linux
netstat -ano | findstr :7860  # Windows
```

### Graph doesn't load
**Solution**:
- Ensure document status is "ready" (wait 3-5 seconds)
- Check `data/graph_data/` folder exists
- Verify write permissions
- Check browser console (F12) for errors

### Chat not responding
**Solution**:
- Verify GROQ_API_KEY is set
- Check document status is "ready"
- Verify internet connectivity
- Check application logs

### Model download too slow
**Solution**:
- This is normal on first run (30-60 seconds)
- Model is cached after first download
- Subsequent starts are instant

## πŸ“ Project Structure

```
graph-rag-chatbot/
β”œβ”€β”€ app.py                      # Main Flask application
β”œβ”€β”€ templates/
β”‚   └── index.html             # Web interface
β”œβ”€β”€ requirements.txt            # Python dependencies
β”œβ”€β”€ Dockerfile                 # Container definition
β”œβ”€β”€ docker-compose.yml         # Docker Compose config
β”œβ”€β”€ .env.example              # Configuration template
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ uploads/              # Uploaded documents
β”‚   └── graph_data/           # Generated graphs
└── README.md                 # This file
```

## πŸš€ Deployment

### Local Deployment
See Quick Start section above

### Docker Deployment
```bash
docker build -t graph-rag-chatbot .
docker run -p 7860:7860 \
  -e GROQ_API_KEY=your_key \
  -v $(pwd)/data:/app/data \
  graph-rag-chatbot
```

### Hugging Face Spaces
This Space is already configured for HF Spaces deployment:
- SDK: Docker
- App file: app.py
- Secrets: GROQ_API_KEY (set in Space Settings)

### Cloud Deployment (AWS/Azure/GCP)
See `DEPLOYMENT_CHECKLIST.md` for detailed instructions

## πŸ’‘ Tips & Best Practices

βœ… **Performance**
- Use Docker Compose for easiest setup
- Test with CSV first (fastest processing)
- Larger chunks = better context but slower processing
- Smaller chunks = faster processing but less context

βœ… **Customization**
- Colors: Edit CSS in `index.html` (~line 50)
- Title: Edit HTML title and headers
- Upload limit: Change `MAX_CONTENT_LENGTH` in `app.py`
- Add more file types in `DocumentProcessor` class

βœ… **Production**
- Set `FLASK_ENV=production`
- Use Gunicorn instead of Flask dev server
- Enable HTTPS/SSL
- Add authentication if needed
- Monitor logs and metrics

## πŸ“ž Support

### Documentation Files
- **START_HERE.md** - Quick overview and FAQ
- **QUICKSTART.md** - 5-minute setup guide
- **TESTING.md** - Test cases and procedures
- **DEPLOYMENT_CHECKLIST.md** - Production readiness
- **PROJECT_STRUCTURE.md** - Architecture details

### Getting Help
1. Check the relevant documentation file above
2. Review the troubleshooting section
3. Check application logs: `docker-compose logs -f`
4. Verify API key is set correctly

## πŸ“ Known Limitations

1. **Storage**: Ephemeral (HF Spaces free tier)
   - Solution: Upgrade to persistent storage

2. **Processing Speed**: Single machine
   - Solution: Use GPU tier or distributed processing

3. **Concurrency**: Python GIL limitation
   - Solution: Use Gunicorn with multiple workers

4. **Graph Complexity**: Limited to 500 nodes for visualization
   - Solution: Implement hierarchical layouts

5. **API Rate Limits**: Groq free tier (30 req/min)
   - Solution: Upgrade Groq plan or implement caching

## 🎯 Future Enhancements

- [ ] User authentication
- [ ] Persistent database (PostgreSQL)
- [ ] Vector database (ChromaDB/Pinecone)
- [ ] Advanced graph algorithms
- [ ] Conversation memory
- [ ] Export to PDF reports
- [ ] Multi-language support
- [ ] WebSocket for real-time updates
- [ ] API rate limiting
- [ ] Advanced analytics

## πŸ“„ License

MIT License - Feel free to use for personal or commercial projects

## πŸ™ Credits

- **Framework**: Flask
- **LLM**: Groq API
- **Embeddings**: Hugging Face SentenceTransformers
- **Graphs**: NetworkX
- **Visualization**: Matplotlib
- **Deployment**: Docker

---

## Quick Links

| Link | Purpose |
|------|---------|
| [Groq Console](https://console.groq.com) | Get API key |
| [GitHub Issues](https://github.com/yourusername/graph-rag-chatbot/issues) | Report issues |
| [Documentation](./README.md) | Full docs |

---

**Created**: June 27, 2024  
**Version**: 1.0.0  
**Status**: βœ… Production Ready

Made with ❀️ for Knowledge Graph RAG applications