Aigenthix/Graph_RAG7
๐ค 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 QueriesQuery 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) โญ
# 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:7860Option 2: Python Virtual Environment
# 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:7860Option 3: Hugging Face Spaces (Already Deployed)
If running on HF Spaces:
- The app is already running at this Space URL
- GROQAPIKEY is configured as a repository secret
- Just upload a document and start asking questions!
๐ Usage Guide
Uploading Documents
- Click the Upload Zone or drag & drop files
- Supported formats: PDF, CSV, TXT
- Maximum file size: 50MB
- Status progression:
- ๐ก queued โ Processing will start soon
- ๐ processing โ Building graph and embeddings
- ๐ข ready โ Ready for queries, graph available
Viewing Knowledge Graphs
- Once document status is "ready", click "๐ View Full Graph"
- Or switch to the "Knowledge Graph" tab
- Select the document from the dropdown
- Graph shows:
- ๐ต Blue nodes = Document chunks
- ๐ข Green nodes = Extracted entities (keywords)
- Edges = Relationships between chunks and entities
Asking Questions
- Select a document from the dropdown
- Type your question in the chat box
- Press Enter or click Send
- 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
{
"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
curl -X POST \
-F "files=@document.pdf" \
http://localhost:7860/api/uploadResponse:
{
"success": true,
"message": "โ
1 file(s) queued for processing",
"successful": 1,
"failed": 0,
"files": ["document.pdf"]
}POST /api/query
Query a document with RAG
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"query": "What is the main topic?",
"document": "example.pdf"
}' \
http://localhost:7860/api/queryResponse:
{
"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
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 modeCustomizable Parameters (in app.py)
Chunk Size (line ~66):
chunk_size=500, # Size of text chunks in characters
chunk_overlap=100 # Overlap between chunks for contextEmbedding Model (line ~27):
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):
model="mixtral-8x7b-32768", # Fast, powerful open model
max_tokens=500 # Response lengthSimilarity Threshold (line ~164):
if similarities[i] > 0.3 # Increase for stricter matching๐งช Testing
Run the test suite to verify all features:
# Upload a test document
# Check if status changes to "ready"
# View the knowledge graph
# Ask a question and verify response
# Delete the documentSee TESTING.md for 15+ comprehensive test cases with procedures.
๐ฆ Technology Stack
๐ Performance
Processing Speed
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
- GROQAPIKEY 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
"GROQAPIKEY not configured"
Solution:
- Check
.envfile has your API key - In HF Spaces: Verify secret is added in Settings
- Restart the application
Port 7860 already in use
Solution:
# Use different port
PORT=8000 python app.py
# Or find and stop the process
lsof -i :7860 # Mac/Linux
netstat -ano | findstr :7860 # WindowsGraph 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 GROQAPIKEY 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
docker build -t graph-rag-chatbot .
docker run -p 7860:7860 \
-e GROQ_API_KEY=your_key \
-v $(pwd)/data:/app/data \
graph-rag-chatbotHugging Face Spaces
This Space is already configured for HF Spaces deployment:
- SDK: Docker
- App file: app.py
- Secrets: GROQAPIKEY (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_LENGTHinapp.py - Add more file types in
DocumentProcessorclass
โ 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
- Check the relevant documentation file above
- Review the troubleshooting section
- Check application logs:
docker-compose logs -f - Verify API key is set correctly
๐ Known Limitations
- Storage: Ephemeral (HF Spaces free tier)
- Solution: Upgrade to persistent storage
- Processing Speed: Single machine
- Solution: Use GPU tier or distributed processing
- Concurrency: Python GIL limitation
- Solution: Use Gunicorn with multiple workers
- Graph Complexity: Limited to 500 nodes for visualization
- Solution: Implement hierarchical layouts
- 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
Created: June 27, 2024 Version: 1.0.0 Status: โ Production Ready
Made with โค๏ธ for Knowledge Graph RAG applications
