Let's Learn GenAI
  • Learn0 topics
  • Techniques0 topics
  • Courses0 courses
    View all courses →
  • GenAI Guide
    AI Career Path
    Paid AI Models & Tools
    Free AI Models & Tools
    Interview Preparation
    AI Career Path0 items
    View all paths →
  • Resources
    ArticlesResearch, releases & insight.NewsletterCurated AI, to your inbox.BenchmarkTop models, ranked.
Newsletter
  1. Home
  2. /Interview Prep
  3. /System Design
  4. /Legal Contract Intelligence

Legal Contract Intelligence

Design natural-language search over ten years of scanned contracts - OCR, clause-level retrieval, amendment history, and answers that cite the governing clause.

Last updated: September 2026

A legal team wants natural-language search over ten years of internal documents and contracts - questions like which of our master agreements cap liability below twelve months of fees. The hard parts are not the LLM. They are getting clean text out of scanned PDFs, retrieving at clause granularity rather than document granularity, knowing which version of an agreement was in force on a given date, and refusing to answer when the corpus does not support one. Permission filtering matters here too, but it is covered end to end on the Enterprise Knowledge Agent problem - this one is about the document layer.

“Every answer cites the clause, not the document. A contract answer without a pinpoint citation is unusable to a lawyer, who has to verify it before relying on it. The retrieval unit is the clause; the document is only the container.”

Clarifying Questions (Ask These First ~5 min)

QuestionWhy it matters
Native PDFs or scans, and what share is scanned?Decides whether OCR is the dominant cost and the dominant error source
One jurisdiction and language, or many?Drives OCR model, clause taxonomy, and legal-term normalisation
Do amendments and restatements exist for the same agreement?Version resolution is the difference between a right and a wrong answer
Is the answer advisory, or does someone act on it?Sets the citation bar and the disclaimer policy
Who may see which contracts?Matter-level and client-level walls - see Enterprise Knowledge Agent
Any retention or destruction obligation on the corpus?Constrains where extracted text and embeddings may live
Corpus size and annual growth?10k vs 2M documents changes OCR budget and index choice

Architecture (Draw This)

INGESTnightlyPARSINGreal-timeINDEXINGQUERYon-demandSourcesScanned PDFs, DOCX,emailIngest and dedupeContent hash1OCR and layoutPage image to text2Structure parserClauses and headings3Agreement graphAmendments and dates4IndexClause chunks andmetadata5User questionQuery plannerMetadata and semantic6Hybrid retrievalClause level filtering7Answer synthesisPinpoint citation8Abstain gateThreshold or conflict9

Say this as you draw it

Key Components (30-second pitch each)

  • 1OCR is the accuracy ceiling - Everything downstream inherits OCR error. Budget for a layout-aware model, keep per-page confidence, and route pages below threshold to a review queue rather than indexing garbage. Faxed amendments, stamped exhibits and signature pages are where accuracy collapses.
  • 2Clause-level chunking, not fixed windows - Split on the contract's own structure - numbered clauses, schedules, exhibits - and carry the clause path in metadata. A 512-token sliding window cuts an indemnity in half, and the retrieved fragment can then mean the opposite of the clause.
  • 3Defined terms travel with the chunk - Contracts define their own vocabulary. Resolve defined terms at index time and attach the definitions a clause depends on, or the model reads the clause with the everyday meaning of the word rather than the contractual one.
  • 4Hybrid retrieval, weighted toward exact terms - Legal queries carry exact strings: party names, clause numbers, Section 11.3, Force Majeure. Dense vectors alone miss them. Merge BM25 and vector with Reciprocal Rank Fusion, then cross-encoder rerank the top 100 clauses.
  • 5Version and effective-date resolution - An amendment silently replaces a clause. Store the agreement graph and resolve questions against an as-of date, defaulting to today and stating that date in the answer. Without this the system confidently quotes superseded text.
  • 6Mandatory pinpoint citation and abstention - Every sentence carries document, clause and page, with a verbatim quote of the operative sentence. Below the score threshold, or where two versions conflict, the system lists candidates instead of picking one.

What Separates a Strong Answer

  • 1Implement OCR review queue - Flag low-confidence OCR pages for manual review rather than indexing them. This prevents silent data loss and maintains high accuracy in the indexed corpus.
  • 2Use clause-level chunking - Index clauses based on the document's own structure to ensure accurate retrieval. Avoid fixed token windows that can split clauses and change their meaning.
  • 3Resolve defined terms at index - Attach definitions to clauses during indexing to preserve contractual meanings. This prevents the model from misinterpreting terms with everyday meanings.
  • 4Employ hybrid retrieval strategy - Combine exact term matching with semantic retrieval to handle legal queries effectively. This approach captures both precise legal terms and broader semantic context.

Retrieval Granularity Trade-offs

UnitStrengthFailure mode
Whole documentFull context preservedTop-K fills with one 80-page agreement; recall collapses
Fixed 512-token windowCheap and uniformSplits clauses, strands defined terms, drops negations
Clause with parent headingMatches how lawyers citeNeeds a structure parser per document family
Clause plus resolved definitionsModel reads the clause as writtenLarger chunks, higher embed and inference cost

Where the Answers Go Wrong

