Architecting a Self-Hosted AI Paralegal: Hybrid pgvector Search, Word Track Changes, and PostgreSQL RLS
How to engineer a privacy-first legal operations platform with PostgreSQL pgvector HNSW + GIN hybrid retrieval, native OOXML Word Track Changes redlines, PII/privilege guardrails, Bates stamping, and hash-chained audit logs.
Legal operations teams face a harsh conflict when adopting generative AI. Contract review, deposition synthesis, and discovery search involve thousands of pages of scanned PDFs, Word agreements, and email threads—yet sending unredacted client files to generic third-party SaaS chatbots can compromise attorney-client privilege and violate data-handling obligations. Worse still, generic chatbots routinely invent clause citations and export plain-text diffs instead of native lawyer-ready redlines.
When designing AI Paralegal Platform (open-source on GitHub), the architecture had to guarantee matter isolation at the database layer, verify every research citation down to the exact document span, emit native Microsoft Word Track Changes, and treat all AI outputs strictly as attorney-review aids rather than legal advice.
Ingestion Hygiene and Tesseract OCR for Messy Legal Production Sets#
Real litigation productions and executed third-party agreements rarely arrive as clean Markdown. Async Celery workers backed by Redis ingest PDFs, DOCX contracts, and EML email threads after validating magic bytes so misnamed executables or malformed uploads fail before reaching downstream parsers. For image-only scanned PDFs where embedded text layers are absent or corrupted, the pipeline falls back transparently to Tesseract OCR before chunking and indexing.
Progress streams in real time over Redis Pub/Sub Server-Sent Events (SSE) into the React 18 workbench, allowing paralegals and attorneys to monitor multi-document OCR jobs, sequential page-level Bates numbering, and Legal Hold retention locks without polling loops.
Hybrid HNSW Vector + GIN Full-Text Retrieval via Reciprocal Rank Fusion#
Vector embeddings alone underperform in legal search. Asking about an 'indemnification carve-out' benefits from semantic similarity, while searching for 'Section 14.2(b)', a defined counterparty term, or an exact Bates stamp demands deterministic keyword matching. Maintaining separate vector SaaS stores also introduces consistency drift whenever matters are deleted or placed under Legal Hold.
Keeping both indexes inside PostgreSQL 16 solves this cleanly. Each document chunk stores a pgvector embedding indexed with HNSW alongside a generated tsvector column indexed with GIN, ranked together using Reciprocal Rank Fusion (RRF):
WITH semantic AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query_vec) AS rank
FROM document_chunks WHERE matter_id = :matter_id LIMIT 40
),
lexical AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', :q)) DESC) AS rank
FROM document_chunks WHERE matter_id = :matter_id AND tsv @@ plainto_tsquery('english', :q) LIMIT 40
)
SELECT COALESCE(s.id, l.id) AS chunk_id,
COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + l.rank), 0) AS rrf_score
FROM semantic s FULL OUTER JOIN lexical l ON s.id = l.id
ORDER BY rrf_score DESC LIMIT 12;Every claim synthesized by the research assistant carries source chunk identifiers validated against the retrieved set and opens directly inside a Click-to-Verify Source Viewer drawer highlighting the originating passage—eliminating silent citation fabrication.
Native OOXML Word Track Changes and Playbook Risk Matrices#
Attorneys negotiate inside Microsoft Word, not web textareas. During playbook review, clauses are checked against firm fallback positions and compiled into a Portfolio Risk Matrix across active agreements. Instead of dumping suggested text into a side panel, an OOXML exporter parses the original `.docx` XML tree and emits native `<w:del>` and `<w:ins>` revision elements—while an Office.js Word task-pane add-in lets reviewers inspect clause risk scores and insert approved redlines right inside Word.
Pre-Inference Privilege Guardrails, FORCE RLS, and Hash-Chained Audits#
Security in a multi-tenant legal platform requires defense-in-depth at three boundaries (see also hardening production RAG pipelines):
- PostgreSQL FORCE ROW LEVEL SECURITY: FastAPI request dependencies set transaction-scoped organization identifiers so PostgreSQL enforces tenant isolation at the storage engine level.
- Outbound Cloud LLM Blocking & Redaction: Pattern detectors catch SSNs, EINs, bank accounts, Luhn-verified card numbers, and attorney-client or work-product privilege markers—routing privileged material exclusively to self-hosted Ollama models (Llama 3.1, Qwen 2.5, Mistral NeMo, DeepSeek-R1) and scrubbing PII before any permitted cloud Gemini fallback.
- Identity & Tamper-Evident Chain of Custody: OIDC JWKS role synchronization, PBKDF2/JWT bearer rotation with `jti` logout denylisting, Legal Hold delete locks, and SHA-256 hash-chained audit logs detect post-hoc tampering.
Combined with enterprise DMS connectors (SharePoint, Google Drive, iManage, NetDocuments), SSRF-hardened HMAC webhooks, OpenTelemetry tracing, and Helm charts verified in CI against live pgvector, Redis, and Playwright E2E suites, teams gain self-hosted legal automation without surrendering privilege.
If you are architecting document-heavy AI systems under strict confidentiality constraints, explore my AI & LLM Engineering and Software Architecture Review services or schedule an architecture consultation.
Production Case Studies & Capabilities
Explore how these engineering patterns are deployed in production systems and available through client engagements.
AI Paralegal Platform
A production-grade Python (FastAPI) and React legal operations platform featuring hybrid pgvector + full-text retrieval, native OOXML Word Track Changes redline export, PII/privilege guardrails, Bates stamping, Legal Hold, hash-chained audit logs, and an Office.js Word add-in.
AI Engineering & LLM Integration
Many AI initiatives fail in production due to prompt fragility, high token latency, hallucination risks, and lack of structured evaluation. I bridge the gap between experimental LLM prompts and deterministic software engineering.
Software Architecture & System Design
Fast-moving teams frequently accrue hidden architectural liabilities: tangled domain logic, unmaintainable monoliths, or over-engineered microservices that paralyze development.
Frequently Asked Questions
Why combine PostgreSQL pgvector HNSW with GIN tsvector retrieval for legal discovery?
How can an AI contract review tool generate native Microsoft Word Track Changes without corrupting formatting?
How do PostgreSQL Row-Level Security and pre-inference guardrails prevent cross-matter leaks?
Related Technical Articles
Designing a Self-Hosted Autonomous AI Workforce: Shared Architecture Across 10 Enterprise Operations Platforms
Architectural blueprint unifying 10 open-source FastAPI, pgvector, and React enterprise AI platforms—from SDR, logistics, and insurance to procurement, scheduling, and localization—under HITL approvals and local Ollama routing.
Self-Hosted AI Finance Operations: Three-Way Reconciliation, 13-Week Cash Flow, and SOX Audit Chains
Inside the Phase 1 implementation of a self-hosted AI finance operations platform: SHA-256 deduplicated PDF/CSV intake, PO/receipt/invoice 3-way matching, AP/AR settlement gates, 13-week cash scenarios, and immutable SOX logs.