Adaptive RAG is an intelligent, end-to-end Retrieval-Augmented Generation (RAG) system powered by agentic AI architecture. It combines dynamic query routing, intelligent document retrieval, and advanced LLM capabilities to provide accurate, context-aware answers to user queries.
The system intelligently adapts its retrieval strategy based on query type, utilizing indexed documents, general knowledge, or real-time web search to generate comprehensive responses. Built with a modular architecture using LangGraph for workflow orchestration and multiple storage backends for scalability.
- Adaptive Classification: Automatically routes queries to the most appropriate processing pipeline
- Three Query Types:
- Index: Queries answerable from uploaded documents
- General: Queries answerable with general knowledge
- Search: Queries requiring real-time web search
- Document Processing: Intelligent chunking and embedding of documents
- Vector Search: Fast similarity-based retrieval using Qdrant
- Relevance Grading: Automatic evaluation of retrieved documents
- Query Rewriting: Optimizes queries for better retrieval results
- Multi-Agent System: Specialized agents for different tasks
- ReAct Framework: Reasoning and Acting pattern for intelligent decision-making
- Tool Integration: Seamless integration with retrieval tools and web search
- MongoDB Backend: Persistent chat history and session management
- Session Tracking: Individual conversation contexts per user
- Memory Management: Full conversation context retention
- Streamlit Web App: Interactive chat interface with document upload
- File Support: PDF and TXT document uploads
- Real-time Feedback: Live chat with instant responses
- FastAPI Backend: High-performance REST API
- Async Operations: Non-blocking database and API calls
- RESTful Endpoints: Well-defined API contracts
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Interface β
β βββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββ β
β β Streamlit Web Application β β
β β β’ Chat Interface β β
β β β’ Document Upload (PDF, TXT) β β
β β β’ Session Management β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ β
ββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββ
β FastAPI Backend β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β REST API Endpoints β β
β β β’ POST /rag/query β β
β β β’ POST /rag/documents/upload β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β LangGraph Orchestration β
β βββββββββββ ββββββββββββ βββββββββββ ββββββββββββ β
β β Query ββ β Classify ββ β Router ββ β Pipeline β β
β β Analyze β β Query β β Output β β Exec β β
β βββββββββββ ββββββββββββ ββββοΏ½οΏ½ββββββ ββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββοΏ½οΏ½βββββββββββ¬ββββββββββββββββοΏ½οΏ½ββ¬βββββββββββββββββ
β β β β
βββββββββββ ββββββββββββ ββββββββββββββ ββββββββββββ
β Retrieverβ β General β β Web Search β β Response β
β (Index) β β LLM β β (Tavily) β β Generatorβ
βββββββββββ ββββββββββββ ββββββββββββββ ββββββββββββ
β β β β
ββββββββββββββββββββ¬βββββββββββββββββββ¬βββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββ
β Response to User β
βββββββββββββββββββββββββββββββββββ
- query_analysis: Analyzes and classifies incoming queries
- retriever: Retrieves relevant documents from vector store
- grade: Evaluates relevance of retrieved documents
- rewrite: Optimizes query for better retrieval results
- generate: Generates final response from context
- web_search: Performs real-time web search when needed
- general_llm: Provides general knowledge answers
AdaptiveRag/
βββ src/ # Main source code
β οΏ½οΏ½ββ main.py # FastAPI application entry point
β βββ api/ # API routes and endpoints
β β βββ routes.py # RAG query and document upload endpoints
β βββ config/ # Configuration management
β β βββ settings.py # Application settings
β β βββ prompts.yaml # LLM prompts and system messages
β βββ core/ # Core utilities
β β βββ config.py # Core configuration
β β βββ logger.py # Logging setup
β βββ db/ # Database layer
β β βββ mongo_client.py # MongoDB client initialization
β βββ llms/ # Language model integrations
β β βββ openai.py # OpenAI ChatGPT-4o initialization
β βββ memory/ # Chat memory management
β β βββ chat_history_mongo.py # MongoDB-backed chat history
β β βββ chathistory_in_memory.py # In-memory chat history (fallback)
β βββ models/ # Data models and schemas
β β βββ state.py # Graph state definition
β β βββ query_request.py # Query request schema
β β βββ grade.py # Relevance grade model
β β βββ route_identifier.py # Route classification model
β β βββ verification_result.py # Answer verification model
β βββ rag/ # RAG pipeline implementation
β β βββ graph_builder.py # LangGraph workflow construction
β β βββ nodes.py # Graph node implementations
β β βββ retriever_setup.py # Vector store and retriever setup
β β βββ document_upload.py # Document processing and upload
β β βββ reAct_agent.py # ReAct agent setup
β βββ tools/ # Utility tools and functions
β βββ common_tools.py # Shared utility functions
β βββ graph_tools.py # Graph routing and decision tools
β
βββ streamlit_app/ # Streamlit web application
β βββ home.py # Authentication and login page
β βββ pages/ # Multi-page application
β β βββ chat.py # Chat interface and document upload
β βββ utils/ # Streamlit utilities
β βββ api_client.py # Backend API client
β
βββ README.md # This file
βββ requirements.txt # Python dependencies
βββ CODE_STYLE_GUIDE.md # Code formatting standards
βββ QUICK_REFERENCE.md # Quick reference guide
βββ README_FORMATTING.md # Formatting documentation
βββ VERIFICATION_CHECKLIST.md # QA verification checklist
βββ FORMATTING_SUMMARY.md # Summary of code formatting
βββ DOCUMENTATION_INDEX.md # Documentation navigation index
http://localhost:8000
Process a RAG query and get intelligent response
POST /rag/query
Content-Type: application/json
{
"query": "What is the main topic of the document?",
"session_id": "user_session_123"
}Response:
{
"result": {
"type": "ai",
"content": "Based on the document, the main topic is..."
}
}Parameters:
query(string, required): User's question or querysession_id(string, required): Unique session identifier for conversation tracking
Status Codes:
200: Success400: Invalid request format500: Server error
Upload documents for RAG indexing
POST /rag/documents/upload
X-Description: Brief description of the document
Form Data:
- file: <PDF or TXT file>Response:
{
"status": true
}Headers:
X-Description(string, required): Document description for context
Parameters:
file(file, required): PDF or TXT file to upload (max size: depends on system)
Supported Formats:
- PDF (.pdf)
- Plain Text (.txt)
Status Codes:
200: Successfully uploaded and indexed400: Invalid file type or missing description500: Processing error
# System Requirements
- Python 3.9 or higher
- MongoDB (local or cloud)
- Qdrant vector database
- OpenAI API key
- Tavily API key (for web search)# Clone the repository
git clone https://github.com/HoneyTyagii/Adaptive-Rag.git
cd AdaptiveRag
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtCreate a .env file in the project root:
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
# Tavily Search Configuration
TAVILY_API_KEY=your_tavily_api_key_here
# Qdrant Configuration
QDRANT_URL=http://localhost:6333
QDRANT_API_KEY=your_qdrant_api_key
QDRANT_CODE_COLLECTION=code_documents
QDRANT_DOCS_COLLECTION=documents
# MongoDB Configuration
MONGODB_URL=mongodb://localhost:27017
MONGODB_DB_NAME=adaptive_ragStart FastAPI Backend:
# Terminal 1: Run FastAPI server
python -m uvicorn src.main:app --reload --host 0.0.0.0 --port 8000Start Streamlit Frontend:
# Terminal 2: Run Streamlit app
streamlit run streamlit_app/home.pyAccess the Application:
- Web Interface: http://localhost:8501
- API Documentation: http://localhost:8000/docs
- ReDoc Documentation: http://localhost:8000/redoc
Using the Web Interface:
- Navigate to http://localhost:8501
- Create account or login
- Upload documents in the sidebar
- Start chatting in the main chat area
Using cURL:
# Upload a document
curl -X POST http://localhost:8000/rag/documents/upload \
-H "X-Description: Sample document about Python" \
-F "file=@document.pdf"
# Query the RAG system
curl -X POST http://localhost:8000/rag/query \
-H "Content-Type: application/json" \
-d '{
"query": "Tell me about Python",
"session_id": "user_123"
}'Using Python:
import requests
# Query endpoint
response = requests.post(
"http://localhost:8000/rag/query",
json={
"query": "What is Python?",
"session_id": "user_123"
}
)
print(response.json())# Core application settings loaded from environment
OPENAI_API_KEY # OpenAI API authentication
TAVILY_API_KEY # Web search functionality
QDRANT_URL # Vector database endpoint
QDRANT_API_KEY # Vector database authentication
MONGODB_URL # Chat history databaseContains system prompts for:
- system_prompt: ReAct agent system instructions
- classify_prompt: Query classification logic
- grading_prompt: Document relevance evaluation
- rewrite_prompt: Query optimization
- generate_prompt: Response generation
The system routes queries based on classification:
Query Classification
βββ "index" β Use retriever (indexed documents)
βββ "general" β Use general LLM (common knowledge)
βββ "search" β Use web search (real-time information)
- Navigate to http://localhost:8000/docs
- Expand endpoint sections
- Click "Try it out"
- Enter test data
- Click "Execute"
Test 1: Simple Query
{
"query": "Hello, how are you?",
"session_id": "test_user_1"
}Test 2: Document-Based Query
{
"query": "What topics are covered in the uploaded document?",
"session_id": "test_user_1"
}Test 3: General Knowledge Query
{
"query": "What is machine learning?",
"session_id": "test_user_1"
}- Store API keys in
.envfile (never commit) - Use environment variables for sensitive data
- Implement rate limiting for production
- Validate all user inputs
- Use HTTPS in production
- Implement authentication/authorization
- Secure MongoDB with proper credentials
# Run development server with auto-reload
python -m uvicorn src.main:app --reload# Run with production settings
python -m uvicorn src.main:app --host 0.0.0.0 --port 8000 --workers 4Create Dockerfile and docker-compose.yml for containerized deployment.
- Document Chunking: Configurable chunk size (1000 chars, 150 overlap)
- Vector Search: Efficient similarity search with Qdrant
- Async Operations: Non-blocking I/O for better throughput
- Caching: Query results cached when applicable
- Batch Processing: Document processing in batches
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/YourFeature) - Make changes following CODE_STYLE_GUIDE.md
- Commit with descriptive messages (
git commit -m 'feat: Add YourFeature') - Push to your branch (
git push origin feature/YourFeature) - Open a Pull Request
- Follow PEP 8 standards
- Add docstrings to all functions
- Write unit tests for new features
- Update documentation
- Run linting:
flake8 src/
| Component | Technology | Version |
|---|---|---|
| LLM Framework | LangChain | ~0.3.27 |
| Workflow Orchestration | LangGraph | ~0.5.4 |
| Web Framework | FastAPI | Latest |
| ASGI Server | Uvicorn | Latest |
| UI Framework | Streamlit | Latest |
| Vector Database | Qdrant/FAISS | Latest |
| Chat Database | MongoDB/InMemory | Latest |
| Document Processing | LangChain Community | ~0.3.27 |
| LLM Provider | OpenAI | ~0.3.28 |
| Web Search | Tavily | Latest |
| Async DB | Motor | Latest |
| Data Validation | Pydantic | ~2.11.7 |
- CODE_STYLE_GUIDE.md - Comprehensive coding standards
- QUICK_REFERENCE.md - Quick patterns and templates
- README_FORMATTING.md - Code formatting overview
- VERIFICATION_CHECKLIST.md - QA checklist
- DOCUMENTATION_INDEX.md - Full documentation index
Q: How do I upload multiple documents?
A: Upload one document at a time through the Streamlit interface. Each upload creates a new indexed collection.
Q: What's the maximum file size?
A: Limited by system memory and Qdrant storage. Typical limit is 100MB per file.
Q: Can I use different LLM providers?
A: Currently configured for OpenAI. You can modify src/llms/openai.py to use other providers.
Q: How is conversation history stored?
A: MongoDB stores all chat messages with timestamps and session IDs for full context retention.
Q: Can I run this without web search?
A: Yes, remove Tavily dependency. Queries will use index or general LLM only.
For issues, questions, or suggestions:
- Open an Issue
- Check existing documentation
- Review the code comments
- Built with LangChain and LangGraph
- Vector search powered by Qdrant
- LLM capabilities by OpenAI
- Web search by Tavily
- UI powered by Streamlit
- Thanks to the open-source community
This project is licensed under the MIT License - see the LICENSE file for details.
Honey Tyagi
- GitHub: @HoneyTyagii
- Project: Adaptive RAG
- β Core RAG pipeline implemented
- β Document upload and indexing
- β Query routing (index/general/search)
- β MongoDB chat history
- β Streamlit web interface
- β Code formatted and documented
- π Production ready
- Enhanced context management
- Multi-language support
- Performance benchmarks
- Extended LLM provider support
- Advanced authentication
- Real-time collaboration
- Analytics dashboard
- Cost optimization
Last Updated: April 6, 2026
Status: β
Production Ready
Documentation: β
Comprehensive