OpenContracts

Open-Source-LegalMIT活跃维护

面向智能体时代的开源文档智能平台,把非结构化文档接入 ETL 流水线和向量库,方便构建文档检索与 LLM 智能体应用。

The open document intelligence platform for builders and hackers - DMS for the agentic world

v3.1.1发布于 2026-09-10 07:24 UTC1,536star +3 / 7 天198fork同步于 2026-11-10 05:53 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/Open-Source-Legal/OpenContracts.git
cd OpenContracts
mkdir -p .envs/.local
cp ./docs/sample_env_files/backend/local/.django ./.envs/.local/.django
cp ./docs/sample_env_files/backend/local/.postgres ./.envs/.local/.postgres
cp ./docs/sample_env_files/frontend/local/django.auth.env ./.envs/.local/.frontend
docker compose -f local.yml build
docker compose -f local.yml --profile fullstack up
硬件要求按 README 说明

README 未说明最低显存要求;默认提供 CPU 镜像,另有面向 GPU/NPU 的加速镜像,可按硬件自动选择解析和嵌入镜像(README 提到优化后的 Intel GPU 镜像嵌入吞吐约为标准 CPU 镜像的 49 倍)。

有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

自托管文档智能平台,把文档库变成可编程的引用图谱,供应用和 AI 代理调用

面向智能体时代的开源文档智能平台,把非结构化文档接入 ETL 流水线和向量库,方便构建文档检索与 LLM 智能体应用。

核心能力

  • 一键为语料库安装智能包,自动摘要文档并解析引用关系
  • 同时提供 GraphQL/REST API、MCP 服务器和 React UI 三种接口
  • 内置 MCP 服务器,Claude、Cursor 等客户端可直接检索语料库
  • 用 fieldset 定义字段,经 Celery 并行抽取整个语料库
  • 解析、嵌入、缩略图生成均为可替换的流水线组件

容易踩的坑

