A robust, production-ready, completely offline RAG (Retrieval-Augmented Generation) chatbot for document Q&A, built with React frontend, FastAPI backend, ChromaDB, Ollama with Mistral, and Redis caching. Designed for governmental and sensitive environmentsβzero internet required after initial setup.
π Now featuring advanced AI capabilities from RAGFlow integration including Agentic RAG, Multi-OCR with Layout Analysis, Web Search, Anti-Hallucination, and Cross-Language Support.
- Agentic RAG System: Multi-agent architecture with query analysis, search, reasoning, and synthesis agents
- Intelligent query classification and routing
- Advanced reasoning with confidence scoring
- Tool calling capabilities for complex operations
- Performance tracking and metrics
- Enhanced Multi-OCR with Layout Analysis: Advanced document processing pipeline
- Layout-aware text extraction with table detection
- Form field recognition and document structure analysis
- Multi-engine OCR with consensus validation
- Quality scoring for layout elements
- Web Search Integration: Real-time web search capabilities via Tavily API
- Hybrid search combining local documents with web results
- News and academic search capabilities
- Source attribution for web results
- Intelligent caching for web search results
- Advanced Anti-Hallucination System: Comprehensive fact verification
- Multi-type hallucination detection
- Source consistency checking
- Confidence scoring and validation
- Automatic correction suggestions
- Cross-Language Query Support: Multi-language processing for 11+ languages
- Intelligent language detection
- Query translation and processing
- Multi-language embedding models
- Cross-language search capabilities
- Template-Based Chunking: Intelligent document processing
- Semantic and structural chunking strategies
- Document-type specific templates
- Explainable chunking decisions
- Quality metrics and visualization
- Dynamic Query Routing: Queries are automatically classified and routed to relevant documents
- "Section 304" β Law documents
- "Electronegativity of chlorine" β Chemistry documents
- "Prayer times" β Religious documents
- Hybrid Search: Combines vector similarity with keyword matching for better results
- Cross-encoder Reranking: Advanced reranking using sentence-transformers for improved accuracy
- Source Attribution: Every response includes source information (document, page, section)
- Domain Filtering: UI allows filtering queries by specific domains
- Health Monitoring: Real-time system metrics and service status
- Complete Offline Operation: All AI models and services run locally with zero external dependencies
- Multi-Document Conflict Resolution: Detects and handles conflicting information across documents
- Session Isolation: Prevents context contamination between different queries
- Anti-Hallucination: Strict fact verification and source citation
- Confidence Scoring: Ranks sources by relevance and reliability
- Multi-format Document Support: Upload and query PDF, DOCX, CSV, and Excel files
- Dynamic Query Routing: Automatically route queries to relevant documents based on domain classification
- Hybrid Search: Combines dense vector search with sparse keyword matching for improved accuracy
- Cross-encoder Reranking: Uses sentence-transformers for advanced result reranking
- Source Attribution: Display sources with page numbers, sections, and document titles
- Domain Filtering: Filter queries by domain (law, chemistry, physics, etc.) for targeted results
- Real-time Embedding Generation: Instant vector embeddings using Ollama's nomic-embed-text model
- Intelligent Context Retrieval: Advanced semantic search with context expansion
- Conversation Memory: Persistent chat history with context preservation
- Knowledge Base Management: Add, remove, and manage documents dynamically
- React Frontend: Modern, responsive UI built with TypeScript and Tailwind CSS
- Real-time Chat Interface: Streaming responses with typing indicators
- Responsive Design: Sidebar is collapsible on mobile, chat bubbles and input area adapt to all screen sizes, and a floating scroll-to-bottom button appears when needed.
- Document Upload: Drag-and-drop file upload with progress tracking
- Conversation Management: Save, load, export, delete, and robustly rename chat histories (renames update everywhere in real time)
- Settings Panel: Configure chunk sizes and overlap in the frontend, which are respected by the backend for new uploads
- Overlay During Streaming: The chat area is blanked out with a loading overlay while the LLM is generating a response
- UI/UX Polish: Rounded corners, subtle shadows, smooth transitions, and improved spacing throughout
- Dark/Light Theme: Toggle between themes with persistent preferences
- Redis Caching: High-performance caching for embeddings, queries, and chat history
- FastAPI Backend: High-performance async API with automatic documentation
- Health Monitoring: Real-time system metrics and service health checks
- Docker Support: Containerized deployment with docker-compose
- Real-time Processing: Streaming responses and live status updates
- Error Handling: Comprehensive error boundaries and user feedback
- Production Ready: Supports 100-1,000+ documents with intelligent routing
- Completely Offline: Zero internet required after initial setup
- Local Data Storage: All data stored locally in ChromaDB and file system
- Local AI Models: All LLM, embedding, and reranking models run locally
- No External APIs: No cloud services or external dependencies (except optional web search)
- Large File Support: Up to 150MB file uploads
- CORS Protection: Secure cross-origin request handling
- Input Validation: Comprehensive file and input validation
- Docker and Docker Compose (for containerized deployment)
- 16-32GB RAM (recommended for large document collections)
- 50GB+ disk space (for models and data)
- NVIDIA GPU (optional, for faster LLM inference)
# Clone the repository
git clone <repository-url>
cd RAG-CHATBOT-XOR
# Create environment file
cp .env.example .env# Install Python dependencies (all local, no external APIs)
pip install -r requirements.txt
# Pre-download sentence-transformers model (recommended for full offline use)
python -c "from sentence_transformers import CrossEncoder; CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')"
# Pull Ollama models (stored locally in Docker volumes)
docker run --rm -v ollama_data:/root/.ollama ollama/ollama:latest ollama pull mistral:latest
docker run --rm -v ollama_data:/root/.ollama ollama/ollama:latest ollama pull nomic-embed-text# Build and start all services
docker-compose up --build -d
# Verify deployment
curl http://localhost:8000/health/detailed# Disconnect from internet (optional test)
# All features should work without any external dependencies
# Test endpoints
curl http://localhost:8000/health
curl http://localhost:8000/domainsAfter setup, the system runs completely offline with:
- β Local LLM: Mistral 7B via Ollama (default)
- β Local Embeddings: nomic-embed-text via Ollama
- β Local Reranking: sentence-transformers cross-encoder
- β Local Vector DB: ChromaDB with persistent storage
- β Local Caching: Redis with persistent storage
- β No External APIs: Zero cloud dependencies (except optional web search)
- β No Internet Required: All models and services local
- β Robust Error Handling: Graceful fallbacks for document processing issues
Figure: Modern architecture with React frontend, FastAPI backend, Redis caching, ChromaDB vector store, and Ollama LLM with advanced AI features.
-
Frontend (React + TypeScript):
- Modern UI with Tailwind CSS
- Real-time chat interface
- Document upload and management
- Conversation history
- Settings and configuration
-
Backend (FastAPI):
- RESTful API endpoints
- Document processing and chunking
- Vector store operations
- LLM integration
- Redis caching layer
- Advanced AI features (Agentic RAG, Multi-OCR, Web Search, etc.)
-
Data Layer:
- ChromaDB: Persistent vector storage
- Redis: High-performance caching
- File System: Document storage and chat logs
-
AI/ML Layer:
- Ollama: Local LLM inference and embeddings
- Mistral 7B: Advanced language model (default)
- nomic-embed-text: High-quality embeddings
- Agentic RAG: Multi-agent architecture
- Multi-OCR: Advanced document processing
- Web Search: Real-time information retrieval
- Anti-Hallucination: Fact verification system
- Cross-Language: Multi-language support
.
βββ frontend/ # React TypeScript frontend
β βββ src/
β β βββ components/ # Reusable UI components
β β β βββ SourceDisplay.tsx # Source attribution UI
β β β βββ DomainFilter.tsx # Domain filtering UI
β β βββ pages/ # Page components
β β βββ contexts/ # React contexts
β β βββ main.tsx # App entry point
β βββ package.json # Frontend dependencies
β βββ vite.config.ts # Vite configuration
β βββ Dockerfile # Frontend container
βββ backend/ # FastAPI backend
β βββ api.py # Main API endpoints with health monitoring
βββ rag_core/ # Core RAG logic with advanced features
β βββ agentic_rag.py # Multi-agent RAG system
β βββ multi_ocr.py # Advanced OCR with layout analysis
β βββ web_search.py # Web search integration
β βββ anti_hallucination.py # Fact verification system
β βββ language_processor.py # Cross-language support
β βββ chunking_templates.py # Intelligent document chunking
β βββ conversation_manager.py # Advanced conversation management
β βββ vectorstore.py # ChromaDB operations with hybrid search
β βββ document.py # Document processing with semantic chunking
β βββ llm.py # LLM integration with Mistral
β βββ reranker.py # Cross-encoder reranking
β βββ utils.py # Query/document classification
β βββ redis_cache.py # Redis caching
β βββ history.py # Chat history management
β βββ config.py # Configuration management
βββ demo-rag-chroma/ # ChromaDB persistent storage
βββ log/ # Application logs and chat history
βββ requirements.txt # Python dependencies (all local)
βββ docker-compose.yml # Complete offline deployment
βββ .env # Environment configuration
βββ log/ # Chat history and logs
βββ assets/ # Branding and architecture images
βββ docker-compose.yml # Multi-service deployment
βββ Dockerfile # Backend container
βββ requirements.txt # Python dependencies
βββ .env # Environment configuration
βββ README.md
-
Clone and setup:
git clone https://github.com/QuantumBreakz/PITB-RAG.git cd PITB-RAG cp .env.example .env # Edit .env as needed
-
Start all services:
docker-compose up -d
-
Access the application:
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Note: The chat UI is now fully responsive and beautiful, with a collapsible sidebar, floating scroll-to-bottom button, and real-time chunk size/overlap settings.
-
Backend Setup:
python3 -m venv venv source venv/bin/activate pip install -r requirements.txt cp .env.example .env # Edit .env configuration
-
Frontend Setup:
cd frontend npm install -
Start Services:
# Terminal 1: Backend cd backend && uvicorn api:app --host 0.0.0.0 --port 8000 --reload # Terminal 2: Frontend cd frontend && npm run dev # Terminal 3: Redis (if not using Docker) redis-server
-
Access the application:
- Frontend: http://localhost:5173
- Backend API: http://localhost:8000
| Variable | Description | Default |
|---|---|---|
| Ollama Configuration | ||
| OLLAMA_BASE_URL | Ollama server URL | http://localhost:11434 |
| OLLAMA_EMBEDDING_MODEL | Embedding model name | nomic-embed-text:latest |
| OLLAMA_LLM_MODEL | LLM model name | mistral:latest |
| Application Settings | ||
| MAX_FILE_SIZE | Max file size in bytes | 157286400 (150MB) |
| CHUNK_SIZE | Document chunk size | 400 |
| CHUNK_OVERLAP | Chunk overlap | 100 |
| N_RESULTS | Number of results to retrieve | 10 |
| Database Configuration | ||
| CHROMA_DB_PATH | ChromaDB storage path | ./demo-rag-chroma |
| CHROMA_COLLECTION_NAME | ChromaDB collection name | pitb_rag_app_demo |
| Redis Configuration | ||
| REDIS_HOST | Redis server host | localhost |
| REDIS_PORT | Redis server port | 6379 |
| REDIS_DB | Redis database number | 0 |
| CACHE_TTL | Cache time-to-live (seconds) | 3600 |
| Logging | ||
| LOG_LEVEL | Logging level (DEBUG, INFO, etc.) | INFO |
| LOG_FILE | Log file path | pitb_rag_app.log |
POST /upload- Upload and process documentsGET /documents- List all documents in knowledge baseDELETE /documents/{filename}- Remove specific document
POST /query- Standard RAG query with contextPOST /query/stream- Streaming query responseGET /health- Health check endpointGET /test_vectorstore- Test vector store connectivity
POST /agentic/query- Agentic RAG query with multi-agent processingPOST /agentic/stream- Streaming agentic RAG responsePOST /ocr/process- Multi-OCR document processingPOST /ocr/layout- Layout analysis for documentsPOST /web/search- Web search integrationPOST /anti-hallucination/validate- Fact verificationPOST /language/detect- Language detectionPOST /language/translate- Text translationPOST /chunking/template- Template-based chunking
GET /history/list- List all conversationsGET /history/get/{conv_id}- Get specific conversationPOST /history/save- Save conversationDELETE /history/delete/{conv_id}- Delete conversationGET /history/export/{conv_id}- Export conversation as JSON
POST /reset_kb- Clear entire knowledge base
- Multi-Agent Architecture: Query analyzer, search agent, reasoning agent, and synthesis agent
- Intelligent Query Classification: Automatic routing to appropriate data sources
- Advanced Reasoning: Complex problem-solving with confidence scoring
- Tool Calling: Execute specific operations based on query requirements
- Performance Tracking: Real-time metrics and optimization
- Layout-Aware Processing: Document structure detection and analysis
- Table Detection: Automatic identification and extraction of tabular data
- Form Field Recognition: Intelligent form processing and field extraction
- Multi-Engine Consensus: Multiple OCR engines with validation
- Quality Scoring: Confidence metrics for extracted content
- Real-time Information: Access to current web data via Tavily API
- Hybrid Search: Combine local documents with web results
- News Search: Latest news and current events
- Academic Search: Research papers and scholarly content
- Source Attribution: Proper citation of web sources
- Fact Verification: Comprehensive validation of generated responses
- Source Consistency: Cross-reference information across sources
- Confidence Scoring: Reliability metrics for responses
- Contradiction Detection: Identify conflicting information
- Automatic Correction: Suggest improvements for uncertain responses
- Multi-Language Detection: Support for 11+ languages
- Query Translation: Automatic translation of queries
- Cross-Language Search: Search across documents in different languages
- Language-Specific Processing: Optimized handling for each language
- Translation Caching: Performance optimization for repeated translations
- Intelligent Chunking: Document-type specific processing strategies
- Semantic Chunking: Context-aware text segmentation
- Structural Chunking: Layout-based document organization
- Quality Metrics: Chunking effectiveness evaluation
- Visualization: Chunking decision explanations
- Instant Processing: Documents are chunked and embedded immediately upon upload
- Batch Processing: Efficient handling of large documents with configurable batch sizes
- Retry Logic: Automatic retry with exponential backoff for failed operations
- Progress Tracking: Real-time feedback during document processing
- Semantic Search: Advanced vector similarity search using nomic-embed-text
- Context Expansion: Automatically includes neighboring chunks for better context
- Keyword Boosting: Prioritizes chunks containing important keywords
- File Filtering: Query specific documents or search across all
- Embedding Cache: Caches document embeddings to avoid reprocessing
- Query Cache: Caches query results for improved response times
- Chat History Cache: Fast access to conversation data
- Configurable TTL: Adjustable cache expiration times
- Responsive Design: Works seamlessly on desktop and mobile
- Real-time Updates: Live status indicators and progress bars
- Error Boundaries: Graceful error handling with user-friendly messages
- Loading States: Smooth loading animations and feedback
- Theme Support: Dark/light mode with persistent preferences
# Build and start all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down- Frontend: React app served by Vite dev server
- Backend: FastAPI with uvicorn ASGI server
- Ollama: Local LLM and embedding service
- Redis: Caching and session storage
- ChromaDB: Persistent vector storage
./logβ Chat history and application logs./demo-rag-chromaβ ChromaDB data persistence./assetsβ Static assets and branding
Frontend not connecting to backend:
- Check if backend is running on port 8000
- Verify CORS settings in backend/api.py
- Check browser console for network errors
Embedding generation fails:
- Ensure Ollama is running and accessible
- Verify embedding model is installed:
ollama pull nomic-embed-text:latest - Check Ollama logs for errors
Redis connection issues:
- Verify Redis server is running:
redis-cli ping - Check Redis host/port configuration in .env
- Ensure Redis is accessible from backend container
Document upload fails:
- Check file size limits in .env
- Verify supported file types (PDF, DOCX, CSV, Excel)
- Check backend logs for processing errors
Slow response times:
- Increase Redis cache TTL
- Optimize chunk size and overlap settings
- Use smaller embedding model for faster processing
Memory issues:
- Reduce batch size in vectorstore.py
- Limit concurrent document processing
- Monitor system resources during large uploads
--- Live stream: cd deployment && docker compose logs -f backend Recent only: cd deployment && docker compose logs --tail=200 backend
New File Types:
- Extend
DocumentProcessorinrag_core/document.py - Add file type detection and processing logic
- Update frontend file type validation
New Vector Stores:
- Implement new
VectorStoreclass inrag_core/vectorstore.py - Add configuration options in
rag_core/config.py - Update API endpoints to use new store
New LLM Providers:
- Extend
LLMHandlerinrag_core/llm.py - Add provider-specific API integration
- Update configuration and environment variables
- Frontend: React with TypeScript, Tailwind CSS, Vite
- Backend: FastAPI with async/await, Pydantic models
- Core Logic: Modular Python packages in
rag_core/ - Data Layer: ChromaDB for vectors, Redis for caching, file system for storage
- Fully Offline: No internet required after initial setup
- Local Data: All embeddings, documents, and chat history stored locally
- No Telemetry: No data sent to external services
- Input Validation: Comprehensive validation of all inputs
- CORS Protection: Secure cross-origin request handling
- Environment Variables: Sensitive configuration via .env files
MIT License
- React - Frontend framework
- FastAPI - Backend framework
- Ollama - Local LLM inference
- Mistral AI - Advanced language model
- ChromaDB - Vector database
- Redis - Caching layer
- Tailwind CSS - Styling framework
- Vite - Build tool
- Frontend: Set
VITE_API_URLinfrontend/.envto your backend URL (e.g.,https://your-backend-domain.com). - Backend: Set
FRONTEND_ORIGINin the backend environment (or Dockerfile) to your frontend URL (e.g.,https://your-frontend-domain.com).
- Both frontend and backend Dockerfiles support these environment variables for deployment.
- See each Dockerfile for usage and example ENV lines.
- Build and run backend with correct
FRONTEND_ORIGIN. - Build and run frontend with correct
VITE_API_URL. - Ensure Ollama and ChromaDB are running and accessible.
- Access the app via your frontend URL.
See frontend/README.md and backend/Dockerfile for more details.
Available models through Ollama:
mistral:latest(7B) - Default - Advanced reasoning and instruction followingllama3.2:3b(3B) - Fast and efficientllama2(7B) - Balanced performancellama2:13b(13B) - Higher quality, more resource intensivecodellama(Code specialized) - Programming and technical tasksneural-chat(7B) - Conversational AI optimized
- β Agentic RAG: Multi-agent architecture with intelligent query processing
- β Multi-OCR: Advanced document processing with layout analysis
- β Web Search: Real-time information retrieval via Tavily API
- β Anti-Hallucination: Comprehensive fact verification system
- β Cross-Language: Multi-language support for 11+ languages
- β Template Chunking: Intelligent document processing strategies
- β Conversation Management: Advanced analytics and insights
- π‘ Advanced Reranking: Enhanced result ranking (partially implemented)
- π‘ Performance Monitoring: Comprehensive analytics (partially implemented)
- π΄ MCP Support: Model Context Protocol (planned)