Delivered remotely for a business based in London, United Kingdom. Names withheld by agreement.
Project Overview
Commercial legal teams routinely review hundreds of counterparty NDAs, MSAs, DPAs, and vendor order forms each quarter, yet most agreements arrive as inconsistent Word documents or flattened PDFs with bespoke clause numbering. Junior reviewers spend hours hunting through prior executed deals to locate approved fallback wording on indemnity, limitation of liability, and governing law, while senior counsel become bottlenecks for routine escalations.
We designed and implemented a LegalTech contract review and clause intelligence platform built on Python, FastAPI, React, and a dedicated Vector Database. The system parses incoming agreements into structured clause trees, evaluates each obligation against codifiable corporate playbooks, retrieves battle-tested fallback language from historical precedent, and exports clean Microsoft Word tracked changes.
Review Bottlenecks
Before this platform, corporate legal departments contended with systemic workflow friction across intake, analysis, and negotiation:
- Inconsistent Playbook Enforcement: Static Word or PDF playbook manuals went unread under deal pressure, causing different attorneys to accept conflicting liability caps or auto-renewal notice periods for comparable deal sizes.
- Lost Precedent Knowledge: Previously negotiated fallback clauses sat buried inside email attachments and shared drives without semantic indexing, forcing teams to rewrite acceptable compromises from scratch.
- Fragile Redline Tooling: Generic AI summaries stripped out cross-references, defined terms, and section numbering, making generated suggestions unusable without manual retyping inside Microsoft Word.
- Unquantified Escalation Queues: Legal operations leaders lacked visibility into which clause categories repeatedly triggered outside-counsel escalation or slowed commercial signature cycles.
Architectural Strategy
We decoupled document parsing, semantic retrieval, and deterministic rule verification behind an asynchronous FastAPI service tier. Rather than feeding an entire 60-page agreement into a monolithic prompt, the pipeline segments each contract into typed clause nodes enriched with their surrounding defined terms and section context.
Each clause undergoes hybrid retrieval against the tenant's Vector Database collection—containing both standard playbook positions and approved historical compromises—before a structured evaluation pass scores risk severity and generates minimally invasive redline diffs. FastAPI streams progressive analysis results via Server-Sent Events (SSE) to the React workbench so attorneys can begin reviewing high-risk sections within seconds of upload.
Core Capabilities
Layout-Aware Clause Parsing & Cross-Reference Resolution
The Python ingestion engine preserves hierarchical headings, nested sub-clauses, schedules, and capitalized defined terms. When an indemnity clause references "Excluded Losses" defined on page two, the resolver attaches that definition directly to the clause evaluation context.
Playbook Rule Engine & Deviation Scoring
Legal ops teams author structured playbooks specifying preferred positions, acceptable fallback tiers, and hard red-lines per contract type and jurisdiction. Each parsed clause is classified by topic and scored as Aligned, Minor Variance, or Escalation Required with explicit rule citations.
Hybrid Precedent & Fallback Clause Search
Inside the React side panel, reviewers query the Vector Database using natural language or selected counterparty text to surface previously approved fallback language filtered by deal size, region, and counterparty sector.
Native Tracked-Change DOCX Export
Attorneys accept, tweak, or reject proposed edits in a side-by-side diff interface. On export, the backend writes native OOXML w:ins and w:del revision tags back into the original Word package, preserving headers, footers, styles, and signature blocks intact.
Technical Architecture
Flow: React Workbench -> FastAPI Async API (SSE) -> Celery Ingestion Workers -> DOCX/PDF Structural Parser -> Vector Database (Hybrid Search) & Playbook Evaluator -> PostgreSQL Matter Ledger -> Native DOCX Redline Exporter
- Interactive Workbench: Built in React 18 and TypeScript, featuring synchronized scroll mapping between the rendered contract canvas, clause risk cards, and fallback precedent drawer.
- FastAPI Orchestration: Handles OIDC authentication, presigned binary uploads, SSE progress streaming, and strict Pydantic schema validation for every model output.
- Vector Database Indexing: Maintains per-tenant collections pairing dense semantic embeddings with sparse BM25 lexical vectors, indexed via HNSW graphs for low-latency similarity queries with metadata pre-filtering.
- PostgreSQL Governance Store: Tracks matter lifecycles, clause-level review sign-offs, playbook version snapshots, and immutable audit logs linking every exported redline to the playbook version active at review time.
Technology Stack
| Category | Technology Detail |
|---|---|
| Redlining Workbench | React 18 and TypeScript split-pane viewer with synchronized clause-to-playbook navigation |
| Inference & API Layer | Python 3.12 with FastAPI async endpoints, Pydantic schemas, and streaming SSE updates |
| Semantic Retrieval | Vector Database (Qdrant) storing tenant-partitioned clause embeddings and HNSW indexes |
| Relational Metadata | PostgreSQL managing matter hierarchies, playbook rules, approval states, and audit trails |
| Document Ingestion | Python DOCX XML / PDF layout parsers preserving numbered hierarchy and tracked changes |
| Background Pipeline | Celery workers on Redis orchestrating chunking, embedding generation, and LLM evaluation |
| Lexical Hybrid Search | BM25 sparse vectors paired with dense embeddings for exact statutory and defined-term recall |
| Encrypted Storage | Object storage with envelope encryption for original binaries and exported redline DOCX files |
| Security Controls | OIDC SSO, matter-level RBAC, PII redaction hooks, and zero-retention LLM gateway routing |
Engineering Trade-offs & Solutions
| Architectural Challenge | Engineering Resolution |
|---|---|
| Detecting subtle negation flips ("not liable" vs. "liable") missed by dense embeddings | Combined dense semantic embeddings with sparse BM25 scoring and deterministic regex checks for modal verbs, negations, and numerical caps. |
| Preserving complex Word list numbering during automated redlining | Manipulated underlying OOXML <w:r> text runs in place rather than converting documents to Markdown or HTML and back. |
| Avoiding context overflow on lengthy multi-schedule Master Services Agreements | Indexed global defined terms separately and injected only referenced definitions into each per-clause evaluation payload. |
| Keeping long document ingestion responsive in the UI | Streamed clause-by-clause analysis events over FastAPI SSE channels so early high-priority findings render while trailing schedules finish parsing. |
Security & Reliability
Confidentiality requirements in corporate legal operations demand strict tenant isolation and zero training leakage. Uploaded binaries undergo envelope encryption at rest, and access checks enforce matter-level role permissions (separating M&A restricted matters from standard commercial procurement). Every vector search passes mandatory tenant and matter filter predicates, eliminating cross-client retrieval exposure.
Inference pipelines strip configurable sensitive identifiers prior to external gateway calls and operate exclusively over zero-data-retention enterprise agreements. Deterministic substring verification ensures every flagged risk points to exact source offsets, preventing ungrounded commentary from reaching business stakeholders.
Performance & Scale
Parallelizing clause evaluation across Celery worker pools lets large multi-schedule agreements finish triage in predictable wall-clock time rather than scaling linearly per page. Vector Database HNSW parameters are tuned for high recall over filtered tenant subsets, keeping precedent lookups responsive even as historical clause libraries grow across years of executed agreements. Caching parsed document ASTs and immutable playbook snapshots in Redis eliminates redundant re-embedding when reviewers toggle between playbook tiers.
Operational Outcomes
Commercial legal teams transitioned from ad-hoc manual markups to consistent, playbook-anchored contract triage. Junior reviewers resolve standard deviations using vetted fallback language independently, escalation queues surface genuinely novel commercial risks to senior counsel with clear precedent context, and legal operations leaders gain structured telemetry on where counterparties push back most frequently across negotiations.