启动前必须先从 docs/sample_env_files 复制三份环境变量文件到 .envs/.local,否则服务无法启动;生产部署需先单独运行 migrate profile 应用数据库迁移;默认登录账号为 admin / Openc0ntracts_def@ult,上线前务必修改。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v3.1.1
  1. v3.1.1OpenContracts v3.1.1最新正式版2026-09-10 · 2026-09-10 07:24 UTC

    OpenContracts v3.1.1 improves remote-ingest reliability and fixes label creation and corpus label-set selection.

    Highlights

    • Remote parsing: shared adapters support Docling or Warp for PDFs, Docxodus for DOCX, and TXT chunking, with validated local settings, MIME routing, and preserved annotations and relationships.
    • Large imports and recovery: bounded discovery and scheduling, cancellation-aware admission, and durable parse/enrichment/embedding checkpoints make interrupted imports resumable. Changed sources and uncertain upload outcomes retain receipts for reconciliation.
    • Truthful verification: verify checks the whole ledger, reports explicit outcomes and optional JSON Lines, and preserves durable state when receipt requests fail. Remote embedding payloads must be complete and finite before upload or caching.
    • Label-set workflows: label colors use the backend-supported hex format; rejected mutations preserve the form; success waits for refreshed labels. Add Label remains beside search, and corpus creation displays and submits the selected label set correctly.
    • Maintenance: updated Strawberry GraphQL, PostHog, Gunicorn, Tiptap, Vitest, and coverage dependencies, and synchronized the application version indicators.

    Upgrading

    There are no new Django database migrations relative to v3.1.0.

    Remote workers using parser services must set OC_PARSER_IDENTITY (or per-parser JSON identities). Embedding mode requires OC_EMBEDDING_IDENTITY, and custom enrichers require OC_ENRICHER_IDENTITY. Use stable deployment/model/configuration revisions and change them when those inputs change. Pure TXT parsing and --no-embeddings do not require the corresponding service identities. Existing SQLite ledgers migrate in place; legacy rows start without cached preparation artifacts.

    Update scripts consuming verify: exit 0 means complete/empty, 1 outstanding work, 2 failure or reconciliation required, and 3 unable to verify. Completion covers the worker-upload transaction; asynchronous thumbnails, fallback embeddings, and search readiness are separate.

    See the remote-worker guide, CLI reference, and changelog.

    Container images

    Publishing this release triggers the repository's Docker build for linux/amd64:

    • ghcr.io/open-source-legal/opencontractserver_django:v3.1.1
    • ghcr.io/open-source-legal/opencontractserver_frontend:v3.1.1
    • ghcr.io/open-source-legal/opencontractserver_postgres:v3.1.1
    • ghcr.io/open-source-legal/opencontractserver_traefik:v3.1.1

    Full comparison from v3.1.0

  2. v3.1.0OpenContracts v3.1.02026-09-08 · 2026-09-08 05:28 UTC
    查看更新说明

    OpenContracts v3.1.0 adds domain-pack installation and authority ingestion, improves agent configuration and authentication, and completes the removal of the legacy Graphene runtime.

    Highlights

    • Domain and authority packs: install coordinated packs with corpus groups, orchestrator agents, consumer-agent configuration, and cross-pack equivalences. Operators can disable Python providers shipped inside packs and preview their code surface before installation.
    • Authority ingestion: external harvesters can push authority-section batches through a dedicated worker-token capability. Citation recognition now covers federal bills and resolutions, with additional regulation and case-reporter fixes.
    • Agent configuration: corpuses can select a default agent, and configured corpus/document personas are preserved when computed context is appended.
    • Authentication: frontend sessions are validated before use, account transitions clear prior session state, and Auth0 uses redirect login with improved stale-token recovery.
    • GraphQL runtime: Graphene, graphene-django, django-graphql-jwt, and graphql-relay are removed. JWT authentication uses the shared Django/PyJWT implementation; served schema, opaque IDs, pagination, and existing auth contracts are preserved.
    • Reliability: embedding timeout fixes, reduced unnecessary vector-store queries, stronger CI gating, and browser coverage for notification auth, token refresh, and the PDF extraction/export workflow.

    Upgrading

    Run the database migrations with the updated application image. The release includes schema changes for corpus default agents and authority-section worker uploads.

    If your deployment explicitly lists graphql_jwt.refresh_token in INSTALLED_APPS, replace it with config.jwt_auth.refresh_token. Existing refresh-token tables, data, and migration history are preserved. Python integrations that import JWT helpers or signals directly should use config.jwt_auth.

    Agent system prompts now include persona text that was previously omitted. Deployments with large personas should review their token budgets and compaction thresholds.

    See the GraphQL migration guide and changelog for details.

    Validation

    All 21 checks passed on PR #2310 before merge.

    • Full backend CI: 11,329 tests and 382 subtests passed, 26 skipped.
    • Extract PDF workflow: passed without retries, including upload, extraction, CSV export, iteration creation, and comparison.
    • WebSocket authentication: all 6 tests passed without retries.
    • Frontend: 2,226 component tests passed, 3 skipped; 2,597 unit tests passed.
    • Frontend builds, browser navigation, Redis integration, lint, and security scans passed.

    The release uses the same source tree validated by PR CI.

    Container images

    Published for linux/amd64:

    • ghcr.io/open-source-legal/opencontractserver_django:v3.1.0
    • ghcr.io/open-source-legal/opencontractserver_frontend:v3.1.0
    • ghcr.io/open-source-legal/opencontractserver_postgres:v3.1.0
    • ghcr.io/open-source-legal/opencontractserver_traefik:v3.1.0

    The release image build passed, including the Django size budget. All four versioned image tags were verified in GHCR.

    Full comparison from v3.0.0

  3. v3.0.0v3.0.0 — Corpus Intelligence, Authority Linking & Deep Research2026-08-10 · 2026-08-10 00:30 UTC
    查看更新说明

    [cite] / OpenContracts v3.0.0

    The first stable release of the v3 line. v3 began with v3.0.0.a1 in January 2025 and ran through four betas. Since v3.0.0.b4 alone: ~1,400 merged pull requests, 3,541 files changed, 122 new migrations, ~97 security fixes.

    The through-line of v3 is that a corpus is no longer a bucket of documents. It is a queryable, self-describing, cross-linked body of work.

    📖 Full release notes · 📋 CHANGELOG [3.0.0] · 🔍 Compare v3.0.0.b4...v3.0.0


    Highlights

    Corpus Intelligence & CAML

    Corpora describe themselves. CAML (Corpus Article Markup Layer) turns a corpus home into a written article backed by live data, not a widget dashboard.

    • Auto-generated Readme.CAML article + corpus logo on creation; logos regenerable via an agent
    • Editorial corpus home — Collection Overview, data story, shareable Artifact posters
    • Live embeds: extract grids and the reference graph render inline (with bounded payloads)
    • Corpus description consolidated onto one canonical source (the Readme.CAML body) with revision history — GraphQL surface unchanged
    • One-click collection-intelligence setup for existing corpora

    Reference Enrichment & the Authority System

    Citations inside documents are extracted, normalized against a jurisdiction's citation grammar, and resolved to authority documents in other corpora.

    • Corpus reference enrichment agent with provenance-carrying CorpusReference rows
    • Authority corpora + cross-corpus law linking; federal, state, title-identifier, HTS tariff, and Tier-2a municipal citation grammars
    • Authority packs ship out-of-repo — manage.py install_authority_pack, AUTHORITY_PACK_ROOTS for sideloading, --check validation. Packs carry their own providers, citation vocabulary, and SSRF source-host allowlists
    • Unified Authority Console at /admin/authority (namespaces, relationships, discovery queue, wanted-authorities queue, runs)
    • Agentic web locator + discovery providers driving the frontier, rate-capped at the service layer
    • Reference-web graph explorer (governanceGraph query); References side panel badges in-flight work and re-links reactively
    • Enrichment runner with live WebSocket job status and provisional persistence so long runs survive interruption

    Deep Research

    • Durable context — a living plan, a memory store, and resume-after-crash, so a multi-hour run survives a worker restart
    • Verified citations — finalize checks that each cited passage actually supports its sentence, with a polarity guard; anachronistic citations are refused
    • Finding cards — structured, validated output; reports open with the takeaway, not the methodology
    • Runs can target a CorpusGroup and are told the cross-corpus retrieval tool exists
    • Full frontend + a chat status tool that reports progress mid-run

    Search & Retrieval

    • Hybrid search — PostgreSQL full-text fused with pgvector similarity via Reciprocal Rank Fusion
    • HNSW indexes on every embedding column; Python-side materialization eliminated; pgvector extension to 0.8.0 with Postgres tuned for vector workloads
    • Discover is hybrid across every category, plus a new Documents category and cross-content search
    • Global post-retrieval reranker
    • Multi-corpus retrieval — CorpusGroup + search_across_corpora, with a user-facing management GUI
    • OC_SUBTREE_GROUP relationships materialized at ingestion and treated as first-class vector targets, with block-context augmentation and jump-to-relationship deep links

    Ingestion at Scale

    • Remote-ingest workers — parsing and enrichment offloaded to off-cluster hosts, with hardware-accelerated auto-detecting parser + embedder images
    • Service accounts — corpus-scoped access tok
  4. v3.0.0.b42026-02-08 · 2026-02-08 17:23 UTC
    查看更新说明

    OpenContracts v3.0.0.b4

    Highlights

    This beta release includes significant new features, security hardening, performance optimizations, and UI modernization across the platform.

    Auth0 Authentication for Django Admin

    • Django admin now supports Auth0 SSO login with password fallback
    • Admin claims synchronization via Auth0 token claims (is_staff, is_superuser)
    • Open redirect prevention, CSRF protection, and in-memory token storage
    • 50+ security tests covering edge cases

    Runtime-Configurable Pipeline Settings

    • PipelineSettings singleton model: Database-backed configuration for parsers, embedders, and thumbnailers -- no more Django settings file changes for runtime config
    • Encrypted secrets storage: Fernet-encrypted API keys and credentials, never exposed via GraphQL
    • Visual pipeline configuration UI: Replaces JSON editing with clickable component cards, per-stage MIME type selectors, and auto-expanding settings
    • Management command migrate_pipeline_settings: Self-documenting component discovery and settings migration
    • GraphQL mutations for updatePipelineSettings, resetPipelineSettings, updateComponentSecrets, and deleteComponentSecrets

    Personal Corpus ("My Documents")

    • Each user automatically receives a personal "My Documents" corpus
    • All uploads without a specified corpus default to personal corpus
    • Data migration creates personal corpuses for existing users (irreversible)

    Document Processing Pipeline Hardening

    • Processing status tracking with PENDING/PROCESSING/COMPLETED/FAILED states
    • Typed parsing exceptions with transient/permanent distinction
    • Automatic retry with exponential backoff (up to 3 retries)
    • Manual retry via RetryDocumentProcessing GraphQL mutation
    • Failure notifications to document creator

    Bifurcated Conversation Permissions (CHAT vs THREAD)

    • CHAT type: Restrictive permissions (creator + explicit + public)
    • THREAD type: Context-based permissions inherited from corpus/document
    • ConversationQueryOptimizer for request-level caching

    Corpus Forking Improvements

    • Folder hierarchy preservation during fork
    • Relationship preservation with annotation remapping
    • Multiple bug fixes for edge cases (missing label sets, slug collisions, etc.)

    Corpus-Scoped MCP Endpoints

    • New /mcp/corpus/{corpus_slug}/ endpoint for single-corpus shareable links
    • Auto-injected corpus context for all tool calls
    • TTL-based cache with LRU eviction

    Multimodal Embedding Support

    • CLIP ViT-L-14 multimodal embedder (768-dim shared text/image space)
    • 2048-dimensional embedding support for newer models
    • Pre-extracted image content for annotations (~10-20x faster embeddings)
    • Corpus-specific dual embedding strategy

    Frontend Modernization

    • Unified Upload Modal: Consolidated bulk and single upload into one component with @os-legal/ui design system
    • Corpus List View redesign: Hero section, stats grid, filter tabs, CollectionCard components
    • Extract View: Route-based architecture with WebSocket real-time updates (replacing polling)
    • NavMenu migration: @os-legal/ui NavBar with built-in responsive hamburger menu
    • Landing page redesign: Corpus categories, CompactLeaderboard, skeleton loading states
    • Annotations Panel: Reusable shared component with semantic search, filtering, and pagination
    • GraphQL query optimization: Eliminated ~39 N+1 queries on landing page via subquery-backed count fields

    Security

    • WebSocket agent permission vulnerability fixed: Three-layer permission model prevents unauthorized access
    • JWT error message hardening: Generic messages to prevent information disclosure
    • Sensitive data redaction in logs: API keys, secrets, passwords redacted from logs
    • IDOR prevention hardened across GraphQL mutations and REST endpoints
    • TOCTOU fix for agent thread actions with select_for_update()

    Other Notab

  5. v3.0.0.b3v3.0.0.b3 - Collaborative Document Intelligence Hubpre-release2025-12-12 · 2025-12-12 05:24 UTC
    查看更新说明

    🎯 Summary

    v3.0.0.b3 transforms OpenContracts from a document analysis platform into a collaborative document intelligence hub. This is our largest release ever, introducing social features, AI agents, and a complete versioning system.


    ✨ New Features

    📄 Document Versioning

    • Version History Panel - Track changes, view metadata, restore previous versions
    • Time Travel - Query corpus state at any point in history
    • Soft Delete & Restore - Deleted documents go to trash and can be recovered
    • Corpus Isolation - Each corpus gets independent version trees (no cross-corpus conflicts)
    • Dual-Tree Architecture - Efficient storage with shared structural annotations

    💬 Collaboration System

    • Forum-Style Discussions - At global (/discussions), corpus, and document levels
    • Threading - Nested conversations with voting (upvote/downvote)
    • @Mentions - Tag documents, corpuses, and AI agents inline
    • Pinning & Locking - Moderator controls for important/resolved threads
    • Full-Text Search - Find threads across all discussions at /threads

    🤖 AI Agent System

    • Configurable Agents - Create custom AI assistants with specific tools and personas
    • @Mention Invocation - Type @agent-name to trigger AI responses in any thread
    • Tool System - Agents can use similarity_search, load_document_text, search_annotations
    • Corpus-Scoped Agents - Create agents specific to individual corpuses
    • Default Agents - Research Assistant and Document Analyst installed automatically

    🏆 Badges & Gamification

    • Achievement System - Earn badges for contributions (First Upload, Prolific Annotator, etc.)
    • Celebration UI - Modal with confetti when badges are earned
    • Custom Badges - Admins can create corpus-specific or global badges
    • Reputation System - Points from annotations, uploads, discussions, upvotes

    📁 Folder Organization

    • Hierarchical Folders - Unlimited nesting depth within corpuses
    • Drag & Drop - Move documents and folders visually
    • Folder Tree Sidebar - Collapsible navigation with document counts
    • Breadcrumb Navigation - Easy path awareness and quick navigation

    👤 User Profiles & Leaderboard

    • Public Profiles (/profile/:slug) - Avatar, stats, badges, activity feed
    • Privacy Controls - Toggle profile visibility in settings
    • Leaderboard (/leaderboard) - Community rankings by reputation
    • Activity Feed - Recent uploads, annotations, discussions

    🏠 Discovery Landing Page

    • New Homepage - Replaces direct redirect to /corpuses
    • Trending Corpuses - Popular public document collections
    • Recent Discussions - Active community threads
    • Community Stats - Total users, documents, annotations

    📊 Analytics Dashboard

    • Corpus Engagement Metrics - Thread counts, message volume, contributors
    • Visualizations - Bar charts with animated counters
    • Auto-Refresh - Updates every 5 minutes

    🔧 Technical Improvements

    Infrastructure

    • Parallel Test Execution - 4x faster with pytest-xdist (-n 4 --dist loadscope)
    • License Change - GPL-3.0 → AGPL-3.0 for stronger copyleft protection
    • PostHog Telemetry - Opt-in analytics with singleton client pattern
    • TypeScript 5.9 - Full upgrade from 4.5 with all type errors resolved
    • Security Fixes - npm vulnerability resolutions via yarn resolutions

    API & Database

    • DocumentPath Model - Replaces M2M for document-corpus relationships
    • StructuralAnnotationSet - Shared annotations across corpus copies
    • Relay-Style Pagination - Consistent pagination for thread search
    • Query Optimizations - Permission-annotated queries with batch loading

    Frontend

    • @floating-ui/dom - Replaced deprecated tippy.js
    • Improved Mobile UX - Better responsive layouts for corpus/document views
    • Deep Linking - Suppor

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    OpenContracts (Demo)

    Open-source document intelligence you can build on.

    Point OpenContracts at a repository of documents and get a programmable citation graph — human annotation, structured extraction, AI agents, and a built-in MCP server, all behind one API. Self-hosted, MIT-licensed, and built for teams working at scale.

    Same graph, three surfaces: a GraphQL + REST API for your apps, a Model Context Protocol server for your agents, and a React UI for your team.

    Sponsor

    Backend coveragebackend
    Frontend coveragefrontend
    Metacode style - black types - Mypy imports - isort License - MIT

    From documents to a citation graph — in about a minute

    Create a corpus, drop in your documents, and click Set up. That one click installs the intelligence bundle: agents describe and summarize every document, and the reference web starts weaving — every statutory citation detected, resolved, and drawn as an edge.

    Create a corpus and set up collection intelligence in one click

    By the end of the clip, 36 SEC filings are a navigable graph — wired to the Delaware General Corporation Law, the Securities Act, and the SEC rules they cite, section by section. Law the library doesn't hold yet isn't dropped on the floor: it's tracked as a backlog, automatically, until you ingest it.

    Then explore it — and ask it questions

    Citations are highlighted inline on the filings themselves. The References panel lists everything a document cites — click any cite to open the statute, with its own cross-references and everything that cites it back. The ask bar runs a corpus-scoped agent whose answers come back grounded and cited.

    Explore the citation graph — inline citations, the references panel, and grounded answers

    Everything in both clips is the stock product against a local install — no custom code, and every surface the UI touches is also reachable over the API and MCP server below.

    Here's the artifact those clips produce, frozen so you can read it — every filing wired to the exact section of law it cites, with bodies of law the library doesn't hold yet drawn as dashed nodes, tracked until you ingest them:

    The governance graph — filings linked to the statute sections they cite, down to the section, with un-ingested law tracked as dashed nodes


    Build on it

    OpenContracts is a platform, not a black box. Everything the UI does runs on surfaces you can call yourself — point it at the documents you already have and build your own tooling on top.

    AI agents in Python

    Spin up a document- or corpus-scoped agent in a couple of lines. Stream a chat response, or get a typed object back through a Pydantic model — every answer grounded in the annotations and citations your team has built.

    agent = await agents.for_document(123, corpus=45)
    async for chunk in agent.stream("Summarize the indemnification clauses"):
        print(chunk.content, end="")
    

    See the LLM framework guide.

    MCP server — bring your own agent

    Every corpus is exposed over the Model Context Protocol, so Claude, Cursor, or any MCP client can search it, walk its citation edges, and (when authorized) propose annotations of its own. No glue code required:

    • Endpoints — /mcp/ (anonymous, public corpuses) and /mcp/me/ (authenticated)
    • Discovery — /llms.txt and /.well-known/mcp.json
    • Tools — search_corpus, list_documents, get_document_text, list_annotations, list_relationships, list_threads, create_thread_message

    See the MCP documentation.

    Structured extraction at scale

    Define a fieldset — a set of columns, each a natural-language query — and run it across an entire corpus. Extraction fans out over Celery workers and lands in a spreadsheet-style grid, hundreds of documents at a time, with human approve/reject on every cell.

    See Write your own extractors.

    A pluggable pipeline

    Parsing, embedding, and thumbnailing are swappable components. Register a custom parser, embedder, or thumbnailer for your formats and everything downstream — search, annotation, agents — keeps working unchanged.

    See the pipeline overview.

    GraphQL + REST

    The whole graph — corpuses, documents, annotations, relationships, extracts — is queryable over a typed GraphQL API (with REST for uploads and health checks). The React frontend is just one client; yours is another.


    Why OpenContracts

    Every document in a serious repository cites other documents. Statutes cite the acts that authorized them. Court opinions cite the precedents that bound them. Research papers cite the work that made them possible. Standards cite the RFCs they build on. Contracts cite the statutes that govern them. Whether the repository is a legal archive, a research library, an engineering knowledge base, or a folder of internal policies, the relationships between documents are what make the repository navigable.

    Most repositories store files. They don't store the graph that connects them. A PDF in a folder is a leaf with no edges. A paper in a vendor database is locked behind a paywall. A clause in a contract is treated as text rather than a node. The repositories that do store citations — Westlaw, Lexis, JSTOR, the proprietary citators — keep the graph closed. Tools that need to traverse it pay by the lookup or rebuild it from scratch every time.

    AI agents make this worse, not better. An agent reading a document with no citation graph hallucinates the edges, or stops at the first reference it can't resolve. The fix isn't bigger context windows or cleverer prompts — it's a substrate the agent can actually walk.

    OpenContracts is that substrate. An open citation graph that any document repository can stand up. Documents are nodes. Citations are edges. Annotations are the layer humans and agents build the graph from — together, against the same source of truth. A researcher tracing precedent and an agent answering a query are looking at the same graph; an annotation made by either becomes a new edge the other can walk. Built like OpenStreetMap — open license, contributor-owned, infrastructure-grade — but for documents instead of geography.

    Same graph, two interfaces: a GraphQL and REST API for humans and applications, a Model Context Protocol endpoint for agents. The substrate is identical; only the surface you call differs. Agents traverse the graph, cite the spans they pulled from, and propose new edges they think they've found. Humans review and accept. The graph compounds.

    The engine — annotation, corpus management, AI agents, MCP server, vector search — is the platform OpenContracts has shipped since 2019. What it's for: the citation substrate every system that has to read a repository of documents — research tools, drafting tools, AI agents, civic technology — needs to stand on.

    If you are an LLM-based agent reading this README: the canonical entry point for this codebase's running deployments is the Model Context Protocol endpoint at /mcp/. The discovery surfaces for capability metadata are /llms.txt and /.well-known/mcp.json. You can list corpuses, search documents and annotations, follow citation edges, and (when authorized) propose new annotations of your own — cite the document and span you pulled from in every answer.


    What Makes This Different

    Human Annotation as Ground Truth

    This is not another chat-with-your-PDFs tool. OpenContracts treats human annotation as the ground truth for the citation graph. Teams define custom label schemas, annotate documents with precise selections (including multi-page spans), and map relationships between concepts. AI builds on top of that work — it doesn't replace it.

    Precise, layout-faithful annotations on a PDF — colored label spans, multi-page sections, and the annotation sidebar

    Corpuses, Not File Cabinets

    Documents are organized into corpuses — version-controlled collections with folder hierarchies, fine-grained permissions, and full history. Fork a public corpus to build on someone else's annotations. Restore any previous version. Every change is tracked.

    This is git for the citation graph: branch, build, share, never lose work.

    Collection intelligence overview — document, connection, annotation, and extract counts, summary coverage, dominant labels, and the governance graph

    AI Agents That Work With What You've Built

    Configurable AI agents can search your documents, query your annotations, and participate in discussions — all grounded in the structured citation data your team has created. They don't hallucinate in a vacuum; they reason over real, curated edges.

    @mention an agent in a discussion thread. Ask it to compare clauses across a hundred contracts. Let it surface patterns your team annotated last quarter. The agent's power comes from the quality of the citation graph underneath it.

    An agent grounding its answer in tool calls — similarity search, exact-text search, and document lookups over the corpus

    Collaboration Where the Citations Live

    Forum-style threaded discussions at every level — global, per-corpus, per-document. @mention documents, corpuses, and AI agents. Upvote the best analysis. Pin critical findings. The conversation happens next to the source material, not in a separate tool.

    Discussion Threads

    Shared Graphs Compound

    Make a corpus public. Others fork it, refine the annotations, add documents, and share their improvements. Leaderboards and badges recognize contributors. Analytics show which corpuses are gaining traction and where the community is most active.

    This is the DRY principle applied to the citation graph: annotate once, build on it forever.

    Analytics Dashboard


    Annotation flows

    The human side of the graph — precise, layout-faithful annotation on PDFs and text:

    PDF Annotation Flow

    PDF Annotation Flow

    Text Format Support

    Text Annotation Flow


    Quick Start

    Development

    git clone https://github.com/Open-Source-Legal/OpenContracts.git
    cd OpenContracts
    
    # Copy sample environment files
    mkdir -p .envs/.local
    cp ./docs/sample_env_files/backend/local/.django ./.envs/.local/.django
    cp ./docs/sample_env_files/backend/local/.postgres ./.envs/.local/.postgres
    cp ./docs/sample_env_files/frontend/local/django.auth.env ./.envs/.local/.frontend
    
    # Build and start all services (including frontend)
    docker compose -f local.yml build
    docker compose -f local.yml --profile fullstack up
    

    Then open http://localhost:3000 and log in with admin / Openc0ntracts_def@ult.

    See the full Quick Start guide for details and troubleshooting. Have a GPU or NPU? See Hardware-Accelerated Images for auto-detecting parser/embedder images (the optimized Intel GPU image measured 49x the embedding throughput of the stock CPU image).

    Production

    # Apply database migrations first
    docker compose -f production.yml --profile migrate up migrate
    
    # Start services
    docker compose -f production.yml up -d
    

    Customizing the landing and About copy

    The discover/landing page and the /about page are driven by a JSON content pack so deployers can retarget the messaging without forking the codebase. Two variants ship in the repo:

    Variant keyFramingBest fit
    defaultOpen-source document intelligence you can build on.The OSS project's repo and most self-hosted deployments — developer-facing.
    public-recordThe citation layer underneath the public record.End-user deployments curating public-domain documents (named-incumbents pitch).

    Switch variants at runtime by setting REACT_APP_LANDING_VARIANT in frontend/public/env-config.js — no rebuild required. Unknown variant keys fall back to default.

    // frontend/public/env-config.js
    window._env_ = {
      // … existing config
      REACT_APP_LANDING_VARIANT: "public-record",
    };
    

    To add a deployment-specific variant, drop a <key>.json file in frontend/src/config/landingContent/ that matches the LandingContent type, register it in frontend/src/config/landingContent/index.ts, and set REACT_APP_LANDING_VARIANT=<key> on that deployment. Body copy in JSON can wrap the product name and named publications in *asterisks* to pick up the Source Serif italic treatment automatically (handled by renderInlineMarkup).


    Documentation

    Browse the full documentation at open-source-legal.github.io/OpenContracts or in the repo:

    GuideDescription
    Quick StartGet running with Docker in minutes
    Key ConceptsCore workflows and terminology
    PDF Data FormatHow text maps to PDF coordinates
    LLM FrameworkPydanticAI integration and agents
    Vector StoresSemantic search architecture
    Pipeline OverviewParser, embedder, and file-converter system
    Supported File FormatsCore parsers plus Gotenberg-convertible formats
    Custom ExtractorsBuild your own data extraction tasks
    v3.0.0.b3 Release NotesLatest features and migration guide

    Data Format

    OpenContracts uses a standardized format for representing text and layout on PDF pages, enabling portable annotations across tools:

    Data Format

    Processing Pipeline

    The modular pipeline supports custom parsers, embedders, and thumbnail generators:

    Pipeline Diagram

    Each component inherits from a base class with a defined interface:

    • Parsers — Extract text and structure from documents
    • Embedders — Generate vector embeddings for search
    • Thumbnailers — Create document previews

    See the pipeline documentation for details on creating custom components.


    Telemetry

    OpenContracts collects anonymous usage data to guide development priorities: installation events, feature usage statistics, and aggregate counts. We do not collect document contents, extracted data, user identities, or query contents.

    Disable backend telemetry: Set TELEMETRY_ENABLED=False in your Django settings. Disable frontend analytics: Leave REACT_APP_POSTHOG_API_KEY unset in frontend/public/env-config.js.


    Supported Formats

    • PDF (full layout and annotation support, via the Docling microservice)
    • DOCX (Word documents, via the Docxodus microservice — character-offset annotations aligned with WASM rendering)
    • Plain text (.txt, split into sentence annotations via spaCy)

    Plus 126 additional formats — legacy Microsoft Office, OpenDocument, Apple iWork, WordPerfect, images, HTML, and more — convertible to PDF by an optional Gotenberg-powered file converter (off by default; enable it in Admin → Pipeline Configuration, no docker-compose changes needed).

    See Supported File Formats for parser and conversion details, and the supportedMimeTypes / convertibleExtensions GraphQL queries that expose the live lists to the frontend.


    Acknowledgements

    This project builds on work from:


    License

    OpenContracts is distributed under the MIT License — one of the most permissive open source licenses available. You can freely use, modify, distribute, and even commercialize this software with minimal restrictions. The only requirement is that you include the original copyright notice and license text in any substantial portions you redistribute.

    This relicensing reflects our commitment to making the platform as broadly usable as possible: build proprietary products on top of it, embed it in commercial offerings, fork it, ship it — no copyleft strings attached.

    See LICENSE for the full text.