| title | Adaptive RAG |
|---|---|
| emoji | π€ |
| colorFrom | blue |
| colorTo | purple |
| sdk | docker |
| pinned | false |
A structure-aware Retrieval-Augmented Generation system that intelligently adapts its retrieval strategy based on how a document is organized and what kind of question is being asked.
π§ Demo temporarily unavailable β auth + frontend rewrite in progress
Standard RAG systems treat every document and every question the same way β fixed-size chunks, single retrieval method. This works poorly for documents with rich section structures (reports, manuals, legal docs) where context lives within clearly defined headings and subsections.
Adaptive RAG analyzes the document before indexing and dynamically selects the retrieval approach that best fits the document's structure and the nature of the question. A conceptual question ("how does X work?") over a well-structured document triggers section-aware hierarchical retrieval. A term-based lookup ("what is the value of Y?") triggers full hybrid search across all chunks. The result is more precise, context-grounded answers.
βββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client ββββββΆβ FastAPI β
βββββββββββββββ ββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β Ingestion Pipeline β
β Parse β Analyze β Chunk β Index β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β Dual Index β
β Qdrant (vectors) + BM25 (keys) β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β Adaptive Router β
β Profile + Question β Strategy β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β Hybrid Retrieval + RRF β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β Cross-Encoder Rerank β
ββββββββββββββββββ¬βββββββββββββββββ
β
ββββββββββββββββββΌβββββββββββββββββ
β LLM Answer (Gemini 2.5) β
βββββββββββββββββββββββββββββββββββ
When a document is uploaded the system:
- Parses the file using format-specific parsers (PDF via PyMuPDF, DOCX via python-docx, Markdown via markdown-it-py, plain TXT)
- Extracts structure β detects headings using font size + bold flags (PDF), paragraph styles (DOCX), or heading tokens (Markdown)
- Validates headings β filters false positives like figure captions, numbered lists, and single-word fragments
- Builds a document profile with metrics:
total_words,total_sections,heading_density,size_variance - Classifies the document along two dimensions:
- Structure quality:
high/medium/low - Length:
short(<2k words) /medium(2β10k) /long(>10k)
- Structure quality:
Based on the document profile, one of two chunking strategies is applied:
| Strategy | Triggered When | Behavior |
|---|---|---|
| Hierarchical | High structure | Sections <50w accumulated, 50β500w kept intact, >500w split with overlap |
| Fixed | Low/medium structure | All content split into 400-word chunks with 50-word overlap |
Each chunk carries metadata: section_title, parent_section, heading_level, page_number.
Every document gets its own isolated Qdrant collection (doc_{document_id}) and BM25 index:
- Vector index β chunks embedded with
all-MiniLM-L6-v2(384 dimensions, cosine distance) stored in Qdrant Cloud - Keyword index β BM25s index built over chunk text, serialized and stored in Supabase PostgreSQL alongside document metadata
When a question arrives the router examines two things:
Document profile (what kind of document is this?) Question type (what kind of answer is being sought?)
Question classification:
- Concept β contains "how", "why", "explain", "summarize", "describe", "what is", etc.
- Term/Technical β contains numbers, symbols, acronyms, or is a very short lookup query
Routing decision table:
| Document Structure | Question Type | Strategy |
|---|---|---|
| Short (any structure) | Any | Hybrid β full document search |
| Low / Medium structure | Any | Hybrid β section boundaries unreliable |
| High structure | Concept | Hierarchical + Hybrid β match sections by question keywords |
| High structure | Term / Technical | Hybrid β numbers and acronyms need full search |
| Manual override | Any | User-specified force_strategy |
Both indexes are queried in parallel:
- Vector search β top-10 semantically similar chunks from Qdrant
- Keyword search β top-10 BM25-ranked chunks
Results are merged using Reciprocal Rank Fusion:
score(chunk) = Ξ£ 1 / (rank + 60)
The fused top-10 are passed to the reranker.
A cross-encoder/ms-marco-MiniLM-L-6-v2 model scores each (question, chunk) pair directly. Top 4 chunks by reranker score are selected as the final context.
The top chunks are assembled into a context string (capped at MAX_CONTEXT_CHARS). The LLM is prompted to answer strictly from the provided context and respond with "I don't know" if the answer cannot be found. Default model is Gemini 2.5 Flash via LiteLLM (supports OpenAI as fallback).
| Layer | Technology | Purpose |
|---|---|---|
| Web Framework | FastAPI + Uvicorn | REST API |
| Frontend | Next.js 16, Tailwind CSS, shadcn/ui | UI |
| Vector DB | Qdrant Cloud | Semantic search |
| Database | Supabase PostgreSQL | Document metadata + BM25 storage |
| Embeddings | sentence-transformers/all-MiniLM-L6-v2 |
384-dim chunk vectors |
| Reranker | cross-encoder/ms-marco-MiniLM-L-6-v2 |
Relevance scoring |
| Keyword Search | BM25s | TF-IDF weighted full-text search |
| LLM | Gemini 2.5 Flash via LiteLLM | Answer generation |
| PDF Parsing | PyMuPDF | Text + font metadata extraction |
| DOCX Parsing | python-docx | Paragraph style extraction |
| Markdown Parsing | markdown-it-py | Token-based heading detection |
adaptive-rag/
βββ backend/
β βββ app/
β β βββ main.py # FastAPI app, route definitions
β β βββ database.py # Supabase connection, save/load documents
β β βββ api/
β β β βββ pipeline.py # Ingest and answer orchestration
β β βββ ingestion/
β β β βββ parser/parser.py # PDF, DOCX, MD, TXT parsers
β β β βββ chunker/chunker.py # Hierarchical and fixed chunking
β β β βββ structure_analyzer.py # Heading validation, document profiling
β β βββ indexing/
β β β βββ embedder.py # Sentence transformer embeddings
β β β βββ vector_store.py # Qdrant collection management
β β β βββ keyword_store.py # BM25 index build and search
β β βββ retrieval/
β β βββ router.py # Strategy selection logic
β β βββ retriever.py # Hybrid search + RRF merge
β β βββ reranker.py # Cross-encoder reranking
β βββ tests/
β β βββ test_parser.py
β βββ requirements.txt
β βββ Dockerfile
βββ frontend/
βββ app/ # Next.js App Router pages
βββ components/ # UI components (shadcn/ui)
βββ lib/api.ts # Backend API client
βββ netlify.toml # Netlify deployment config
Upload and index a document.
Request: multipart/form-data with a file field (PDF, DOCX, MD, TXT)
Response:
{
"message": "Document indexed successfully",
"document_id": "uuid-string",
"profile": {
"structure": "high",
"length_category": "medium",
"total_words": 4821,
"total_sections": 12,
"heading_density": 0.42
}
}Ask a question about an indexed document.
Request:
{
"question": "What are the key findings of the report?",
"document_id": "uuid-string",
"force_strategy": null
}force_strategy accepts "hybrid" or "hierarchical+hybrid" to override routing.
Response:
{
"answer": "The key findings include...",
"strategy_used": "hierarchical+hybrid",
"reason": "High-structure document with concept question β matched sections by keywords",
"confidence": "high",
"target_sections": ["Executive Summary", "Key Findings"],
"sources": [
{ "section": "Key Findings", "page": 3 },
{ "section": "Executive Summary", "page": 1 }
]
}Returns {"status": "ok"} if the service is running.
cd backend
pip install -r requirements.txt
uvicorn app.main:app --reloadCreate backend/.env:
QDRANT_URL=https://your-cluster.qdrant.io
QDRANT_API_KEY=your-qdrant-api-key
DB_HOST=aws-x-region.pooler.supabase.com
DB_PORT=5432
DB_NAME=postgres
DB_USER=postgres.your-project-ref
DB_PASSWORD=your-db-password
GOOGLE_API_KEY=your-google-api-key
LITELLM_MODEL=gemini/gemini-2.5-flash
GEMINI_FALLBACK_MODELS=gemini/gemini-2.5-flash-lite,gemini/gemini-2.0-flash-lite
MAX_CONTEXT_CHARS=8000If the primary model returns an overload-style error such as 429, 503, RESOURCE_EXHAUSTED, or "overloaded", the backend will automatically retry with the models listed in GEMINI_FALLBACK_MODELS from left to right.
GEMINI_FALLBACK_MODELS is used when LITELLM_MODEL starts with gemini/. The older LITELLM_FALLBACK_MODELS setting still works as a generic fallback for non-Gemini setups or for backward compatibility.
cd frontend
npm install
npm run devCreate frontend/.env.local:
NEXT_PUBLIC_API_URL=http://localhost:8000| Service | Platform | Config |
|---|---|---|
| Backend | Hugging Face Spaces (Docker) | backend/Dockerfile |
| Frontend | Netlify | frontend/netlify.toml |
| Vector DB | Qdrant Cloud | Managed |
| Database | Supabase | Managed |
- Not hardened for concurrent users β model instances are global singletons
- BM25 index is serialized as pickle in PostgreSQL (not suitable for large scale)
- First request after cold start is slow due to model loading (~700MB RAM required)
- Single-document-per-query design β no cross-document retrieval