Skip to content

topspeed69/LegalContractAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

67 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

LegalContractAI - AI-Powered Legal Contract Platform

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.

🎯 Overview

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.)

Key Features

  • πŸ“ 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

πŸ“ Project Structure

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
    └── ...

πŸš€ Quick Start

Prerequisites

  • 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)

Setup Instructions

1. Clone the Repository

git clone <repository-url> LegalContractAI
cd LegalContractAI

2. Backend Setup

cd 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)

3. Start the Backend

# From backend directory
python -m app.main
# Or
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

The API will be available at http://localhost:8000

4. Frontend Setup

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

5. Start the Frontend

# From frontend directory
npm run dev
# or
pnpm dev
# or
bun dev

The application will be available at http://localhost:5173


πŸ“š Architecture Overview

Technology Stack

Backend

  • 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

Frontend

  • 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

System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     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)       β”‚      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Flow

  1. Contract Drafting:

    User Input β†’ Frontend β†’ API Endpoint β†’ Ingestion Agent β†’ 
    LLM (OpenAI) β†’ Response β†’ Frontend Display
    
  2. Compliance Checking:

    Contract Text β†’ Clause Agent (split clauses) β†’ 
    Compliance Agent (RAG + LLM analysis) β†’ Risk Agent (classify) β†’ 
    Report Generator β†’ JSON Response
    
  3. RAG-Enhanced Analysis:

    Query β†’ Embedding (Sentence Transformer) β†’ Vector Search (Pinecone) β†’
    Retrieved Documents β†’ LLM with Retrieved Context β†’ Response
    

πŸ”Œ API Endpoints

Core Endpoints

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

Request/Response Examples

Contract Drafting

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"
  }'

Compliance Check

curl -X POST http://localhost:8000/api/compliance/check \
  -H "Content-Type: application/json" \
  -d '{
    "contract_text": "Your contract text here...",
    "jurisdiction": "United States"
  }'

πŸ› οΈ Development Guide

Backend Development

Running in Development Mode

cd backend
source venv/bin/activate  # or venv\Scripts\activate on Windows
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Creating New Agents

Agents 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 state

Creating New API Endpoints

from 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))

Frontend Development

Component Development

// 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>
  );
};

API Integration

// 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: "..."
});

Adding New Pages

  1. Create component in src/pages/
  2. Add route in src/App.tsx
  3. Update navigation in src/components/Header.tsx

πŸ” Security Considerations

  • API Keys: Store all sensitive keys in .env files (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

Environment Variables Best Practices

# .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

πŸ“Š Database Schema

Key Tables (Supabase)

  • contracts: Stored contracts with metadata
  • compliance_reports: Compliance analysis results
  • chat_history: Encrypted chat messages
  • usage_logs: API usage tracking
  • templates: Contract templates

πŸ§ͺ Testing

Backend Testing

cd backend

# Run tests
pytest tests/ -v

# Run specific test file
pytest tests/test_api.py -v

# Run with coverage
pytest --cov=app tests/

Frontend Testing

cd frontend

# Run linting
npm run lint

# Build for production
npm run build

# Preview production build
npm run preview

πŸ“¦ Deployment

Backend Deployment

Options:

  • Heroku: git push heroku main
  • Railway: Connect GitHub repo
  • Docker: Build with included Dockerfile
  • AWS EC2: Deploy with systemd/supervisor

Frontend Deployment

Options:

  • Vercel: Deploy directly from GitHub
  • Netlify: Connect repository
  • AWS S3 + CloudFront: Static hosting
  • Docker: Run in container

Docker Deployment

# 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

πŸ—ΊοΈ Roadmap

Planned Features

  • 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

🀝 Contributing

We welcome contributions! Here's how to help:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution Guidelines

  • 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

πŸ“– Additional Resources


πŸ“„ License

This project is licensed under the MIT License. See the LICENSE file for details.


πŸ†˜ Troubleshooting

Backend Issues

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 8001

Import errors:

# Reinstall dependencies
pip install -r requirements.txt --force-reinstall

API key errors:

# Verify .env file exists and contains valid keys
cat .env

Frontend Issues

Module not found:

# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

Port 5173 already in use:

# Vite will automatically try next port or specify manually
npm run dev -- --port 5174

πŸ“ž Support & Community


Last Updated: February 16, 2026
Version: 1.0.0

About

The Legal Contract is an AI-powered chatbot and tool designed to assist users with legal queries and Legal Documents and Contract Drafting

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors