A Hybrid Retrieval-Augmented Generation (RAG) chatbot API that combines FAISS vector search, BM25 lexical ranking, and fuzzy matching for intelligent document retrieval and LLM-powered summarization.
- Hybrid Search Scoring: Combines embedding-based (E5), BM25 lexical, and fuzzy matching scores
- Field-Aware Retrieval: Automatically selects relevant fields based on query semantics
- Automatic Query Expansion: Uses concept embedding clustering to expand queries intelligently
- Cross-Encoder Re-ranking (Optional): High-accuracy re-ranking for improved relevance
- Parallel Field Search: Multi-threaded FAISS index querying for fast retrieval
- LLM Summarization: Ollama-based query intent summarization
- REST API: FastAPI endpoints for easy integration
- Performance Metrics: Detailed execution time breakdown per component
Query Input
↓
[Query Expansion] (concept-based)
↓
[Field Selection] (embedding + keyword overlap)
↓
[FAISS Parallel Retrieval] (per-field vector search)
↓
[Hybrid Scoring] (embedding + BM25 + fuzzy)
↓
[Optional Cross-Encoder Re-ranking]
↓
[LLM Summarization] (Ollama)
↓
Structured Results + Recommendations
- Python 3.8+
- CUDA 11.8+ (for GPU acceleration, optional)
- Ollama (for LLM summarization)
-
Clone the repository
git clone https://github.com/HariP-git/Hariprasath-Infynd-chatbot.git cd Hariprasath-Infynd-chatbot -
Create a virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Install Ollama (for LLM features)
- Download from ollama.ai
- Pull the model:
ollama pull tinyllama
The system expects data in the following structure:
data/
├── vector/
│ ├── field1.faiss
│ ├── field2.faiss
│ └── ...
├── metadata.json
├── field_embeddings.json (auto-generated)
├── field_keywords.json (auto-generated)
├── concept_terms.json (auto-generated)
└── concept_embeddings.json (auto-generated)
Building FAISS Indexes:
python scripts/build_faiss_incremental.pyStart the FastAPI server:
python app.py --serveServer runs on http://localhost:8000
POST /query
Request:
{
"query": "What are the system requirements?",
"mode": "fast"
}Response:
{
"summary": "System needs at least 8GB RAM and Python 3.8+",
"results": {
"requirements": ["8GB RAM", "Python 3.8+"]
},
"recommendations": {
"requirements": ["8GB RAM", "Python 3.8+", "CUDA 11.8+ (optional)"]
},
"model_used": "intfloat/e5-large-v2 + BM25",
"execution_time_seconds": {
"embedding": 0.025,
"field_selection": 0.008,
"retrieval": 0.015,
"rerank": 0.0,
"bm25_and_hybrid": 0.012,
"llm": 0.420,
"total": 0.480
}
}fast(default): Quick retrieval without query expansionhigh: Enhanced retrieval with query expansion and cross-encoder re-ranking (if available)
# Single query test
python app.py --query "What is the installation process?" --mode fast
# With high accuracy mode
python app.py --query "system requirements" --mode highEdit app.py to customize:
# Model Selection
EMBED_MODEL = "intfloat/e5-large-v2" # Embedding model
OLLAMA_MODEL = "tinyllama" # LLM for summarization
# Search Parameters
TOP_K = 50 # Results per field
HIGH_MATCH_SCORE = 0.90 # Strong match threshold
MEDIUM_MATCH_SCORE = 0.60 # Medium match threshold
# Hybrid Weights (must sum to 1.0)
WEIGHT_EMB = 0.6 # Embedding score
WEIGHT_BM25 = 0.25 # BM25 lexical score
WEIGHT_FUZZY = 0.15 # Fuzzy match score
# Field Selection
FIELD_SIM_THRESHOLD = 0.35 # Min semantic similarity
MAX_RELEVANT_FIELDS = 12 # Max fields to search
# Performance
MAX_THREAD_POOL = 8 # Parallel threads
RECOMMEND_LIMIT_PER_FIELD = 6 # Recommendations per field- Per-field vector indexes using
intfloat/e5-large-v2embeddings - Normalized L2 distances for cosine similarity
- Lightweight implementation without external dependencies
- Term frequency-inverse document frequency scoring
- IDF calculation with Okapi BM25 formula
- Embedding similarity to field names
- Keyword overlap detection
- Automatic fallback to top fields
- Weighted combination of three scoring methods:
- Embedding: Semantic similarity (60%)
- BM25: Lexical matching (25%)
- Fuzzy: String similarity via RapidFuzz (15%)
- Concept term extraction from metadata
- Embedding-based nearest neighbor search
- Automatic query augmentation (high mode)
- Ollama integration for intent summarization
- Timeout protection (20 seconds default)
- Graceful fallback to heuristic summary
Typical execution times (on moderate hardware):
| Component | Time (ms) |
|---|---|
| Embedding | 25-50 |
| Field Selection | 5-15 |
| FAISS Retrieval | 10-30 |
| BM25 Scoring | 10-20 |
| LLM Summarization | 300-500 |
| Total | ~500-1000 |
See requirements.txt for full dependencies:
- FastAPI 0.115.2 - Web framework
- Uvicorn 0.32.0 - ASGI server
- Sentence-Transformers 3.1.1 - Embeddings
- PyTorch ≥2.0.0 - Deep learning backend
- FAISS 1.8.0 - Vector search
- NumPy ≥1.26.0 - Numerical computing
- RapidFuzz 3.10.0 - Fuzzy matching
- ijson 3.2.3 - JSON streaming
- Pydantic ≥2.7.0 - Data validation
.
├── app.py # Main RAG API (FastAPI)
├── fallback.py # Alternative implementation
├── requirements.txt # Python dependencies
├── scripts/
│ └── build_faiss_incremental.py # Index building script
├── data/
│ ├── vector/ # FAISS index files
│ ├── metadata.json # Field-value metadata
│ └── ...
└── README.md # This file
- Ensure
data/vector/contains.faissfiles - Run
scripts/build_faiss_incremental.pyto generate indexes
- Check Ollama is running:
ollama serve - Increase
OLLAMA_TIMEOUTin config (default: 20s) - Summaries will fallback to heuristic if Ollama fails
- Use
mode=fastinstead ofhigh - Reduce
TOP_Kfor faster retrieval - Ensure GPU is available (
torch.cuda.is_available())
- Reduce batch size in
build_faiss_incremental.py - Use
faiss-cpuinstead offaiss-gpu - Reduce embedding model (
e5-base-v2instead ofe5-large-v2)
The system automatically detects and uses cross-encoders in high mode:
python app.py --query "complex query" --mode highBoost specific fields by updating FIELD_WEIGHTS:
FIELD_WEIGHTS = {
"title": 1.2,
"description": 1.0,
"tags": 0.8
}from scripts.build_faiss_incremental import build_fieldwise_index
build_fieldwise_index()- Use GPU: Ensure CUDA is installed and
torch.cuda.is_available()returnsTrue - Batch Processing: Query multiple inputs in parallel using ThreadPoolExecutor
- Caching: Field embeddings and keywords are cached in JSON files
- Field Filtering: Increase
FIELD_SIM_THRESHOLDto search fewer fields - Smaller Models: Use
e5-base-v2ore5-small-v2for faster inference
For issues, questions, or suggestions, please open an issue on GitHub.
Made with ❤️ for intelligent information retrieval