CoolFace
Apppublic

Aigenthix/Graph_RAG7

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
App README

๐Ÿค– 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. 1.The app is already running at this Space URL
  2. 2.GROQAPIKEY is configured as a repository secret
  3. 3.Just upload a document and start asking questions!

๐Ÿ“š Usage Guide

Uploading Documents

  1. 1.Click the Upload Zone or drag & drop files
  2. 2.Supported formats: PDF, CSV, TXT
  3. 3.Maximum file size: 50MB
  4. 4.Status progression:
  5. 5.๐ŸŸก queued โ†’ Processing will start soon
  6. 6.๐ŸŸ  processing โ†’ Building graph and embeddings
  7. 7.๐ŸŸข ready โ†’ Ready for queries, graph available

Viewing Knowledge Graphs

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

Asking Questions

  1. 1.Select a document from the dropdown
  2. 2.Type your question in the chat box
  3. 3.Press Enter or click Send
  4. 4.Bot responds with:
  5. 5.Answer based on document content
  6. 6.Source chunks used
  7. 7.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

ComponentTechnologyPurpose
BackendFlask 2.3.3Web framework
LLMGroq Mixtral 8x7bLanguage model for answers
EmbeddingsSentenceTransformersDocument/query embeddings
GraphsNetworkX 3.1Graph algorithms
VisualizationMatplotlib 3.7.2Graph visualization
FrontendHTML5/CSS3/JavaScriptWeb interface
ContainerizationDocker 20.10+Deployment
OrchestrationDocker Compose 1.29+Multi-container management

๐Ÿ“Š Performance

Processing Speed

OperationTime
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 response2-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

  • โ€”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 .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 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

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: 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_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. 1.Check the relevant documentation file above
  2. 2.Review the troubleshooting section
  3. 3.Check application logs: docker-compose logs -f
  4. 4.Verify API key is set correctly

๐Ÿ“ Known Limitations

  1. 1.Storage: Ephemeral (HF Spaces free tier)
  2. 2.Solution: Upgrade to persistent storage
  1. 1.Processing Speed: Single machine
  2. 2.Solution: Use GPU tier or distributed processing
  1. 1.Concurrency: Python GIL limitation
  2. 2.Solution: Use Gunicorn with multiple workers
  1. 1.Graph Complexity: Limited to 500 nodes for visualization
  2. 2.Solution: Implement hierarchical layouts
  1. 1.API Rate Limits: Groq free tier (30 req/min)
  2. 2.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

LinkPurpose
Groq ConsoleGet API key
GitHub IssuesReport issues
DocumentationFull docs

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

Made with โค๏ธ for Knowledge Graph RAG applications