OpenContracts Documentation

repository·main·Indexed 23 days ago

https://github.com/open-source-legal/opencontracts

An open-source document intelligence platform that converts document repositories into navigable citation graphs. It provides APIs, an MCP server, and a UI for structured extraction, reasoning, and annotation on interconnected documents. The platform includes a Cloudflare Worker (cite-og-worker) for social media link previews and supports hardware-accelerated deployments for docling-parser and vector-embedder using CPU, NVIDIA CUDA, AMD ROCm, and Intel GPU/NPU.

Tokens
376.7K
Snippets
638
Records
1.4K
Agent score
79%

What's inside OpenContracts

  1. Overview of the OpenContracts Routing System

    main

    The OpenContracts routing system is a centralized architecture designed to synchronize the browser URL with application state. It is built around a single source of truth: the CentralRouteManager.

    Key Principles

    • Centralized Management: CentralRouteManager handles all URL $\leftrightarrow$ State synchronization, entity fetching, and canonical redirects.
    • Explicit Route Patterns: Uses /c/ and /d/ prefixes to eliminate ambiguity between different entity types.
    • Slug-First URLs: Provides SEO-friendly URLs with automatic redirection from IDs to slugs.
    • Dumb Consumers: Route components are simplified; they only read reactive variables using useReactiveVar() and render the UI.
    • Complete Viewer State: The URL encodes the full document viewer state, including both selections and visualization settings, enabling robust deep linking.
  2. Overview of Frontend WebSocket Components

    main

    The OpenContracts frontend uses specific React components to handle real-time WebSocket interactions depending on the scope of the conversation:

    • ChatTray: Used for document-specific conversations, typically rendered in the right sidebar of the document viewer. Located at frontend/src/components/knowledge_base/document/right_tray/ChatTray.tsx.
    • CorpusChat: Used for corpus-wide conversations via a full-screen interface. Located at frontend/src/components/corpuses/CorpusChat.tsx.
    • Thread Components: UI components for managing discussion threads. Located in frontend/src/components/threads/.

    All these components follow a similar pattern for managing WebSocket connections, state, and UI rendering.

  3. Overview of OpenContracts WebSocket Architecture

    main

    OpenContracts uses WebSockets to provide real-time, streaming conversations with AI agents. This architecture supports progressive streaming of answers, source citations, reasoning timelines, and tool approval workflows.

    Key components include:

    • Frontend (React): Uses components like ChatTray, CorpusChat, and ChatMessage to manage UI state (including Source Atom State).
    • WebSocket Layer: Handles the message protocol and connection lifecycle.
    • Backend (Django Channels): Uses specific consumers to manage different contexts:
      • UnifiedAgentConsumer: Manages all agent chat contexts (corpus, document, standalone).
      • ThreadUpdatesConsumer: Handles real-time thread/conversation updates.
      • NotificationUpdatesConsumer: Handles real-time user notifications.
    • Data Layer: Persists conversations and messages in the database.
  4. Overview of OpenContracts capabilities

    main

    OpenContracts is an MIT-licensed, self-hosted document analytics platform designed for building knowledge bases that support both human users and AI agents. It provides a unified environment for document management, AI-driven analysis, and collaborative annotation.

    Core Capabilities:

    • Document Management: Organize documents into corpuses with folder hierarchies, permissions, versioning, and forking capabilities.
    • Multi-format Ingestion: Supports PDF (via Docling), DOCX (via Docxodus), and plain text.
    • Pluggable Pipeline: Modular architecture for custom parsers, embedders, and thumbnailers (registered in Python).
    • Custom Metadata: Typed fields with validation for structured data.
    • Human Annotation: Tools for multi-page text annotations, document-level labels, relationships, and structural annotations.
    • AI Agents: Configurable agents built on PydanticAI that can search documents and query annotations.
    • MCP Server: Exposes corpuses to MCP-compatible tools (like Claude or Cursor) via streamable HTTP.
    • Data Extraction: Perform large-scale extraction using Fieldset, Column, and Extract records.
    • Collaborative Tools: Forum-style discussions with voting, moderation, and @-mentions.
    • Multimodal Search: Combines vector embeddings (pgvector) with full-text search over documents and annotations.
  5. Overview of the Worker Upload System

    main

    The Worker Upload System is a REST API designed for machine-to-machine workflows. It allows external pipelines, bulk ingestion scripts, and pre-processed document feeds to push documents, annotations, and embeddings into OpenContracts. This is ideal when documents have already been parsed and annotated outside of the standard OpenContracts pipeline.

    Use cases:

    • External processing pipelines: Integrating custom NLP pipelines.
    • Bulk ingestion: Migrating large volumes of pre-annotated documents.
    • Pre-processed documents: Uploading files where text extraction, layout analysis, and embeddings are already complete.
  6. Overview of OpenContracts

    main

    OpenContracts is an open-source document intelligence platform that transforms document repositories into programmable citation graphs. It provides a substrate for both humans and AI agents to navigate relationships between documents (nodes) and citations (edges).

    Key capabilities include:

    • Citation Graph: Automatically detects and resolves statutory citations to create a navigable web of references.
    • AI Agents: Python-based agents that can search, summarize, and reason over documents using grounded annotations.
    • MCP Server: A Model Context Protocol server that allows AI tools like Claude or Cursor to interact directly with your corpus.
    • Structured Extraction: Scalable, LLM-powered extraction across large corpuses using natural-language queries.
    • Pluggable Pipeline: Swappable components for parsing, embedding, and thumbnailing.
    • Multi-surface Access: A GraphQL + REST API for applications, an MCP server for agents, and a React UI for human teams.
  7. Overview of the Corpus Collaboration System

    main

    The Corpus Collaboration System transforms OpenContracts from a document annotation platform into a collaborative knowledge hub. It provides community-driven interactions within corpus contexts through several core modules:

    • Discussion Threads: Supports nested replies (unlimited depth) at both corpus and document levels. Conversation types include CHAT (agent-based) and THREAD (standard discussion).
    • Voting & Reputation: Allows upvoting/downvoting messages with asynchronous reputation calculation and protection against self-voting.
    • Moderation System: Provides a permission hierarchy (Superusers > Corpus Owners > Moderators > Creators) with tools for thread locking, pinning, and reversible soft deletion.
    • Badge System: Features global and corpus-specific badges that can be awarded manually or automatically based on configurable criteria.
    • Notification System: A real-time system covering 14 notification types (e.g., replies, mentions, votes, badges).
    • Agent Mentions: Allows referencing AI agents in chat using @agent syntax, which triggers autocomplete via GraphQL.
  8. Overview of the Data Extraction and Retrieval System

    main
    OpenContracts is a unified system designed to extract structured data from documents and facilitate interactive Q&A over document collections using AI agents. It features a multi-framework architecture (supporting PydanticAI and others), a vector search system powered by pgvector, and a real-time WebSocket infrastructure for streaming responses.
  9. Overview of the OpenContracts Notification System

    main

    The notification system provides real-time alerts for important collaboration events, including replies, mentions, votes, badges, and moderation actions. It is built using a decoupled architecture consisting of:

    • Notification Model: Stores records, read/unread status, and links to related objects (messages, conversations, actors).
    • Signal Handlers: Automatically trigger notifications via Django post_save signals.
    • GraphQL API: Provides queries for retrieval and mutations for management.
    • WebSocket Support: Enables instant delivery via a real-time WebSocket connection.
  10. High-Level APIs in opencontractserver.llms

    main

    The opencontractserver.llms module provides four primary entry points for interacting with LLM capabilities:

    • agents (AgentAPI): The most common entry point. Used for creating and interacting with document and corpus agents, including structured data extraction.
    • embeddings (EmbeddingAPI): Used for generating text embeddings.
    • vector_stores (VectorStoreAPI): Used for creating and interacting with vector stores for similarity search.
    • tools (ToolAPI): Used for creating and managing CoreTool instances.
    from opencontractserver.llms import agents, embeddings, vector_stores, tools
    from opencontractserver.llms.tools.tool_factory import CoreTool
  11. Success Criteria for Global Embeddings Implementation

    main

    The implementation of Global Embeddings must satisfy the following criteria to be considered successful:

    • Annotation State: All new annotations must use the DEFAULT_EMBEDDER embedding. Corpus annotations configured with a custom embedder must maintain both the custom and the default embeddings.
    • Search Functionality:
      • Global Search: Must return results across all accessible documents.
      • Corpus Search: Must prioritize and use corpus-specific embeddings when they are available.
    • Data Integrity: Existing annotations must be backfilled with default embeddings, and all tests must pass.