Skip to content

Repository files navigation

⚖️ Contract Diff

Contract and compliance review UX with clause grids, obligation tracking, redline planning, and risk controls.

PythonFastAPISQLiteLocal LLMCloud LLMNo Fake Data

Domain:Legal / Contract Ops · Suite:Legal & Compliance Suite · Accent:#c084fc

🚀 Quick Start · ✨ Features · 🎛️ Customization · 🧠 LLM Providers · 🧪 Testing · 🧯 Troubleshooting


🧭 What This Project Does

Contract Diff is a standalone, browser-based AI workflow app for Legal / Contract Ops. It turns structured inputs, uploaded files, and project-specific settings into reviewable outputs using a deterministic local engine plus optional local/cloud LLM enhancement.

Core job: Two contract versions → semantic change analysis.

Designed for: Domain operator, business owner, analyst, or team member who needs this workflow executed reliably.

Why use it:

  • 🧩 Standalone project folder: run this project by itself without depending on a central dashboard.
  • 🖥️ Elegant GUI: includes project-specific panels, structured forms, upload handling, output preview, and exports.
  • 🧠 Model-flexible: choose local models for privacy or cloud models for stronger reasoning.
  • 🧾 Auditable: every run is stored in SQLite with inputs, settings, result, and export history.
  • 🚫 No fake live data: external systems are only used when real API keys/connectors are configured.
  • 🛡️ Human review gates: sensitive legal, medical, hiring, finance, or security outputs are flagged for review.

✨ Features

  • semantic diff
  • risk delta
  • obligation changes
  • removed protections
  • party-favorable changes
  • approval checklist
  • redline memo

🧱 Built-In Platform Capabilities

  • FastAPI backend with documented JSON endpoints.
  • 🎨 Responsive web UI with dark, polished SaaS-style layout.
  • 📁 File upload and text extraction for common document/code formats.
  • 🗂️ Job history saved locally in data/*.sqlite3.
  • 🔐 Encrypted provider settings for API keys and local endpoints.
  • 📤 Exports to Markdown, JSON, DOCX, and PDF when dependencies are available.
  • 🔌 Provider routing for local and cloud LLMs.
  • 🧪 Local test file to verify the project runs.

🎨 UX/UI Design

UX profile:Legal Review Desk

Workflow layout: Document intake → clause map → risk heatmap → negotiation/actions

Empty state: Paste legal text or upload a document. This is decision support, not legal advice.

Main UI Components

  • Clause extraction grid
  • Risk heatmap
  • Obligation timeline
  • Redline/position panel
  • Negotiation checklist

Review / Workflow Lanes

  • Read
  • Classify
  • Risk-rate
  • Negotiate
  • Finalize

Metrics Shown in the Interface

  • Risk exposure
  • Missing clauses
  • Obligations found
  • Review readiness

Quick Actions

  • Extract clauses
  • Build risk matrix
  • Create negotiation points
  • Prepare redline checklist

🧩 Project Inputs

These are the main fields exposed by the GUI and /api/run. Required fields are enforced before execution.

FieldTypeRequiredDefaultPurpose
two_contract_versions
Two contract versions
textYesAffects input: Two contract versions.
work_brief
Work brief / source text / URL / instructions
textareaYesPaste the material, URL, description, or instruction needed for this project.

🎛️ Customization

This project is not a generic prompt box. The customization controls are connected to workflow behavior, validation, output shape, and export format.

FieldTypeRequiredDefaultPurpose
execution_mode
Execution mode
selectNoProductionControls strictness, depth, and output format for this project workflow.
contract_type
contract type
textNoAffects customization: contract type.
jurisdiction
jurisdiction
selectNoUnited StatesAffects customization: jurisdiction.
party_role
party role
selectNobuyer/clientAffects customization: party role.
materiality_threshold
materiality threshold
sliderNo50Affects customization: materiality threshold.
risk_tolerance
risk tolerance
sliderNo50Affects customization: risk tolerance.
clause_playbook
clause playbook
textareaNoAffects customization: clause playbook.
output_format
output format
selectNoMarkdownAffects customization: output format.
language
language
selectNoEnglishAffects customization: language.
privacy_mode
privacy mode
selectNocloud allowedAffects customization: privacy mode.
confidence_threshold
Confidence threshold
sliderNo75Items below this confidence are escalated to the human review queue.

Select / Option Controls

  • Execution mode: Draft, Production, Audit / strict review, JSON/API output
  • jurisdiction: United States, United Kingdom, European Union, Egypt, UAE, Saudi Arabia, Custom
  • party role: buyer/client, seller/vendor, employer, employee, landlord, tenant, disclosing party, receiving party, mutual, custom
  • output format: Markdown, JSON, CSV, PDF, DOCX, XLSX
  • language: English, Arabic, Egyptian Arabic, French, German, Spanish
  • privacy mode: cloud allowed, local only, redact sensitive data

🧠 LLM Providers

You can run the project with the local deterministic engine, or enhance the output with a configured LLM provider.

Supported Provider Types

Provider TypeExamplesBest For
Local OpenAI-compatibleOllama, LM Studio, vLLMPrivate files, offline/local workflows, cost control
Cloud OpenAI-compatibleOpenAI, OpenRouter, custom gatewayGeneral high-quality generation and structured output
AnthropicClaude modelsLong-context reasoning and document-heavy workflows
Google GeminiGemini modelsMultimodal or Google ecosystem workflows
MistralMistral APIFast European cloud models
Azure OpenAIAzure deploymentsEnterprise-controlled cloud deployment
AWS BedrockBedrock-hosted modelsAWS enterprise environments

Recommended Model Usage

Use CaseRecommendation
Draftingfast cloud or local instruct model
Reasoningstrong reasoning model
Private documentslocal model via Ollama/LM Studio/vLLM
Vision/PDF pagesvision-capable model when image pages are used

🚀 Quick Start

1) Clone or open this folder

cd contract-diff

2) Run on macOS / Linux / WSL

chmod +x run_gui.sh
./run_gui.sh

3) Run on Windows PowerShell

Set-ExecutionPolicy-Scope Process-ExecutionPolicy Bypass
.\run_gui_windows.ps1

4) Open the GUI

http://127.0.0.1:9111

🛠️ Manual Installation

Use this when you want full control instead of the run scripts.

cd contract-diff
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
pip install -r requirements.txt
cp .env.example .env # Windows: copy .env.example .env
uvicorn app.main:app --host 127.0.0.1 --port 9111

🔐 Environment Variables

The project can be configured through the GUI settings screen or .env/environment variables.

VariablePurpose
AI_SUITE_HOSTHost to bind the local app, usually 127.0.0.1.
AI_SUITE_PORTPort for this project GUI, default 9111.
AI_SUITE_DBSQLite database path for job history.
AI_SUITE_SECRET_KEYSecret used for local encryption/signing. Set this in production.
OPENAI_API_KEYEnables OpenAI-compatible cloud calls.
ANTHROPIC_API_KEYEnables Anthropic/Claude calls.
GEMINI_API_KEYEnables Google Gemini calls.
OPENROUTER_API_KEYEnables OpenRouter model routing.
MISTRAL_API_KEYEnables Mistral cloud models.
AZURE_OPENAI_ENDPOINTAzure OpenAI endpoint URL.
AZURE_OPENAI_API_KEYAzure OpenAI key.
AZURE_OPENAI_DEPLOYMENTAzure deployment name.
OLLAMA_BASE_URLLocal Ollama OpenAI-compatible base URL.
LMSTUDIO_BASE_URLLocal LM Studio OpenAI-compatible base URL.
VLLM_BASE_URLLocal vLLM OpenAI-compatible base URL.

🖥️ How to Use the GUI

  1. Open the local URL.
  2. Review the project purpose and workflow lanes.
  3. Fill the required input fields.
  4. Adjust only the project-related customization controls.
  5. Upload source files when needed.
  6. Choose Rule Engine for local deterministic output or select a configured LLM provider.
  7. Run the workflow.
  8. Review warnings, scorecards, and output sections.
  9. Export the result as Markdown, JSON, DOCX, or PDF.

🔄 Workflow

  • Two contract versions
  • semantic change analysis

Analysis Modules

  • text_diff
  • legal_clause_scan
  • risk_register

Output Sections

  • Semantic diff
  • Changed clauses
  • Risk delta
  • Negotiation checklist

Scorecards

  • Risk severity
  • Evidence strength
  • Negotiation impact
  • Obligation urgency
  • Missing protection risk

📤 Outputs & Exports

  • change memo
  • redline summary
  • obligation diff
  • approval checklist

The export system is designed for reviewable deliverables. For regulated or business-critical work, export drafts should be reviewed before sending to clients, customers, patients, employees, authorities, or production systems.


🔌 Real Integrations & Connector Policy

Configured integrations in this standalone folder:

  • File upload
  • REST API
  • Export download
  • Job history

Real Connector Requirements

  • approved legal playbook or clause library
  • jurisdiction-specific review by qualified counsel
  • document management/e-sign connector if exporting final agreements

Important: this project does not simulate live data. If a workflow needs live Shopify, ATS, ERP, tax, customs, medical, security, market, map, analytics, or repository data, it must be connected with valid credentials and real API access. Missing connectors should produce clear setup errors rather than invented results.


🧯 Guardrails

  • Show uncertainty and confidence
  • Cite evidence from input when possible
  • Human review required for legal, medical, financial, hiring, or security decisions
  • Do not invent facts absent from input

Recommended operating rules:

  • ✅ Use local models for private or sensitive files.
  • ✅ Keep API keys out of Git.
  • ✅ Review low-confidence or high-impact outputs manually.
  • ✅ Keep source files and exported deliverables organized under data/.
  • ❌ Do not treat AI output as legal, medical, tax, hiring, trading, or security authority without expert review.

🧪 Testing

Run the local smoke test:

python tests/test_single_project.py

Run a health check after starting the server:

curl http://127.0.0.1:9111/api/health

Expected result: the API returns ok: true and identifies this project.


🧬 API Usage

MethodEndpointUse
GET/Opens the browser GUI.
GET/api/healthHealth check for deployment and uptime monitoring.
GET/api/projectsReturns the local project configuration.
GET/api/projects/{slug}Returns the project plugin metadata.
GET/api/providersLists configured providers and local/cloud options.
POST/api/providersSaves provider settings/API keys.
POST/api/uploadUploads source files for extraction or context.
POST/api/runRuns the project workflow.
GET/api/jobsLists previous runs and job history.
GET/api/jobs/{job_id}Reads one completed job.
GET/api/jobs/{job_id}/export/{fmt}Exports a job as md, json, docx, or pdf.
GET/api/project-local-statusVerifies local project registration and implementation status.

Minimal Run Request

curl -X POST http://127.0.0.1:9111/api/run \
-H "Content-Type: application/json" \
-d '{ "inputs": { "work_brief": "Paste the source material or task details here" }, "customization": { "execution_mode": "Production" }, "provider": "rule_engine" }'

📁 Folder Structure

contract-diff/
├─ app/ # FastAPI backend, schemas, DB, providers, exports
├─ static/ # Browser GUI assets
├─ plugins/ # Project plugin JSON metadata
├─ data/ # SQLite DB, uploads, exports
├─ tests/ # Smoke tests
├─ project_config.json # Project-specific inputs, controls, UX, workflow
├─ PROJECT_IMPLEMENTATION.md # Implementation details and domain notes
├─ requirements.txt # Python dependencies
├─ run_gui.sh # macOS/Linux/WSL launcher
├─ run_gui_windows.ps1 # Windows PowerShell launcher
└─ README.md # This file

🚢 Deployment Notes

For local/private deployment, run with uvicorn behind a reverse proxy if needed. For production:

  • Set AI_SUITE_SECRET_KEY.
  • Use HTTPS.
  • Store provider keys in environment variables or a proper secret manager.
  • Restrict upload sizes and allowed file types.
  • Back up the SQLite database or move job storage to a managed database.
  • Add authentication before exposing beyond localhost.
  • Enable logging and monitoring.

Example production-style command:

AI_SUITE_HOST=0.0.0.0 AI_SUITE_PORT=9111 uvicorn app.main:app --host 0.0.0.0 --port 9111

🧯 Troubleshooting

ProblemFix
python not foundInstall Python 3.10+ and ensure it is on PATH.
PowerShell blocks the scriptRun Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass.
Port already in useSet another port: AI_SUITE_PORT=9200 ./run_gui.sh.
Provider failsVerify API key, base URL, selected model, and account quota.
Local model failsStart Ollama/LM Studio/vLLM before running the workflow.
PDF/DOCX export failsReinstall requirements and confirm optional export dependencies installed.
Upload extraction is incompleteUse cleaner source files or paste the important text into work_brief.

🧭 Extension Points

You can extend this project by editing:

  • project_config.json for inputs, settings, output sections, UX metadata, and workflow labels.
  • plugins/contract-diff.json for plugin metadata.
  • app/domain_engine.py for deterministic business logic.
  • app/llm_gateway.py for provider integrations.
  • static/app.js and static/styles.css for GUI behavior and component design.
  • tests/test_single_project.py for stronger project-specific tests.

✅ Final Implementation Status

AreaStatus
Standalone folder GUI✅ Implemented
FastAPI backend✅ Implemented
Project-specific config✅ Implemented
Local deterministic workflow✅ Implemented
Local/cloud LLM routing✅ Implemented
Uploads and exports✅ Implemented
Job history✅ Implemented
Real external connectors⚠️ Requires valid credentials/API setup
Fake/simulated live data❌ Not allowed

📜 License

Use the license included in this folder. If no explicit license is present, treat the code as private until you choose one.

About

Two contract versions to semantic change analysis

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages