A sophisticated, full-stack AI-powered platform for drafting, analyzing, and managing legal contracts. Built with a React frontend and FastAPI backend, leveraging advanced LLMs (Open AI) and RAG (Retrieval-Augmented Generation) for intelligent legal document management.
LegalContractAI is an end-to-end solution that combines:
- Intelligent Contract Drafting: Generate professional legal contracts using AI agents and templates
- Compliance Analysis: Real-time compliance checking against legal statutes and regulations
- Risk Assessment: Identify potential loopholes and high-risk clauses
- Document Management: Store, retrieve, and manage legal documents with Supabase integration
- RAG Integration: Access thousands of legal documents through semantic search
- Multi-Jurisdiction Support: Support for different legal jurisdictions (US, India, etc.)
- π Contract Drafting - Generate contracts from templates and requirements
- β Compliance Checking - Analyze contracts against legal requirements
- π Clause Classification - Categorize and analyze contract clauses
β οΈ Risk Detection - Identify loopholes and problematic terms- π Report Generation - Create detailed analysis reports
- π¬ Interactive Chat - Conversational AI for legal queries
- π Secure Storage - Encrypted storage with Supabase backend
- π Usage Analytics - Track API usage and credit consumption
LegalContractAI/
βββ backend/ # FastAPI backend application
β βββ app/
β β βββ main.py # FastAPI entry point
β β βββ config.py # Configuration management
β β βββ agents/ # AI agents for legal tasks
β β β βββ ingestion_agent.py
β β β βββ clause_agent.py
β β β βββ compliance_agent.py
β β β βββ risk_agent.py
β β β βββ merge_agent.py
β β β βββ drafting_agent.py
β β β βββ structure_agent.py
β β β βββ template_agent.py
β β β βββ ...
β β βββ api/ # API route handlers
β β β βββ drafting.py
β β β βββ compliance.py
β β β βββ analysis.py
β β β βββ chat.py
β β β βββ reports.py
β β β βββ research.py
β β β βββ ...
β β βββ llms/ # LLM client implementations
β β β βββ gemini_client.py
β β β βββ openai_client.py
β β β βββ hybrid_client.py
β β β βββ prompts/
β β βββ services/ # Business logic services
β β β βββ draft_service.py
β β β βββ compliance_service.py
β β β βββ insight_service.py
β β β βββ supabase_service.py
β β β βββ encryption.py
β β βββ RAG/ # Retrieval-Augmented Generation
β β β βββ pinecone_store.py
β β βββ schemas/ # Pydantic data models
β β βββ utils/ # Utility functions
β β βββ pdf_templates/ # Contract templates by type
β βββ legal_texts/ # Legal reference documents
β βββ scripts/ # Utility scripts
β βββ requirements.txt # Python dependencies
β βββ .env.example # Environment variables template
β βββ README.md # Backend documentation
β
βββ frontend/ # React + TypeScript frontend
β βββ src/
β β βββ components/ # UI components
β β β βββ ui/ # shadcn/ui primitives
β β β βββ AIForm.tsx
β β β βββ AICredits.tsx
β β β βββ GeneratedReport.tsx
β β β βββ ...
β β βββ pages/ # Route pages
β β β βββ ContractDrafting.tsx
β β β βββ ComplianceCheck.tsx
β β β βββ LoopholeDetection.tsx
β β β βββ ...
β β βββ lib/ # Utilities and clients
β β β βββ ai-clients.ts
β β β βββ supabase.ts
β β β βββ ...
β β βββ hooks/ # Custom React hooks
β β βββ contexts/ # React contexts
β β βββ services/ # API services
β β βββ types/ # TypeScript interfaces
β β βββ App.tsx # Root component
β β βββ main.tsx # Entry point
β βββ public/ # Static assets
β βββ package.json # Frontend dependencies
β βββ vite.config.ts # Vite configuration
β βββ tailwind.config.ts # Tailwind CSS config
β βββ tsconfig.json # TypeScript configuration
β βββ README.md # Frontend documentation
β
βββ docs/ # Additional documentation
βββ ...
- Node.js: 18+ (with npm, yarn, or bun)
- Python: 3.10+ (with pip and virtual environment)
- Git: For version control
- API Keys:
- OpenAI API key
- Google Generative AI (Gemini) API key (optional)
- Pinecone API key (optional, for RAG)
- Supabase credentials (optional, for persistence)
git clone <repository-url> LegalContractAI
cd LegalContractAIcd backend
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txt
# Create .env file
cp .env.example .env
# Edit .env with your API keys
# GOOGLE_API_KEY=your_gemini_api_key (optional)
# OPENAI_API_KEY=your_openai_api_key
# PINECONE_API_KEY=your_pinecone_key (optional)
# SUPABASE_URL=your_supabase_url (optional)
# SUPABASE_KEY=your_supabase_key (optional)# From backend directory
python -m app.main
# Or
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000The API will be available at http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
cd frontend
# Install dependencies
npm install
# or
pnpm install
# or
bun install
# Create .env file
cat > .env << EOF
VITE_API_BASE_URL=http://localhost:8000
VITE_DEFAULT_CREDITS=5
VITE_SUPABASE_URL=your_supabase_url
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
EOF# From frontend directory
npm run dev
# or
pnpm dev
# or
bun devThe application will be available at http://localhost:5173
- Framework: FastAPI (Python web framework)
- Server: Uvicorn (ASGI server)
- AI/ML:
- Open AI models
- LangChain (LLM orchestration)
- Pinecone (Vector database for RAG)
- Sentence Transformers (Embeddings)
- Data Storage:
- Supabase (PostgreSQL + Auth + Storage)
- Pinecone (Vector search)
- Data Validation: Pydantic
- Async Support: AsyncIO, aiohttp
- Framework: React 18+ with TypeScript
- Build Tool: Vite (lightning-fast builds)
- Styling: Tailwind CSS
- UI Components: shadcn/ui (Radix UI primitives)
- State Management: React Context API, TanStack Query
- HTTP Client: Fetch API, axios
- Backend Integration: Supabase SDK
- Form Handling: React Hook Form
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (React) β
β (Vite + TypeScript + Tailwind + shadcn) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β HTTP/REST API β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Backend (FastAPI) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β API Routes (Drafting, Compliance, Analysis, etc.) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β AI Agents (Ingestion, Clause, Compliance, Risk) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β LLM Clients (Gemini, OpenAI, Hybrid) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β
β β Services (Draft, Compliance, Encryption, RAG) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β External Services & Databases β
β βββββββββββββββ¬βββββββββββββββ¬ββββββββββββββββββββββ β
β βOpen AI Modelβ Pinecone β Supabase β β
β β (LLMs) β (Vector DB) β (Data + Auth) β β
β βββββββββββββββ΄βββββββββββββββ΄ββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-
Contract Drafting:
User Input β Frontend β API Endpoint β Ingestion Agent β LLM (OpenAI) β Response β Frontend Display -
Compliance Checking:
Contract Text β Clause Agent (split clauses) β Compliance Agent (RAG + LLM analysis) β Risk Agent (classify) β Report Generator β JSON Response -
RAG-Enhanced Analysis:
Query β Embedding (Sentence Transformer) β Vector Search (Pinecone) β Retrieved Documents β LLM with Retrieved Context β Response
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/health |
Health check |
| POST | /api/drafting/draft |
Generate contract |
| POST | /api/compliance/check |
Analyze compliance |
| POST | /api/analysis/analyze |
General analysis |
| POST | /api/reports/generate |
Generate reports |
| POST | /api/research/query |
Research query |
| POST | /api/summarization/summarize |
Summarize documents |
| POST | /api/chat/message |
Chat interaction |
| GET | /api/usage/stats |
Usage statistics |
curl -X POST http://localhost:8000/api/drafting/draft \
-H "Content-Type: application/json" \
-d '{
"party_a": "Acme Corporation",
"party_b": "Example Industries Inc.",
"jurisdiction": "United States",
"purpose": "Service Agreement",
"term": "24 months",
"requirements": "Software development services with confidentiality clause"
}'curl -X POST http://localhost:8000/api/compliance/check \
-H "Content-Type: application/json" \
-d '{
"contract_text": "Your contract text here...",
"jurisdiction": "United States"
}'cd backend
source venv/bin/activate # or venv\Scripts\activate on Windows
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000Agents follow a common pattern:
from app.agents.state import AgentState
from langchain_google_genai import ChatGoogleGenerativeAI
async def my_new_agent(state: AgentState) -> AgentState:
"""Process the state and update it with results."""
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp")
# Your logic here
result = await llm.ainvoke(state.input)
state.output = result
return statefrom fastapi import APIRouter, HTTPException
from pydantic import BaseModel
router = APIRouter(prefix="/api/my-feature", tags=["my-feature"])
class MyRequest(BaseModel):
input_field: str
@router.post("/endpoint")
async def my_endpoint(request: MyRequest):
try:
# Your logic here
result = await process_request(request)
return {"result": result}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))// Using shadcn/ui components
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
export const MyComponent = () => {
return (
<div className="p-4">
<Input placeholder="Enter text" />
<Button>Submit</Button>
</div>
);
};// Using the AI client
import { aiClient } from "@/lib/ai-clients";
const response = await aiClient.post("/drafting/draft", {
party_a: "Company A",
party_b: "Company B",
requirements: "..."
});- Create component in
src/pages/ - Add route in
src/App.tsx - Update navigation in
src/components/Header.tsx
- API Keys: Store all sensitive keys in
.envfiles (never commit to git) - Encryption: PayloadChat messages are encrypted using AES encryption
- CORS: Configured to only allow trusted origins
- Input Validation: All inputs validated with Pydantic
- Authentication: Optional Supabase authentication
- Rate Limiting: Implemented to prevent abuse
# .env (never commit)
GOOGLE_API_KEY=sk-xxx
OPENAI_API_KEY=sk-xxx
PINECONE_API_KEY=pk-xxx
SUPABASE_URL=https://xxx.supabase.co
SUPABASE_KEY=xxx
CHAT_ENCRYPTION_KEY_V1=xxx
# Frontend .env
VITE_API_BASE_URL=http://localhost:8000
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_ANON_KEY=xxx- contracts: Stored contracts with metadata
- compliance_reports: Compliance analysis results
- chat_history: Encrypted chat messages
- usage_logs: API usage tracking
- templates: Contract templates
cd backend
# Run tests
pytest tests/ -v
# Run specific test file
pytest tests/test_api.py -v
# Run with coverage
pytest --cov=app tests/cd frontend
# Run linting
npm run lint
# Build for production
npm run build
# Preview production build
npm run previewOptions:
- Heroku:
git push heroku main - Railway: Connect GitHub repo
- Docker: Build with included Dockerfile
- AWS EC2: Deploy with systemd/supervisor
Options:
- Vercel: Deploy directly from GitHub
- Netlify: Connect repository
- AWS S3 + CloudFront: Static hosting
- Docker: Run in container
# Build backend image
docker build -f backend/Dockerfile -t legalcontractai-backend .
# Build frontend image
docker build -f frontend/Dockerfile -t legalcontractai-frontend .
# Run with docker-compose
docker-compose up -d- Multi-language support
- Advanced document comparison
- Automated contract renewal reminders
- Team collaboration features
- Advanced audit trail logging
- Mobile app (React Native)
- Blockchain verification of contracts
- Custom model fine-tuning
We welcome contributions! Here's how to help:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow PEP 8 (Python) and ESLint (TypeScript) conventions
- Write clear commit messages
- Add tests for new features
- Update documentation as needed
- Keep PRs focused and manageable
- Backend Documentation
- Frontend Documentation
- API Documentation (Swagger UI)
- Open AI API docs :
- Google Generative AI Docs
- FastAPI Docs
- React Docs
- Tailwind CSS Docs
This project is licensed under the MIT License. See the LICENSE file for details.
Port 8000 already in use:
# Find and kill process on port 8000
lsof -i :8000
kill -9 <PID>
# Or use different port
uvicorn app.main:app --port 8001Import errors:
# Reinstall dependencies
pip install -r requirements.txt --force-reinstallAPI key errors:
# Verify .env file exists and contains valid keys
cat .envModule not found:
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm installPort 5173 already in use:
# Vite will automatically try next port or specify manually
npm run dev -- --port 5174- Issues: GitHub Issues
- Discussions: GitHub Discussions
Last Updated: February 16, 2026
Version: 1.0.0