Skip to content

itachimoonshot/contract-forge

Repository files navigation

Contract Analysis System

Python License: MIT FastAPI CrewAI Next.js

An AI-powered contract analysis system built with CrewAI agents, a FastAPI backend, and a Next.js frontend. Designed to run fully locally using LM Studio or Ollama — no cloud dependencies required.

Upload contracts, ask questions, and get detailed analysis covering conflicts, similarities, and compliance issues — all processed by a pipeline of specialized AI agents.


Table of Contents


Features

  • Fully local AI — Runs on LM Studio or Ollama; OpenAI supported as optional fallback
  • Multi-agent pipeline — 4 specialized CrewAI agents handle retrieval, citation, conflict detection, and report generation
  • Vector search — Qdrant (default) or ChromaDB for semantic contract search
  • Real-time progress — WebSocket-powered dashboard with per-agent status tracking
  • REST API — FastAPI backend with authentication, rate limiting, and full OpenAPI docs
  • Modern frontend — Next.js 15 with React Query, Zustand, and Tailwind CSS
  • Document support — PDF, DOC, DOCX, and TXT file uploads

Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Next.js 15    │    │   FastAPI        │    │   CrewAI        │
│   Frontend      │◄──►│   Backend        │◄──►│   Agents        │
│   (Port 3000)   │    │   (Port 8000)    │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │                       │
                    ┌───────────┴──────┐    ┌──────────┴──────────┐
                    │   Local AI       │    │   Vector DB         │
                    │   LM Studio      │    │   Qdrant            │
                    │   / Ollama       │    │   (Port 6333)       │
                    └──────────────────┘    └─────────────────────┘

Agent Pipeline

The system processes each analysis request through 4 sequential agents:

Agent Role
Data Retrieval Specialist Semantic search over contract vectors
Source Citer Specialist Identifies and cites contract sources with section/paragraph references
Conflicts of Interest Specialist Detects contradictions and conflicts across contracts
Report Generation Specialist Compiles a structured final analysis report

Supported AI Providers

Provider Default URL Notes
LM Studio http://localhost:1234/v1 Recommended for local use
Ollama http://localhost:11434 Alternative local provider
OpenAI https://api.openai.com/v1 Optional cloud fallback

Supported Vector Databases

Database Default URL Notes
Qdrant http://localhost:6333 Default, high-performance
ChromaDB http://localhost:8000 Configurable alternative

Prerequisites

  • Python 3.10–3.13
  • uv package manager
  • Docker and Docker Compose
  • Node.js 18+
  • One of: LM Studio, Ollama, or an OpenAI API key

Quick Start

1. Start Infrastructure

# Start Qdrant vector database
docker-compose up -d

# Verify it's running
curl http://localhost:6333/health

2. Install Dependencies

# Python backend
uv sync

# Frontend
cd frontend && npm install

3. Configure Environment

cp .env.example .env
# Edit .env with your AI provider and settings

Key settings:

LOCAL_AI_PROVIDER=lm_studio        # or: ollama, openai
LOCAL_AI_LLM_MODEL=llama-3.1-8b-instruct
LOCAL_AI_EMBEDDING_MODEL=all-MiniLM-L6-v2
API_SECRET_KEY=your_secret_key_here

4. Start Services

# Terminal 1 — Backend API
uv run start_api

# Terminal 2 — Frontend
cd frontend && npm run dev

5. Open the Application

Service URL
Frontend http://localhost:3000
API http://localhost:8000
API Docs http://localhost:8000/docs
Qdrant UI (dev) http://localhost:3000

Configuration

All configuration is managed via the .env file. Copy .env.example to get started.

Core Variables

# AI Configuration
LOCAL_AI_PROVIDER=lm_studio
LOCAL_AI_LM_STUDIO_BASE_URL=http://localhost:1234/v1
LOCAL_AI_OLLAMA_BASE_URL=http://localhost:11434
LOCAL_AI_LLM_MODEL=llama-3.1-8b-instruct
LOCAL_AI_EMBEDDING_MODEL=all-MiniLM-L6-v2
LOCAL_AI_MAX_TOKENS=4096
LOCAL_AI_TEMPERATURE=0.7

# Vector Database
QDRANT_URL=http://localhost:6333
QDRANT_COLLECTION_NAME=contracts
VECTOR_SIZE=384                    # 384 for local embeddings, 1536 for OpenAI

# Contract Storage
CONTRACTS_DIR=knowledge/contracts

# Security
API_SECRET_KEY=your_secure_key_here
FRONTEND_URL=http://localhost:3000

# Optional: OpenAI fallback
LOCAL_AI_OPENAI_API_KEY=

API Reference

Full interactive documentation is available at http://localhost:8000/docs when the server is running.

Method Endpoint Description
GET /health System health check
POST /api/contracts/upload Upload contract files
POST /api/analysis/start Start agent analysis pipeline
GET /api/ai/status AI provider availability
GET/POST /api/settings Read or update system configuration
WS /api/ws/{task_id} Real-time analysis progress stream

All endpoints except /health require Authorization: Bearer <API_SECRET_KEY>.


Development

Backend

# Install with dev dependencies
uv sync --dev

# Run with auto-reload
uvicorn contract_analysis.api.main:app --reload

# Run tests
uv run pytest

# Run CrewAI pipeline directly (bypass API)
uv run crewai run

Frontend

cd frontend

npm run dev          # Development server
npm run build        # Production build
npm run type-check   # TypeScript check
npm run lint         # ESLint

Project Structure

.
├── src/contract_analysis/
│   ├── api/main.py              # FastAPI application
│   ├── crew.py                  # CrewAI agent definitions
│   ├── local_ai_service.py      # Unified AI provider interface
│   ├── services.py              # Document processing and vector storage
│   ├── models.py                # Pydantic data models
│   └── config/
│       ├── agents.yaml          # Agent configurations
│       └── tasks.yaml           # Task configurations
├── frontend/
│   ├── app/                     # Next.js app router
│   ├── components/              # React components
│   └── lib/                     # Utilities and API client
├── knowledge/contracts/         # Contract file storage
├── docker-compose.yml           # Infrastructure services
├── pyproject.toml               # Python project config
└── .env.example                 # Environment variable template

Docker Support

# Start all services
docker-compose up -d

# Start with Qdrant Web UI (development)
docker-compose --profile dev up -d

# Stop all services
docker-compose down

# View logs
docker-compose logs -f qdrant

Troubleshooting

LM Studio not detected

Ensure LM Studio is running and has a model loaded. Check it is accessible:

curl http://localhost:1234/v1/models

Qdrant connection failed

Verify the Docker container is running:

docker-compose ps
curl http://localhost:6333/health

Frontend build fails

Ensure Node.js 18+ is installed:

node --version

Python import errors

Reinstall dependencies:

uv sync

Security

See SECURITY.md for a full breakdown of implemented security controls including:

  • API key authentication on all endpoints
  • Rate limiting per endpoint
  • File upload validation (type, size, path traversal prevention)
  • CORS configuration
  • WebSocket connection limits
  • Docker network isolation

To report a security vulnerability, open a GitHub Issue marked as security.


License

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


Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/your-feature)
  3. Commit your changes
  4. Push to the branch and open a pull request

Built with CrewAI, FastAPI, and Next.js.

About

AI-powered contract analysis system using CrewAI agents, FastAPI, and Next.js. Runs fully locally with LM Studio or Ollama.

Resources

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages