DivinityAI Architecture & Performance Benchmark: Building a Corpus-Locked Islamic RAG System
- Zero-Hallucination Guarantee: Strict corpus-lock policy refuses answers not grounded in King Fahd Uthmani Quran & 6 canonical Hadith collections.
- Five-Path Intent Router: Classifies queries (Quran, Hadith, Fiqh, Calculation, Off-Domain) with confidence gating before retrieval.
- Hybrid Retrieval: Combines BM25 sparse search on normalized Arabic with BGE-M3 dense embeddings via Reciprocal Rank Fusion.
- 4-Tier Citation Verification: Deterministic chain (Exact Match → Normalized → Levenshtein → Semantic) validates every inline citation pre-output.
- Production Stack: Django ASGI/DRF, React 19/Vite, ChromaDB, Ollama (embeddinggemma), OpenRouter (Gemini 2.5 Flash), Groq (Llama 3.3 70B).

The Engineering Challenge: Why DivinityAI Was Architected
General-purpose LLMs exhibit catastrophic failure rates when handling Islamic primary sources. They fabricate surah:ayah coordinates, conflate distinct Hadith narrations across Sahih al-Bukhari and Sahih Muslim, and synthesize jurisprudential rulings (Fiqh) with no chain of transmission (isnad). In a domain where a single digit error in a verse reference invalidates the answer, probabilistic generation is insufficient.
DivinityAI solves this by inverting the standard RAG paradigm: retrieval precedes and constrains generation. If the locked corpus—comprising the King Fahd Complex Uthmani Quran text and the six canonical Hadith collections—does not contain the evidence, the system refuses to answer. This “corpus-lock” architecture transforms the LLM from a knowledge store into a reasoning engine over verified evidence.
Core Architecture & Technical Stack Deep-Dive
System Topology
The deployment follows a modular, service-oriented topology orchestrated via Docker Compose:
┌──────────────────────┐
│ React 19 / Vite │ ← Tailwind CSS v4, RTL/Uthmani Optimized
└──────────┬───────────┘
│ HTTPS /api/v1/query
▼
┌──────────────────────┐
│ Django ASGI / DRF │ ← Pipeline Orchestrator, Audit Middleware
└──────────┬───────────┘
│
┌───────┼───────┐
▼ ▼ ▼
┌─────┐ ┌───────┐ ┌────────────┐
│Chroma│ │BM25 │ │ Ollama │
│DB │ │Index │ │embeddinggemma│
│(8040)│ │(Disk) │ │(11434) │
└─────┘ └───────┘ └────────────┘
│
▼ (Generation)
┌──────────────────────┐
│ OpenRouter / Groq │ ← Gemini 2.5 Flash / Llama 3.3 70B
└──────────────────────┘
Data Layer: ChromaDB & Sparse Indices
- ChromaDB Collections: Two isolated collections—
quran_collection(6,236 verses, Uthmani + translation metadata) andhadith_collection(canonical 6 books, Arabic matn + isnad + grades). - Embedding Model:
embeddinggemma(via Ollama) generates 768-dim dense vectors optimized for multilingual semantic similarity. - BM25 Sparse Index:
rank_bm25indexes normalized Arabic tokens (diacritic stripping, alef/ya normalization) for exact lexical matching of Quranic roots and Hadith terminology. - Reciprocal Rank Fusion (RRF): Merges dense and sparse ranked lists with
k=60, surfacing documents strong in both semantic and lexical spaces.
Compute Layer: Dual-LLM Orchestration
DivinityAI routes generation tasks by complexity:
- OpenRouter (Gemini 2.5 Flash): Primary generator for nuanced Fiqh synthesis, multilingual response formatting, and HyDE document generation.
- Groq (Llama 3.3 70B): High-throughput fallback for intent classification, query rewriting, and verification judges where latency is critical.
Key Features Breakdown & Practical Benefits
1. Five-Path Intent Router with Confidence Gating
Every query enters a LLMIntentRouter classifying into:
- QURAN_VERSE: Direct verse lookup / thematic search.
- HADITH: Narrations, isnad analysis, grading.
- FIQH: Jurisprudential reasoning requiring cross-source synthesis.
- CALCULATION: Prayer times, Zakat, inheritance (delegated to deterministic engines).
- OFF_DOMAIN: Rejected immediately with informational message.
Benefit: Eliminates wasted compute on irrelevant retrieval strategies; Fiqh queries trigger HyDE + sub-query decomposition, while Quran queries use direct semantic lookup.
2. HyDE & Sub-Query Decomposition for Fiqh
For FIQH intent, the pipeline generates a Hypothetical Document Embedding (HyDE)—a synthetic answer embedding—to bridge the vocabulary gap between user queries (colloquial) and classical Arabic corpus. Complex queries (e.g., “conditions for combining prayers while traveling”) are decomposed into atomic sub-queries (“travel distance”, “combining Zuhr Asr”, “combining Maghrib Isha”), each retrieved independently, then fused.
3. Hybrid Search: BM25 + BGE-M3 + RRF
Retrieval executes in parallel:
- Dense: ChromaDB ANN search (HNSW) on BGE-M3 vectors.
- Sparse: BM25 on normalized Arabic tokens.
- Fusion: RRF merges top-K (default 20) from each.
Benchmark Insight: On a 500-query Arabic/English eval set, Hybrid RRF improved Recall@10 by +18.7% over dense-only and +12.3% over sparse-only, critical for short Hadith queries where exact term match dominates.
4. Deterministic 4-Tier Citation Verification Chain
Before final output, every inline citation [Q 2:255] or [C bukhari/1] passes a deterministic pipeline—no LLM judge involved:
- Exact Match: Byte-for-byte verification against corpus.
- Normalized Match: Diacritic-insensitive, alef/ya normalized comparison.
- Levenshtein Distance: Edit distance ≤ 2 on normalized text (catches OCR/transcription variance).
- Semantic Check: Embedding cosine similarity ≥ 0.92 between cited span and generated claim.
Failure at any tier strips the citation and triggers regeneration or refusal.
5. Pre/Post Generation Guardrails
- Evidence Sufficiency (Pre-Gen): Heuristic checks minimum retrieved chunk count, coverage score, and citation density. Insufficient evidence → “I cannot answer from the authenticated corpus.”
- Fatwa Boundary Detector (Post-Gen): Classifier flags generated text resembling
Leave a Reply