FailureMitigation
Superseded clause returned as currentEffective-date filter from the agreement graph; as-of date stated in the answer
OCR garbles a figurePage confidence threshold; numeric claims re-read from the page image at answer time
Negations and carve-outs droppedClause-level chunks plus a verbatim quote beside every claim
Model merges two different contractsGroup retrieved clauses by agreement; force a per-agreement answer
Question is legal advice, not retrievalOut-of-scope classifier and a fixed refusal - this is a search tool

3 Biggest Risks

  • 1Silent OCR loss - A page that failed to OCR is simply absent from the index, so the system answers confidently from the pages that worked. Mitigated by reconciling page counts per document and alerting on any document with unindexed pages.
  • 2Version confusion - Amendments and side letters change operative terms without changing the original file. Mitigated by the agreement graph, an explicit as-of date on every answer, and surfacing the amendment chain in the citation.
  • 3Confident answers from a thin corpus - Absence of a clause is not absence of the obligation - it may live in a document that was never scanned. Mitigated by an abstain threshold and by reporting corpus coverage per counterparty alongside the answer.

Google Stack: Document AI (OCR + layout parsing) → Cloud Storage (page images + extracted text) → Vertex AI embeddings + Vertex AI Vector Search (clause index) → BigQuery (agreement graph + audit) → Gemini (synthesis) → Cloud DLP (PII detection on export)

Azure Stack: Azure AI Document Intelligence (OCR + layout) → Blob Storage → Azure AI Search (hybrid BM25 + vector with the semantic reranker) → Azure SQL (agreement graph) → Azure OpenAI GPT-4o (synthesis) → Microsoft Purview (retention + audit)

AWS Stack: Amazon Textract (OCR + tables) → S3 → Amazon Bedrock Knowledge Bases with OpenSearch Serverless (hybrid retrieval) → DynamoDB (agreement graph) → Bedrock Claude (synthesis) → CloudTrail (retrieval audit)

Other Options: Docling or Unstructured.io for parsing + Qdrant or Elasticsearch for hybrid retrieval + a self-hosted Llama for firms that cannot send text to a cloud | Buy rather than build - Kira, Luminance or Harvey - and be ready to argue the build-versus-buy line, because for a single legal team it is often the right call.

Frequently asked questions

How do you evaluate this when there is no labelled set?

Build a golden set of 150 to 300 questions from the lawyers' own historical queries, with counsel marking the correct clause. Measure clause-level recall@10 first, because synthesis cannot recover what retrieval missed, then citation correctness sampled and reviewed by a lawyer.

What does OCR for a corpus this size cost?

It is a one-time batch priced per thousand pages, not per document. Run it once and keep the extracted text as the system of record, so a reindex or a chunking change never repeats OCR. Ingest is incremental from then on.

Contract in one language, question in another?

Embed with a multilingual model and keep the original text for citation - never cite a translation as if it were the contract. Translate the retrieved clause for display, mark it as a translation, and link to the source span.

Would you fine-tune the embedding model on contracts?

Usually it helps, but do the cheap things first: clause chunking, defined-term resolution, hybrid retrieval, reranking. A domain-tuned embedder on top of bad chunks is still bad, and the tuning has to be re-run every time the base model moves.

How is this different from a knowledge assistant over the wiki?

Same retrieval skeleton, different hard parts. The wiki case is dominated by permissions and freshness; contracts are dominated by OCR quality, clause structure and version history. The permission design lives on the Enterprise Knowledge Agent problem.

What about privilege?

Privileged material is walled off at the index, not filtered from results - a separate namespace per matter, a privilege flag set at ingest, and a retrieval audit trail. Accidental disclosure is a reportable event, so the control has to be structural.

Where this skill is used

AI roles that rely on this day to day, with salaries and the path in.

  • AI Solutions Architect
  • Generative AI Developer
  • LLM Engineer
  • AI/ML Engineer
  • Data Scientist

Related system design topics

  • AIOps Incident-Response AgentDesign an agent that receives production alerts, investigates root cause, and executes or proposes a fix - without making things worse.
  • Enterprise Knowledge AgentBuild a permission-aware Q&A assistant over internal docs (Confluence, Drive, Jira, Slack) - users only see answers from docs they're allowed to read.
  • Intelligent Document ProcessingDesign an agent that ingests invoices and claims, extracts structured data with LLMs, validates against business rules, and pushes to downstream ERP systems.
  • Deep Research AgentDesign an agent that decomposes complex queries into sub-questions, searches the web in parallel, and produces faithfully cited synthesis reports.
  • Real-Time Voice AgentDesign a low-latency speech-to-speech conversational agent with streaming ASR, LLM, TTS, and barge-in support targeting sub-1s perceived response time.
  • Real-Time Fraud Detection on a Legacy CoreScore 50,000 transactions a day from a legacy Oracle core without touching it - change data capture, sub-200ms scoring, and decisions written to a separate store.

Newsletter

Four editions, one inbox

The Build Layer for developers, The Strategy Signal for managers, The Executive Brief for executives.

Pick your edition

Guided courses

Get certified, not just informed

Guided courses from beginner to advanced, each with a named certificate. Free to take, yours to keep.

Browse courses
Let's Learn GenAI

Your guided portal to AI fundamentals, advanced techniques, and industry resources.

Learn

FundamentalsTechniquesCareersPaid AI ToolsFree AI ToolsBenchmarks

Explore

ArticlesNewsletterResourcesAbout

Legal

Terms of ServicePrivacy Policy

© 2026 Let's Learn GenAI. All rights reserved.