Semantic search and intelligent analysis of the Bharatiya Nyaya Sanhita (BNS) with IPC-to-BNS transition mapping
Features Β· Architecture Β· Tech Stack Β· Setup Β· API Docs Β· Usage Β· Disclaimer
LexAI is an intelligent Retrieval-Augmented Generation (RAG) system designed to assist in understanding and analyzing criminal law provisions in India. It provides semantic search and detailed analysis of the Bharatiya Nyaya Sanhita (BNS) β India's new criminal code β with intelligent IPC-to-BNS mapping to facilitate the transition from the legacy Indian Penal Code.
The system combines advanced natural language processing, vector similarity search, and large language models to deliver comprehensive legal insights, including applicable sections, essential offense ingredients, legal reasoning, and prescribed punishments.
β οΈ Disclaimer: LexAI is a research prototype. It must not be used as a substitute for professional legal advice. Always consult qualified legal professionals for actual legal matters.
- Search across 358+ BNS sections using natural language queries
- Find relevant legal provisions based on case descriptions
- Similarity scoring with configurable thresholds (default: 0.30)
- Fast retrieval using FAISS vector indexing
- 358 BNS Sections fully indexed and searchable
- 500+ IPC Sections mapped to their BNS equivalents
- 20 Chapters covering all offense categories
- Complete statutory text with explanations, illustrations, and exceptions
- Bidirectional IPC β BNS mapping
- Automatic query reformulation for improved search accuracy
- LLM-based analysis generation covering:
- Relevant BNS section identification
- Essential ingredients of the offense
- Legal reasoning and precedents
- Prescribed punishments and penalties
- Real-time streaming responses for interactive analysis
- Multi-turn conversations with legal context awareness
- Persistent chat history with search and filtering
- Suggested prompts to guide legal research
- Specialized legal response renderer with expandable sections
- Real-time thinking animations during processing
- Secure JWT-based authentication (2-hour token expiry)
- Email provider validation (Gmail, Yahoo, Outlook, Hotmail)
- Strong password enforcement (uppercase, lowercase, numbers, special chars)
- Bcrypt password hashing with salt rounds
- Persistent user profiles and chat history
- Side-by-side navigation between old IPC and new BNS provisions
- Clear mapping of corresponding sections and their differences
- Built to help legal professionals transition to the new code
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (React) β
β Chatbot Interface β Auth β Home β Chat History β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β HTTP / Axios
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β Backend (Express.js) β
β Auth β Chat Management β API Orchestration β
β /signup /login /chats /analyze-case β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β HTTP / Axios
βββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββ
β AI Service (FastAPI + Python) β
β Query Reformulation β FAISS Retrieval β LLM β
β Semantic Search β Legal Analysis β Streaming β
βββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
βββββββββββββ΄ββββββββββββ
β File I/O β DB Queries
βββββββββββββββΌβββββββββββ ββββββββββΌβββββββββββββββββββ
β Knowledge Base β β MongoDB β
β FAISS Index β β User Profiles β
β BNS Sections (358) β β Chat History β
β IPC-BNS Mapping (500+) β β Metadata β
ββββββββββββββββββββββββββ βββββββββββββββββββββββββββββ
User Input
β
βΌ
Backend (Auth + Request Handling)
β
βΌ
Query Reformulation ββββ LLM
β
βΌ
FAISS Semantic Search ββββ BNS Embeddings
β
βΌ
Top-k Sections Retrieved (k=5, threshold=0.30)
β
βΌ
LLM Legal Analysis Generation (Streaming)
β
βΌ
Frontend Renderer ββββ Chat Persistence (MongoDB)
| Layer | Technology |
|---|---|
| Frontend | React 19.2.0, Vite, React Router DOM 7.12.0, Axios 1.13.2 |
| Backend | Node.js, Express.js 5.2.1, JWT, bcryptjs |
| Database | MongoDB 9.1.3 |
| AI / ML | FastAPI, FAISS, Sentence Transformers (BAAI/bge-large-en-v1.5) |
| LLM | Ollama (Gemma model) |
| Data | JSON files for BNS sections and IPC-BNS mappings |
| Python | 3.8+ |
mini_project/
β
βββ frontend/ # React frontend application
β βββ src/
β β βββ App.jsx # Main app component with routes
β β βββ main.jsx # React entry point
β β βββ Chatbot.jsx # Main chatbot interface
β β βββ Home.jsx # Landing page with feature showcase
β β βββ Auth.jsx # Login / Signup component
β β βββ Layout.jsx # Navigation wrapper
β β βββ ProtectedRoute.jsx # Auth protection wrapper
β β βββ *.css # Component-specific styles
β β βββ assets/ # Images and static files
β βββ package.json
β βββ vite.config.js
β βββ index.html
β
βββ backend/ # Express.js backend server
β βββ index.js # Main server
β β βββ Auth routes # /signup, /login
β β βββ Chat routes # /chats, /chats/:id
β β βββ AI integration # /analyze-case, /analyze-case-stream
β β βββ Auth middleware
β β βββ Error handling
β βββ package.json
β βββ .env # Environment variables (not committed)
β
βββ ai-service/legal_rag/ # Python ML pipeline
β βββ main.py # FastAPI application entry point
β βββ pipeline.py # RAG pipeline (streaming + non-streaming)
β βββ retriever.py # FAISS-based semantic search
β βββ llm_ollama.py # LLM integration (Gemma)
β βββ requirements.txt # Python dependencies
β βββ faiss_max.bin # Pre-computed FAISS index
β βββ faiss_max.pkl # Index metadata
β βββ bns_max.json # BNS sections database
β βββ bns_ipc_map_updated.json # IPC-to-BNS mapping
β βββ embeddings_max.pkl # Pre-computed embeddings
β βββ venv/ # Python virtual environment
β
βββ bns_ipc_map_updated.json # Root-level reference mapping
βββ README.md
βββ .gitignore
- Node.js 16+ and npm
- Python 3.8+
- MongoDB (local or cloud instance)
- Ollama (for LLM inference)
cd frontend
npm installCreate .env in the frontend/ directory:
VITE_API_URL=http://localhost:5000cd backend
npm installCreate .env in the backend/ directory:
MONGODB_URI=mongodb://localhost:27017/lexai
JWT_SECRET=your_secret_key_here
PORT=5000
AI_SERVICE_URL=http://localhost:8000cd ai-service/legal_rag
python -m venv venv
# Activate virtual environment
source venv/bin/activate # macOS / Linux
venv\Scripts\activate # Windows
pip install -r requirements.txtEnsure Ollama is running with the Gemma model:
ollama run gemmaOpen three separate terminals:
# Terminal 1 β AI Service (http://localhost:8000)
cd ai-service/legal_rag
source venv/bin/activate
python main.py
# Terminal 2 β Backend (http://localhost:5000)
cd backend
npm start
# Terminal 3 β Frontend (http://localhost:5173)
cd frontend
npm run devVisit http://localhost:5173 to access LexAI.
Create a new user account.
// Request
{
"email": "user@gmail.com",
"password": "SecurePass123!",
"fullName": "John Doe"
}
// Response
{
"token": "<jwt_token>",
"user": { "id": "...", "email": "...", "fullName": "..." }
}Authenticate an existing user.
// Request
{
"email": "user@gmail.com",
"password": "SecurePass123!"
}
// Response
{
"token": "<jwt_token>",
"user": { "id": "...", "email": "...", "fullName": "..." }
}All chat endpoints require
Authorization: Bearer <token>
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/chats |
Retrieve all chats for the authenticated user |
POST |
/api/chats |
Create a new chat |
GET |
/api/chats/:id |
Get a specific chat by ID |
PUT |
/api/chats/:id |
Update title or add a message |
DELETE |
/api/chats/:id |
Delete a chat |
Get a complete legal analysis for a case description.
// Request
{
"caseDescription": "A stole B's property worth βΉ5000..."
}
// Response
{
"relevantSections": [
{ "section": "BNS 304", "score": 0.95 }
],
"analysis": {
"sections": "...",
"ingredients": "...",
"reasoning": "...",
"punishment": "..."
}
}Same request format β response is streamed as Server-Sent Events for real-time display.
- Sign up and log in with your email
- Describe your case or legal scenario in natural language
- LexAI returns the most relevant BNS sections with similarity scores
- Review structured analysis: applicable sections, offense ingredients, legal reasoning, punishments
- Save analyses in persistent chat history
- Use IPC-to-BNS mapping for code transition reference
- Explore the Home page to understand the BNS structure
- Test case scenarios through the chatbot
- Learn how different sections apply to real-world situations
- Review explanations and legal reasoning in an accessible format
- Leverage semantic search to find related provisions across the BNS
- Analyze legal patterns across sections and chapters
- Use IPC-BNS mapping for comparative legal research
- Export chat history for documentation and annotation
- Pre-trained Sentence Transformer embeddings (
BAAI/bge-large-en-v1.5) - Converts case descriptions to dense vector embeddings
- Cosine similarity search against indexed BNS section embeddings
- Returns top-5 sections above similarity threshold (0.30)
- LLM rephrases user queries for better semantic alignment with legal text
- Handles legal terminology normalization and ambiguity resolution
- Improves relevance of retrieved sections significantly
- Ollama Gemma generates structured legal analysis
- Output sections: applicable provisions, ingredients, reasoning, punishment
- Full streaming support for real-time progressive display
| Operation | Latency |
|---|---|
| FAISS Search (358 sections) | ~50β100ms |
| Query Reformulation (LLM) | ~500β1000ms |
| Legal Analysis Generation | ~2β5s (streamed) |
| Auth API Requests | ~100β200ms |
| Chat History Retrieval (MongoDB) | <50ms |
- JWT-based authentication with 2-hour token expiry
- Password hashing with bcrypt (10 salt rounds)
- Email provider validation
- CORS middleware configuration
- Protected API endpoints with auth middleware
- Enforce HTTPS/TLS for all communications
- Implement rate limiting on authentication endpoints
- Add request validation and input sanitization
- Enable MongoDB authentication and at-rest encryption
- Implement audit logging for sensitive operations
- Add CSRF protection
- Consider OAuth2 for third-party access
- Core RAG pipeline with semantic search
- 358 BNS sections fully indexed
- 500+ IPC-to-BNS mappings
- JWT user authentication system
- Chatbot interface with auto-scrolling
- Chat persistence in MongoDB
- Streaming response support
- Query reformulation
- Legal response renderer with section expansion
- Embedding optimization for all sections
- Performance improvements
- Case law summaries and precedent analysis
- Sentencing guidelines integration
- Advanced filtering and sorting
- Export functionality (PDF, Word)
- Multi-language support
- Mobile app version
- Offline mode support
AI Service not responding
ollama list
ollama run gemma
curl http://localhost:8000/docsMongoDB connection issues
mongod --version
# Verify MONGODB_URI in backend/.env
# Format: mongodb://localhost:27017/lexaiCORS errors
- Confirm
VITE_API_URLin frontend.envmatches the backend URL exactly - Review CORS configuration in
backend/index.js
Chat history not saving
- Ensure MongoDB is connected and running
- Check that JWT token has not expired (2-hour limit)
- Verify auth middleware is applied to all chat endpoints
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Make your changes with clear, descriptive commit messages
- Test across all three services (frontend, backend, AI service)
- Submit a pull request with a clear description of the changes
Please ensure your code follows existing project conventions and includes relevant comments.
LexAI: An AI-Powered Legal Research System for Indian Criminal Law
Bharatiya Nyaya Sanhita (BNS) Analysis and IPC Mapping
Version 1.0.0 (Beta) β March 2026
LexAI is an AI-powered research and educational tool. It is not a substitute for professional legal advice. The system may contain errors or incomplete information, and all legal information should be independently verified by a qualified legal professional before being relied upon.
Last Updated: March 2, 2026 Β |Β Version: 1.0.0 (Beta) Β |Β Branch: adii
Built for legal research and education purposes