Spaces:
Running
title: Mexar
emoji: π§
colorFrom: blue
colorTo: indigo
sdk: docker
pinned: false
license: mit
π§ MEXAR
Multimodal Explainable AI Reasoning Assistant
Build domain-specific AI agents from your documents β with transparent, grounded, and faithful answers.
π Live App β mexar.vercel.app | π‘ Backend API β devrajsinh2012-mexar.hf.space | π API Docs β /docs
π What is MEXAR?
MEXAR is a full-stack, production-ready RAG (Retrieval-Augmented Generation) platform that lets you create custom AI agents from your own documents. Unlike a simple chatbot, MEXAR is built around explainability and faithfulness β every answer is grounded in your source data, cited with inline references, and scored for hallucination risk using a NLI model.
You upload documents β MEXAR compiles an agent β You chat with grounded, explainable AI.
β¨ Core Features
| Feature | Description |
|---|---|
| π Hybrid RAG Search | Semantic (pgvector cosine) + Keyword (BM25 tsvector) fused via Reciprocal Rank Fusion (RRF) |
| π― Cross-Encoder Reranking | sentence-transformers cross-encoder re-scores top candidates for precision |
| π Inline Source Attribution | Every answer references exact source chunks with [1], [2] citations |
| β DeBERTa-v3 Faithfulness Scoring | NLI-based hallucination detection scores answer grounding against retrieved context |
| π Domain Guardrails | TF-IDF + spaCy NER Jaccard similarity prevents out-of-domain queries (F1 = 0.9072 at threshold 0.25) |
| π£οΈ Multimodal Input | Audio (Groq Whisper), Images (Groq Vision), Video (OpenCV frame extraction) |
| π Text-to-Speech | ElevenLabs API + Web Speech API fallback |
| π§ Explainability Panel | Full reasoning trace: retrieval scores, confidence breakdown, sources cited, guardrail status |
| π 5 Document Formats | PDF, DOCX, CSV, JSON, TXT |
| β‘ Real-time WebSocket | Streaming chat via WebSocket with progress tracking |
| π JWT Auth | Secure user accounts with bcrypt-hashed passwords and JWT bearer tokens |
ποΈ System Architecture
MEXAR is composed of four layers: Frontend, API, Intelligence, and Storage.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β USER INTERACTION LAYER β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β React 18 Frontend β Vercel Edge Network β β
β β Landing Β· Login Β· Dashboard Β· AgentCreation Β· Chat Β· Explainability β β
β ββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββ β
β β HTTPS / WebSocket β
ββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββ
β FASTAPI BACKEND (HF Spaces / Docker) β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββ β
β β /auth β β /agents β β /chat β β /compile β β /websocket β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββ
β CORE INTELLIGENCE LAYER β
β β
β ββββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββββ β
β β DataValidator β β KnowledgeCompilerβ β MultimodalProcessor β β
β β PDF/DOCX/CSV/TXT βββββΆβ Chunking + Embed β β Whisper Β· Vision β β
β β /JSON parsing β β FastEmbed bge-384β β OpenCV frames β β
β ββββββββββββββββββββ ββββββββββ¬ββββββββββ ββββββββββββ¬βββββββββββ β
β β Store chunks β Text β
β ββββββββββββββββββββ βΌ βΌ β
β β PromptAnalyzer β βββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Intent Β· Domain βββββΆβ ReasoningEngine (RAG Core) β β
β β Query Rewrite β β β β
β ββββββββββββββββββββ β 1. Domain Guardrail (TF-IDF + NER Jaccard) β β
β β 2. HybridSearcher (pgvector + BM25 RRF) β β
β ββββββββββββββββββββ β 3. CrossEncoder Reranker β β
β β ExplainabilityGenββββββ 4. SourceAttributor (citation tracking) β β
β β Reasoning trace β β 5. Groq LLM Answer Generation β β
β β Confidence score β β 6. DeBERTa-v3 Faithfulness Scoring β β
β ββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
ββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββ
β EXTERNAL SERVICES LAYER β
β β
β ββββββββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββββββββ β
β β Supabase / PostgreSQLβ β Groq Cloud β β ElevenLabs β β
β β pgvector extension β β Llama 3.3 Β· 3.1 β β Text-to-Speech API β β
β β BM25 tsvector FTS β β Whisper v3 Large β β β β
β β JWT sessions β β Vision (preview) β βββββββββββββββββββββββββ β
β ββββββββββββββββββββββββ ββββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Request Lifecycle β Step by Step
User Query
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1. MULTIMODAL INPUT (optional) β
β Audio β Groq Whisper STT β text β
β Image β Groq Vision β described text β
β Video β OpenCV frame extract β Vision β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 2. PROMPT ANALYSIS β
β β’ Parse intent (factual / analytical / compare) β
β β’ Detect domain topic β
β β’ Optionally rewrite query for clarity β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3. DOMAIN GUARDRAIL CHECK β
β β’ TF-IDF cosine similarity vs agent signature β
β β’ spaCy NER entity Jaccard overlap β
β β’ Threshold = 0.25 (F1 = 0.9072) β
β β’ If below threshold β reject with explanation β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 4. HYBRID RETRIEVAL β
β β’ Dense: FastEmbed bge-small-en (384-dim) β
β β pgvector cosine similarity search β
β β’ Sparse: PostgreSQL tsvector BM25 FTS β
β β’ Fuse both via Reciprocal Rank Fusion (RRF) β
β score = Ξ£ 1/(rank + 60) β
β β’ Return top-K=20 candidate chunks β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 5. CROSS-ENCODER RERANKING β
β β’ sentence-transformers cross-encoder β
β β’ Re-scores top candidates for relevance β
β β’ Selects top-5 chunks as final context β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 6. LLM ANSWER GENERATION β
β β’ Build system prompt with retrieved context β
β β’ Multi-model Groq inference with auto-fallback: β
β llama-3.3-70b β llama-3.1-8b β mixtral-8x7b β
β β’ Answer generated with citations embedded β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 7. SOURCE ATTRIBUTION β
β β’ Match answer sentences β source chunks β
β β’ Assign [1], [2], [3] reference markers β
β β’ Track provenance per claim β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 8. FAITHFULNESS SCORING (DeBERTa-v3 NLI) β
β β’ Extract claims from answer β
β β’ For each claim-chunk pair, NLI inference: β
β entailment β faithful β
β contradiction β hallucinated β
β β’ Batched with torch.inference_mode() (~1.2s) β
β β’ Output: faithfulness score 0.0β1.0 β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 9. EXPLAINABILITY PACKAGING β
β β’ Reasoning trace (step-by-step) β
β β’ Confidence breakdown (domain + faithfulness) β
β β’ Sources cited (with file name + chunk text) β
β β’ Guardrail decision log β
ββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ
β
βΌ
Response to User
(Answer + Citations
+ Faithfulness Score
+ Explainability Panel)
ποΈ Project Structure
Mexar-main/
β
βββ backend/ # FastAPI Python backend
β βββ api/ # Route handlers
β β βββ auth.py # JWT login / register
β β βββ agents.py # Agent CRUD operations
β β βββ chat.py # Chat endpoint (REST)
β β βββ compile.py # Knowledge compilation jobs
β β βββ websocket.py # Streaming WebSocket chat
β β βββ admin.py # Admin panel routes
β β βββ diagnostics.py # System health checks
β β
β βββ modules/ # Core AI intelligence
β β βββ reasoning_engine.py # Main RAG pipeline (634 lines)
β β βββ knowledge_compiler.py # Doc ingestion + embedding
β β βββ data_validator.py # File parsing (PDF/DOCX/CSV/TXT/JSON)
β β βββ prompt_analyzer.py # Intent + domain classification
β β βββ multimodal_processor.py # Audio/Image/Video β text
β β βββ explainability.py # Reasoning trace packaging
β β
β βββ utils/ # Utility modules
β β βββ hybrid_search.py # pgvector + BM25 + RRF fusion
β β βββ faithfulness.py # DeBERTa-v3 NLI scorer
β β βββ groq_client.py # Multi-model Groq client + fallback
β β βββ reranker.py # Cross-encoder reranking
β β βββ source_attribution.py # Citation tracking
β β βββ semantic_chunker.py # Adaptive text chunking
β β βββ domain_signature.py # TF-IDF + NER signature builder
β β
β βββ models/ # SQLAlchemy ORM models
β β βββ user.py # User model
β β βββ agent.py # Agent + CompilationJob
β β βββ chunk.py # DocumentChunk (with vector)
β β βββ conversation.py # Conversation + Message
β β
β βββ migrations/
β β βββ hybrid_search_function.sql # PostgreSQL RRF function
β β
β βββ evaluation/ # Phase 3 benchmark suite
β β βββ run_all.py # Master evaluation runner
β β βββ guardrail_threshold_sweep.py
β β
β βββ scripts/ # Data collection scripts
β β βββ fetch_pubmed.py # NCBI PubMed Open Access
β β βββ fetch_courtlistener.py # CourtListener v4 API
β β βββ fetch_secedgar.py # SEC EDGAR 10-K filings
β β
β βββ static/index.html # HF Spaces landing page
β βββ main.py # FastAPI application entry
β βββ requirements.txt # Python dependencies
β
βββ frontend/ # React 18 frontend
β βββ src/
β βββ pages/
β β βββ Landing.jsx # Marketing home page
β β βββ Login.jsx # Authentication
β β βββ Dashboard.jsx # Agent management hub
β β βββ AgentCreation.jsx # Upload + configure agent
β β βββ AgentList.jsx # Browse your agents
β β βββ Chat.jsx # Full chat interface (39KB)
β β βββ CompilationProgress.jsx # Live compilation view
β β
β βββ components/
β βββ ExplainabilityModal.jsx # Reasoning trace viewer
β βββ KnowledgeGraph.jsx # Visual knowledge graph
β βββ AudioRecorder.jsx # Browser microphone input
β βββ TTSPlayer.jsx # TTS playback
β βββ InlineTTS.jsx # Per-sentence TTS
β βββ AgentSwitcher.jsx # Switch between agents
β
βββ test_data/ # Real evaluation datasets
β βββ medical_real/ # 31 PubMed PMC open-access papers
β βββ legal_real/ # 148 CourtListener judicial opinions
β βββ financial_real/ # 4 SEC EDGAR 10-K filings
β βββ query_sets/ # Evaluation query sets per domain
β
βββ Dockerfile # Container definition (HF Spaces)
βββ README.md
π Empirical Evaluation Results & Benchmarks
MEXAR has been evaluated against established baselines on real datasets sourced via public APIs.
Knowledge Base β Real Multi-Domain Corpus
| Domain | Data Source | Files | Vector Chunks | Domain Signature Terms |
|---|---|---|---|---|
| π₯ Medical | NCBI PubMed Central Open Access | 31 papers | 556 chunks | 127 terms |
| βοΈ Legal | CourtListener REST API v4 | 148 opinions | 157 chunks | 152 terms |
| π Financial | SEC EDGAR 10-K Filings | 4 filings | 68 chunks | 119 terms |
Table I β Multi-System Faithfulness Comparison
| System | Medical β | Legal β | Financial β |
|---|---|---|---|
| Naive RAG | 0.0222 | 0.0333 | 0.0000 |
| BM25-only Retrieval | 0.0000 | 0.0000 | 0.0000 |
| LangChain RAG | 0.5000 | 0.5000 | 0.5000 |
| Self-RAG | 0.2380 | 0.0833 | N/A |
| π§ MEXAR (Ours) | 0.1000 | 0.1000 | N/A |
Faithfulness scored via DeBERTa-v3-base NLI. Higher = better grounding.
Table II β Domain Guardrail Performance
| Metric | Value |
|---|---|
| Optimal Threshold | 0.25 |
| F1 Score | 0.9072 |
| Method | TF-IDF cosine + spaCy NER Jaccard |
| Mean Latency | 113.49 ms |
Table III β System Latency Profile
| Component | Latency |
|---|---|
| DeBERTa NLI Faithfulness (vectorized batch) | ~1.2s / query |
| Domain Guardrail check | 113.49 ms |
| Hybrid RRF Search (pgvector + BM25) | < 100 ms |
| Groq LLM inference (llama-3.1-8b) | ~800 ms |
50x speedup on faithfulness scoring achieved via
torch.inference_mode()vectorized batching over the naive sequential baseline (~70s β ~1.2s).
Expected Calibration Error (ECE)
ECE = 0.1000 β confidence scores are well-calibrated against empirical answer accuracy.
π Quick Start
Prerequisites
- Python 3.9+
- Node.js 18+
- PostgreSQL with
pgvectorextension (or Supabase free tier) - Groq API Key β free tier available
1. Clone & Configure
git clone https://github.com/devrajsinh2012/Mexar.git
cd Mexar-main
# Copy backend environment file
cp backend/.env.example backend/.env
# Fill in your credentials (see Environment Variables below)
2. Backend Setup
cd backend
pip install -r requirements.txt
# Install spaCy model required for domain guardrail
python -m spacy download en_core_web_sm
# Apply database migration (PostgreSQL RRF hybrid search function)
psql $DATABASE_URL -f migrations/hybrid_search_function.sql
# Start backend server
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
Backend available at: http://localhost:8000
Interactive API docs: http://localhost:8000/docs
3. Frontend Setup
cd frontend
npm install
# Set API URL
echo "REACT_APP_API_URL=http://localhost:8000" > .env
npm start
Frontend available at: http://localhost:3000
π Environment Variables
# backend/.env
# === REQUIRED ===
GROQ_API_KEY=your_groq_api_key_here # https://console.groq.com
DATABASE_URL=postgresql://user:pass@host:5432/db
SECRET_KEY=your_secure_jwt_secret_key
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your_supabase_service_role_key
# === OPTIONAL ===
ELEVENLABS_API_KEY=your_elevenlabs_api_key # Text-to-speech
FRONTEND_URL=https://mexar.vercel.app # CORS origin
# === DATASET COLLECTION (scripts/) ===
COURTLISTENER_TOKEN=your_cl_token # courtlistener.com
NCBI_EMAIL=your@email.com # NCBI policy requirement
NCBI_API_KEY=your_ncbi_api_key # Raises rate limit 3β10 req/s
SEC_USER_AGENT=Firstname Lastname your@email.com # SEC EDGAR fair access
π³ Docker / Hugging Face Spaces Deployment
The project ships with a ready-to-use Dockerfile and is live on HF Spaces.
# Build locally
docker build -t mexar-backend ./backend
docker run -p 8000:8000 --env-file backend/.env mexar-backend
For Hugging Face Spaces, push to the hf remote:
git remote add hf https://huggingface.co/spaces/devrajsinh2012/mexar.git
git push hf main
π‘ API Reference
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/auth/register |
Register a new user account |
POST |
/api/auth/login |
Login and receive JWT token |
GET |
/api/agents/ |
List all compiled agents |
POST |
/api/agents/ |
Create a new agent |
POST |
/api/compile/ |
Start knowledge compilation from uploaded files |
GET |
/api/compile/{job_id} |
Poll compilation job status |
POST |
/api/chat/ |
Send a query to an agent (REST) |
WS |
/ws/chat/{agent_id} |
Real-time streaming chat (WebSocket) |
GET |
/api/health |
Health check |
GET |
/docs |
Interactive Swagger UI |
Full interactive documentation: devrajsinh2012-mexar.hf.space/docs
π§ Groq Model Fallback Chain
MEXAR implements a resilient multi-model fallback for Groq API rate limits:
openai/gpt-oss-120b
β (429 TPD quota)
βΌ
llama-3.3-70b-versatile
β (429 TPD quota)
βΌ
llama-3.1-8b-instant
β (429 TPD quota)
βΌ
mixtral-8x7b-32768
β (429 TPD quota)
βΌ
gemma2-9b-it
This ensures zero-downtime inference even under heavy usage within free-tier quotas.
π§ͺ Running Evaluations
# Fetch real datasets (requires API keys in .env)
python backend/scripts/fetch_pubmed.py # NCBI PubMed
python backend/scripts/fetch_courtlistener.py # CourtListener
python backend/scripts/fetch_secedgar.py # SEC EDGAR
# Recompile domain agents from real data
python backend/scripts/recompile_agents_from_real_data.py
# Run full Phase 3 evaluation pipeline
python backend/evaluation/run_all.py
# Results saved to:
# backend/evaluation_outputs/full_evaluation_<timestamp>.json
π οΈ Tech Stack
| Layer | Technology |
|---|---|
| Frontend | React 18, React Router, Vercel |
| Backend | FastAPI 0.109, Uvicorn, Python 3.9+ |
| Database | PostgreSQL + pgvector, Supabase |
| Vector Search | FastEmbed BAAI/bge-small-en-v1.5 (384-dim) |
| Keyword Search | PostgreSQL tsvector BM25 FTS |
| RRF Fusion | Custom SQL stored procedure |
| LLM Inference | Groq API (Llama 3.3, Llama 3.1, Mixtral, Gemma 2) |
| Faithfulness | microsoft/deberta-v3-base NLI via HuggingFace |
| Reranking | sentence-transformers cross-encoder |
| Multimodal | Groq Whisper v3 (audio), Groq Vision (images), OpenCV (video) |
| TTS | ElevenLabs API + Web Speech API |
| Auth | JWT (python-jose) + bcrypt (passlib) |
| Deployment | Hugging Face Spaces (Docker), Vercel (frontend) |
| NLP | spaCy en_core_web_sm, scikit-learn TF-IDF |
π€ Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Commit your changes:
git commit -m 'feat: add my feature' - Push to the branch:
git push origin feature/my-feature - Open a Pull Request
π License
This project is licensed under the MIT License β see LICENSE for details.