LexAI is an intelligent system for processing, analyzing, and retrieving legal documents using state-of-the-art NLP and machine learning techniques.
# Install dependencies
pip install -r requirements.txt#navigate to PIPELINE
cd PIPELINE
#build the vectordb, with documents stored in /doc-store
python build_vectordb.py --reset python main.py <path/to/your/document>.
βββ backend
βΒ Β βββ app
βΒ Β βΒ Β βββ routes
βΒ Β βΒ Β βββ schemas
βΒ Β βΒ Β βββ services
βΒ Β βββ migrations
βΒ Β βββ versions
βββ PIPELINE
βΒ Β βββ doc-store
βΒ Β βββ outputs
βΒ Β βββ vectordb
βββ tests
βββ website
βββ public
βββ src
βββ app
βββ components
βββ lib
- Extract text from legal PDFs using pdfplumber
- Identify case titles, citations, and article references
- Parse structured legal document metadata
- Sentence transformer-based embeddings for semantic understanding
- FAISS-powered efficient similarity search
- Support for large-scale legal document corpora
- Trust Relevance Score (TRS) for multi-factor ranking
Advanced legal case retrieval with comprehensive scoring:
- Similarity Score (S): Semantic similarity via embeddings
- Context Fit (C): Contextual relevance via TF-IDF
- Jurisdiction Score (J): Geographic and temporal alignment
- Internal Confidence (I): Optional model confidence
- Uncertainty (U): Prediction reliability estimation
TRS Formula:
TRS = (w_S Γ S) + (w_C Γ C) + (w_J Γ J) + (w_I Γ I) - (w_U Γ U)
Clipped to [0, 1]
- β Deterministic retrieval (no LLM calls)
- β Configurable TRS weights
- β Alignment detection (supports/contradicts/neutral)
- β Automatic span extraction (β€40 words)
- β Comprehensive justifications
- β GPU acceleration support
- β Custom retriever integration
- Python 3.8 or higher
- pip package manager
# Clone the repository
cd CiteAI
# Create a virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtFor faster embedding generation, install the GPU version of FAISS:
pip uninstall faiss-cpu
pip install faiss-gpufrom ocr_agent import process_pdf
# Process a legal PDF
result = process_pdf("path/to/legal_document.pdf")
print(f"Title: {result['title']}")
print(f"Citations found: {len(result['citations'])}")
print(f"Articles referenced: {len(result['articles'])}")from lexai.agents import ExternalInferenceAgent
import json
# Initialize the agent
agent = ExternalInferenceAgent(
model_name="sentence-transformers/all-MiniLM-L6-v2",
device="cpu"
)
# Load legal documents
with open("lexai/data/raw/document.json", "r") as f:
doc = json.load(f)
# Prepare candidates
candidates = [
{"text": "Constitutional rights are fundamental...", "source": "doc1"},
{"text": "Article 21 guarantees life and liberty...", "source": "doc2"},
# ... more documents
]
# Build search index
agent.build_index(candidates, text_field="text")
# Search for similar documents
results = agent.infer("right to privacy", top_k=5)
for result in results:
print(f"Score: {result['similarity_score']:.4f}")
print(f"Text: {result['text'][:100]}...")python example_usage.pyCiteAI/
βββ app.py # Main application entry point
βββ ocr_agent.py # PDF text extraction agent
βββ example_usage.py # Example usage demonstration
βββ requirements.txt # Python dependencies
βββ lexai/ # Core LexAI package
β βββ agents/ # Intelligent agents
β β βββ __init__.py
β β βββ external_inference_agent.py
β β βββ README.md # Agent documentation
β βββ data/ # Data directory
β βββ raw/ # Raw legal documents
βββ tests/ # Test suite
βββ __init__.py
βββ test_external_inference_agent.py
Extracts structured information from legal PDFs:
- Text Extraction: Uses pdfplumber for reliable text extraction
- Title Detection: Identifies case titles from document headers
- Citation Parsing: Extracts legal citations (case law, AIR references)
- Article References: Identifies constitutional articles and sections
Provides semantic search capabilities:
- Embedding Generation: Creates dense vector representations using sentence transformers
- FAISS Indexing: Efficient similarity search with IndexFlatIP
- Flexible Retrieval: Supports custom retrievers or built-in search
- Metadata Preservation: Maintains document metadata throughout retrieval
See lexai/agents/README.md for detailed documentation.
Run the test suite:
# Run all tests
pytest
# Run with coverage
pytest --cov=lexai --cov-report=html
# Run specific test file
pytest tests/test_external_inference_agent.py -vChoose different sentence transformer models based on your needs:
| Model | Dimension | Speed | Use Case |
|---|---|---|---|
| all-MiniLM-L6-v2 | 384 | Fast | General purpose, quick retrieval |
| all-mpnet-base-v2 | 768 | Medium | Better quality, balanced |
| legal-bert-base-uncased | 768 | Medium | Legal domain-specific |
# Use CPU
agent = ExternalInferenceAgent(device="cpu")
# Use GPU (if available)
agent = ExternalInferenceAgent(device="cuda")
# Auto-detect
agent = ExternalInferenceAgent(device=None)build_index(candidates, text_field="text"): Build FAISS index from documentsinfer(query, top_k=5, retriever=None): Retrieve similar documentsget_index_stats(): Get index statisticsclear_index(): Clear the current index
See lexai/agents/README.md for complete API documentation.
- Batch Processing: Process multiple queries together for better throughput
- GPU Acceleration: Use GPU for encoding large document collections
- Model Selection: Choose smaller models for speed, larger for accuracy
- Index Optimization: For very large datasets (>1M documents), use approximate search methods
- Find precedents similar to a case description
- Discover related case law based on semantic similarity
- Search for judgments citing specific articles
- Identify similar legal arguments across cases
- Cluster related legal documents
- Extract and organize citations
- Build searchable legal knowledge bases
- Organize case law libraries
- Semantic tagging of legal documents
- Add support for more document formats (DOCX, HTML)
- Implement multi-lingual legal document support
- Add citation graph analysis
- Integrate with external legal databases
- Build web interface for document search
- Add fine-tuned legal domain models
Contributions are welcome! Please feel free to submit issues or pull requests.
See LICENSE file for details.
- Built with sentence-transformers
- Powered by FAISS
- PDF processing with pdfplumber
For questions or issues, please open an issue on the repository.