contract-query/README.md
2025-08-14 15:03:33 -05:00

7.7 KiB

Contract Analysis Tool v2.0

A modern, production-ready Retrieval-Augmented Generation (RAG) application for intelligent contract analysis and document Q&A. Built with FastAPI backend and React frontend.

Architecture Frontend Database Cache

🚀 Features

  • Modern Architecture: FastAPI + React + MongoDB + Redis
  • AI-Powered Analysis: GPT-4 integration for contract analysis
  • Document Q&A: Natural language queries with RAG
  • User Management: Role-based access control
  • Real-time Processing: Async document processing
  • Intelligent Caching: Redis-based response caching
  • Scalable Design: Microservice-ready architecture

🏗️ Architecture

React Frontend → FastAPI Backend → MongoDB + ChromaDB → OpenAI API
                      ↓
                 Redis Cache

📋 Prerequisites

  • Python 3.11+
  • Node.js 18+
  • MongoDB 7+
  • Redis 7+
  • OpenAI API Key
  • LlamaParse API Key (optional)

🛠️ Installation

  1. Clone the repository

    git clone <repository-url>
    cd llama-contracts-master
    
  2. Set up environment variables

    # Backend
    cp backend/.env.example backend/.env
    # Edit backend/.env with your API keys
    
    # Frontend
    cp frontend/.env.example frontend/.env
    
  3. Start with Docker Compose

    cd backend
    docker-compose up -d
    
  4. Start the frontend

    cd frontend
    npm install
    npm run dev
    

Option 2: Manual Setup

Backend Setup

  1. Create Python virtual environment

    cd backend
    python3 -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  2. Install dependencies

    pip install -r requirements.txt
    
  3. Set up environment variables

    cp .env.example .env
    # Edit .env with your configuration
    
  4. Start MongoDB and Redis

    # MongoDB
    brew services start mongodb/brew/mongodb-community
    
    # Redis
    brew services start redis
    
  5. Start the backend

    uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
    

Frontend Setup

  1. Install dependencies

    cd frontend
    npm install
    
  2. Set up environment variables

    cp .env.example .env
    
  3. Start the development server

    npm run dev
    

🔧 Configuration

Backend Environment Variables

# Database
MONGODB_URL=mongodb://localhost:27017
DATABASE_NAME=contract_analysis

# Redis
REDIS_URL=redis://localhost:6379

# Authentication
JWT_SECRET_KEY=your-super-secret-jwt-key
JWT_ALGORITHM=HS256
JWT_EXPIRE_MINUTES=30

# OpenAI
OPENAI_API_KEY=your-openai-api-key
LLAMAPARSE_API_KEY=your-llamaparse-api-key

# Application
DEBUG=false
CORS_ORIGINS=["http://localhost:3000"]
UPLOAD_DIR=./uploads
INDICES_DIR=./indices

# Cache
CACHE_ENABLED=true
CACHE_TTL=3600

Frontend Environment Variables

VITE_API_URL=http://localhost:8000
VITE_APP_NAME=Contract Analysis Tool

🚀 Usage

Swagger Testing

Method 1: Get Token via Swagger UI (Easiest)

  1. Go to http://localhost:8000/docs
  2. First, initialize the default users by calling the /api/v1/auth/init-users endpoint
  3. Then use the /api/v1/auth/login endpoint with these credentials:

Admin User:

Regular User:

  1. Copy the access_token from the response
  2. Click the "Authorize" button at the top of Swagger UI
  3. Enter: Bearer YOUR_TOKEN_HERE

Initial Setup

  1. Access the application: http://localhost:3000
  2. Initialize default users (first time only):
    curl -X POST http://localhost:8000/api/v1/auth/init-users
    

Default Credentials

  • Admin: admin@oliver.agency / admin123
  • User: user@oliver.agency / user123

Workflow

  1. Login with admin or user credentials
  2. Create an Index for your document collection
  3. Upload Documents to the index
  4. Chat with your documents using natural language
  5. Manage Users (admin only)

📚 API Documentation

Key Endpoints

  • POST /api/v1/auth/login - User authentication
  • POST /api/v1/indices/create - Create document index
  • POST /api/v1/documents/upload - Upload documents
  • POST /api/v1/chat/query - Query documents
  • GET /api/v1/admin/stats - System statistics

🔒 Security Features

  • JWT Authentication with role-based access
  • Input Validation with Pydantic schemas
  • CORS Protection for frontend integration
  • File Upload Validation with type/size checks
  • Rate Limiting (configurable)
  • Environment Variable Protection

Performance Features

  • Async Processing throughout the backend
  • Redis Caching for API responses
  • Vector Search with ChromaDB
  • Connection Pooling for databases
  • Optimized Queries with MongoDB indexes

🧪 Development

Backend Development

cd backend
source venv/bin/activate
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

Frontend Development

cd frontend
npm run dev

Database Migration

The application automatically creates database collections and indexes on startup.

📊 Monitoring

Health Check

curl http://localhost:8000/health

System Stats (Admin)

curl -H "Authorization: Bearer <token>" http://localhost:8000/api/v1/admin/stats

🐛 Troubleshooting

Common Issues

  1. MongoDB Connection Failed

    • Ensure MongoDB is running: brew services start mongodb-community
    • Check connection string in .env
  2. Redis Connection Failed

    • Ensure Redis is running: brew services start redis
    • Application will continue without caching if Redis is unavailable
  3. OpenAI API Errors

    • Verify API key in backend .env
    • Check API quota and billing
  4. File Upload Issues

    • Check file size limits (50MB default)
    • Verify file types are supported
    • Ensure upload directory permissions

Logs

  • Backend logs: Console output from uvicorn
  • Frontend logs: Browser console
  • Database logs: MongoDB logs in data directory

🔄 Migration from v1.0

The new system provides complete feature parity with the original PHP application:

  • All PHP functionality migrated to FastAPI
  • SQLite data can be migrated to MongoDB
  • Existing ChromaDB indices are compatible
  • All document processing features preserved
  • Enhanced performance and security

🚀 Deployment

Production Deployment

  1. Set production environment variables
  2. Use production database URLs
  3. Enable HTTPS with SSL certificates
  4. Configure reverse proxy (Nginx)
  5. Set up monitoring and logging
  6. Regular backups of MongoDB

Docker Production

docker-compose -f docker-compose.prod.yml up -d

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

📄 License

This project is licensed under the MIT License.

🙏 Acknowledgments

  • OpenAI - GPT-4 and embedding models
  • LlamaIndex - RAG framework
  • ChromaDB - Vector storage
  • FastAPI - Modern Python web framework
  • React - Frontend framework

Built with ❤️ for intelligent contract analysis