Inferensys

Prompt

Legal Clause Extraction from Contract Text Prompt Template

A practical prompt playbook for using Legal Clause Extraction from Contract Text Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required inputs, and operational constraints for legal clause extraction.

This prompt is designed for legal tech platform teams who need to convert unstructured contract narratives into structured, machine-readable clause records. The primary job-to-be-done is extracting specific clause types, obligations, effective dates, and associated risk flags from full-text contracts, while preserving a direct citation back to the source text. The ideal user is an integration engineer or backend developer building a contract review pipeline, where the model's output must be ingested by a downstream database, search index, or review queue without manual reformatting.

Use this prompt when you have already attempted direct structured output generation (e.g., JSON mode or function calling) and the model has failed, producing a narrative or semi-structured markdown response instead. This is a repair and conversion playbook, not a first-pass extraction strategy. It assumes the input is a raw model response containing identified clauses in prose form. The prompt requires a defined [OUTPUT_SCHEMA] with typed fields, a [CLAUSE_TAXONOMY] listing the clause types to detect, and the original [CONTRACT_TEXT] for source grounding. Do not use this prompt for initial contract review, legal advice generation, or any workflow where the model is the first and only reader of the contract. It is a post-generation normalization step.

Before deploying, you must pair this prompt with a validation harness that checks for clause boundary accuracy, missing clause detection, and hallucinated citations. The output should never flow directly to an end-user or a system of record without automated schema validation and, for high-risk contracts, a human review step. If the contract domain is highly regulated (e.g., securities filings, healthcare BAAs), the pipeline must log every extraction with its source citation and confidence flag for auditability. The next section provides the copy-ready prompt template you can adapt to your specific taxonomy and output schema.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Legal Clause Extraction prompt works, where it fails, and the operational preconditions required before putting it into a production contract review pipeline.

01

Good Fit: Structured Clause Inventory

Use when: you need to extract known clause types (indemnification, termination, governing law) from clean, machine-readable contract text into a typed schema. Guardrail: define an explicit clause taxonomy in the prompt and validate extracted clause boundaries against source text citations.

02

Bad Fit: Legal Advice or Risk Scoring

Avoid when: the output implies legal judgment, risk scores, or compliance decisions without human review. Guardrail: the prompt must only extract and cite—never interpret enforceability, fairness, or materiality. Route any risk-labeled output to a human review queue before downstream consumption.

03

Required Inputs: Clean Text and Clause Taxonomy

What to watch: the prompt silently fails on scanned PDFs, handwritten amendments, or contracts with complex tabular layouts. Guardrail: preprocess documents with layout-aware OCR and validate text extraction quality before invoking the extraction prompt. Reject inputs below a minimum character or structure threshold.

04

Operational Risk: Missing Clause Detection

What to watch: the model may omit clauses that are present but phrased unusually, or hallucinate standard clauses that are absent. Guardrail: implement a post-extraction coverage check comparing extracted clause types against the expected taxonomy. Flag contracts where expected clauses are missing for human review.

05

Operational Risk: Clause Boundary Drift

What to watch: extracted clause text may include adjacent clauses, preamble, or signature blocks, corrupting the structured record. Guardrail: validate that each extracted clause's source citation maps to a contiguous, non-overlapping text span. Use a secondary prompt or deterministic boundary check to trim spillover.

06

Scale Fit: High-Volume Contract Intake

Use when: processing hundreds of similar contracts (vendor agreements, NDAs) where clause types are predictable. Guardrail: batch contracts by type and jurisdiction, and monitor extraction consistency across batches. Escalate batches with high variance in clause detection rates for taxonomy or prompt adjustment.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for extracting structured legal clause records from contract text, ready to copy into your application harness.

This prompt template is designed to convert unstructured contract text into a structured JSON array of clause records. Each record includes the clause type, extracted text, obligations, dates, risk flags, and source citations. The template uses square-bracket placeholders that you must replace with your actual contract text, target clause types, output schema, and risk definitions before use. The prompt enforces source grounding by requiring verbatim text extraction and citation to specific sections, which is essential for legal workflows where traceability is non-negotiable.

text
You are a legal document analyzer. Your task is to extract specific clause types from the provided contract text and return them as structured JSON records.

## INPUT
Contract Text:
[CONTRACT_TEXT]

## TARGET CLAUSE TYPES
Extract only the following clause types if present:
[CLAUSE_TYPES]

## OUTPUT SCHEMA
Return a JSON object with a single key "clauses" containing an array of clause objects. Each clause object must have these fields:
- "clause_type": string (one of the target clause types)
- "clause_text": string (verbatim text from the contract, exactly as written)
- "source_location": string (section number, paragraph reference, or line range where this clause appears)
- "obligations": array of strings (specific duties, requirements, or commitments identified in this clause)
- "effective_date": string or null (ISO 8601 date if a specific date is mentioned, otherwise null)
- "expiration_date": string or null (ISO 8601 date if a specific date is mentioned, otherwise null)
- "risk_flags": array of strings (select from: [RISK_CATEGORIES])
- "risk_rationale": string (brief explanation of why each risk flag applies, citing specific language)
- "counterparty": string or null (name of the other party if identifiable, otherwise null)

## CONSTRAINTS
1. Only extract clauses that match the target clause types listed above.
2. Extract clause_text verbatim from the contract. Do not paraphrase or summarize.
3. If a clause type is not present in the contract, do not include it in the output.
4. For dates, use ISO 8601 format (YYYY-MM-DD). If a date is ambiguous or partial, set the field to null and note the ambiguity in risk_rationale.
5. Risk flags must only come from the provided risk categories list. Do not invent new categories.
6. If no risk flags apply, use an empty array.
7. If you cannot determine a field value with confidence, use null rather than guessing.
8. Do not include any text outside the JSON object.

## EXAMPLES
[FEW_SHOT_EXAMPLES]

## RISK LEVEL
This is a [RISK_LEVEL] extraction task. [HUMAN_REVIEW_INSTRUCTION]

To adapt this template, replace each square-bracket placeholder with your actual values. For [CONTRACT_TEXT], insert the full contract text. For [CLAUSE_TYPES], provide a comma-separated list such as "Indemnification, Limitation of Liability, Termination, Confidentiality, Payment Terms." For [RISK_CATEGORIES], define your risk taxonomy like "Uncapped Liability, One-Sided Termination, Automatic Renewal, Vague Obligation, Missing Deadline." The [FEW_SHOT_EXAMPLES] placeholder should contain one or two example input-output pairs showing correct extraction behavior, which dramatically improves accuracy for legal text. The [RISK_LEVEL] and [HUMAN_REVIEW_INSTRUCTION] placeholders let you adjust the review requirement based on your use case—for high-stakes contract review, set [RISK_LEVEL] to "high" and [HUMAN_REVIEW_INSTRUCTION] to "All extracted clauses must be reviewed by a qualified legal professional before use." For lower-risk internal triage, you might set it to "medium" with a lighter review instruction. After adapting the template, test it against a golden dataset of contracts with known clause locations and types to measure extraction recall, clause boundary accuracy, and risk flag precision before deploying to production.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Legal Clause Extraction prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to programmatically verify the input is well-formed before incurring inference cost.

PlaceholderPurposeExampleValidation Notes

[CONTRACT_TEXT]

Full text of the contract or agreement from which clauses will be extracted

This Agreement is entered into as of January 15, 2024 by and between Acme Corp...

Non-empty string check. Minimum 50 characters. Reject if input is a URL or file path rather than raw text. Warn if text exceeds model context window minus prompt overhead.

[CLAUSE_TYPES]

Comma-separated list of clause categories to extract from the contract

Indemnification, Limitation of Liability, Termination, Governing Law, Confidentiality

Must be a non-empty string. Parse into array and validate each entry against a known taxonomy of supported clause types. Reject unrecognized types or return empty array if none provided.

[OUTPUT_SCHEMA]

JSON schema definition that each extracted clause record must conform to

{"type":"object","properties":{"clause_type":{"type":"string"},"clause_text":{"type":"string"},"start_line":{"type":"integer"},"end_line":{"type":"integer"},"risk_flags":{"type":"array","items":{"type":"string"}},"obligations":{"type":"array","items":{"type":"string"}},"effective_date":{"type":"string","format":"date"}},"required":["clause_type","clause_text","start_line","end_line"]}

Parse as valid JSON. Validate against JSON Schema meta-schema. Confirm required fields include clause_type, clause_text, and source location fields. Reject schemas that lack citation or source-text requirements.

[JURISDICTION]

Governing jurisdiction context for interpreting legal terminology and date formats

US-DE, UK-EW, EU-GDPR, US-CA

Must match a supported jurisdiction code from the platform's jurisdiction registry. Used to normalize date formats and interpret terms like 'reasonable efforts' or 'material adverse change'. Default to US-DE if null.

[CONFIDENCE_THRESHOLD]

Minimum confidence score required for a clause to be included in output. Clauses below this threshold are either omitted or flagged for human review

0.85

Must be a float between 0.0 and 1.0. Default to 0.80 if not provided. Values below 0.70 increase false positive risk. Values above 0.95 increase false negative risk. Log threshold in audit trail.

[MAX_CLAUSES]

Upper limit on the number of clause records returned. Prevents runaway extraction on very long contracts

50

Must be a positive integer. Default to 100 if not provided. Enforce in post-processing by truncating results if exceeded. Warn if output hits the limit, indicating possible missed clauses.

[REQUIRE_CITATION]

Boolean flag controlling whether extracted clauses must include exact source text and line references

Must be true, false, or null. Default to true for legal workflows. When true, validate that every output record contains non-empty clause_text, start_line, and end_line fields. Reject records missing citations when this flag is true.

[RISK_TAXONOMY]

Custom list of risk categories the extraction should flag against extracted clauses

Uncapped Liability, Auto-Renewal, One-Sided Termination, Data Sharing, Indemnity Scope

Parse as array of strings. If empty or null, use default risk taxonomy. Each risk flag in output must match an entry in this taxonomy. Flag unrecognized risk labels in post-validation as potential hallucinations.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the legal clause extraction prompt into a production application with validation, retries, and human review gates.

The legal clause extraction prompt is designed to be called from an application layer that manages document chunking, prompt assembly, and output validation. The typical integration pattern involves splitting a contract into sections or pages, sending each chunk through the prompt, and then merging the extracted clause records into a unified result set. Because legal workflows carry compliance risk, the harness must enforce strict validation before any extracted clause reaches a database or user interface. The prompt itself is stateless—it receives one chunk of contract text and returns structured clause records—so the application is responsible for deduplication, cross-chunk clause merging, and maintaining source text provenance across the entire document.

A production harness should implement a validate-or-repair loop around each prompt call. After receiving the model's JSON response, validate that every clause record contains the required fields: clause_type, clause_text, source_citation, obligations, effective_date, and risk_flags. If validation fails, use a repair prompt from the Output Repair and Validation pillar to fix malformed JSON, missing fields, or type errors before retrying. Set a maximum of two repair attempts per chunk; if the output still fails validation, flag the chunk for human review and log the raw model response for debugging. For model choice, use a model with strong structured output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) and enable structured output mode or JSON mode with a provided schema to reduce format failures at the source. Temperature should be set to 0 or near-zero to maximize extraction consistency across chunks.

Human review gates are essential for high-risk clause types. Configure the harness to automatically escalate any extracted clause where risk_flags contains values like indemnification, limitation_of_liability, termination_rights, or uncapped_liability. These records should enter a review queue before being committed to the clause repository. Additionally, implement a missing clause detector that compares the set of expected clause types for the contract category against what was actually extracted. If a contract is expected to contain a governing law clause but none was found, flag the document for manual review rather than silently accepting the gap. Log every extraction with the model version, prompt version, chunk identifier, validation result, and review decision to maintain an audit trail for compliance purposes.

For performance and cost management, batch chunks efficiently but avoid sending chunks larger than the model's reliable context window for structured extraction (typically 4,000-8,000 tokens per chunk works well). Implement caching for repeated contract sections or standard boilerplate language to reduce redundant API calls. If processing high volumes of contracts, consider a two-stage pipeline: first use a cheaper, faster model to identify which chunks contain clauses of interest, then route only those chunks through the full extraction prompt. This reduces cost while maintaining accuracy on the sections that matter. Finally, build a regression test suite using a golden dataset of annotated contracts with known clause types, obligations, and risk flags. Run this suite against any prompt or model change before deploying to production, and monitor extraction accuracy drift over time using the evaluation rubrics defined in the LLM Judge and Evaluation pillar.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact shape, types, and validation rules for each field in the structured clause extraction output. Use this contract to build downstream parsers, database schemas, and automated validation checks before the output enters any system of record.

Field or ElementType or FormatRequiredValidation Rule

clauses

Array of objects

Must be a non-empty JSON array. Each element must conform to the clause object schema defined in subsequent rows.

clauses[].clause_id

String (UUID v4)

Must match UUID v4 regex pattern. Must be unique within the array. No duplicates allowed.

clauses[].clause_type

String (enum)

Must be one of: [INDEMNIFICATION, LIMITATION_OF_LIABILITY, TERMINATION, CONFIDENTIALITY, GOVERNING_LAW, PAYMENT_TERMS, DATA_PROTECTION, FORCE_MAJEURE, ASSIGNMENT, OTHER]. If OTHER, clause_type_notes must be populated.

clauses[].clause_title

String

Must be non-empty string with length between 5 and 200 characters. Should be a descriptive title derived from the clause heading or content, not a generic label.

clauses[].source_text

String

Must be an exact, verbatim quote from the input contract text. Length must be between 10 and 5000 characters. Must be findable as a contiguous substring in [CONTRACT_TEXT] using case-insensitive match.

clauses[].source_location

Object

Must contain section_number (String or null) and page_reference (String or null). At least one of the two fields must be non-null. If both are null, the record fails validation.

clauses[].obligations

Array of strings

If present, each string must be between 10 and 500 characters. Each obligation must be directly traceable to the source_text. Null or empty array is acceptable when no obligations are identified.

clauses[].effective_date

String (ISO 8601 date) or null

If non-null, must be a valid ISO 8601 date string (YYYY-MM-DD). Must be parseable by standard date libraries. Null is acceptable when no effective date is specified in the clause.

clauses[].risk_flags

Array of strings (enum)

If present, each flag must be one of: [ONE_SIDED, UNCAPPED_LIABILITY, AUTOMATIC_RENEWAL, VAGUE_TERMS, MISSING_REMEDIES, UNUSUAL_JURISDICTION, BROAD_INDEMNITY]. Empty array is acceptable when no risks are identified.

clauses[].confidence_score

Number (float 0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. Represents the model's confidence in clause boundary accuracy and type classification. Scores below 0.7 should trigger human review per [CONFIDENCE_THRESHOLD].

extraction_metadata

Object

Must contain model_version (String), extraction_timestamp (ISO 8601 datetime), and total_clauses_found (Integer). total_clauses_found must equal the length of the clauses array.

PRACTICAL GUARDRAILS

Common Failure Modes

Legal clause extraction is brittle when boundaries blur, clauses are implied, or the model invents terms. These failure modes surface first in production and require explicit guardrails.

01

Clause Boundary Drift

What to watch: The model merges adjacent clauses or splits a single clause into fragments, producing records that don't match the source document's actual clause structure. This breaks downstream obligation tracking and amendment workflows. Guardrail: Require the prompt to output source text citations with start and end markers. Add a post-extraction validator that checks citation spans don't overlap and cover contiguous blocks.

02

Missing Clause Detection Failure

What to watch: The model silently omits clauses that are present but phrased unusually, buried in definitions sections, or expressed through cross-references rather than explicit language. Users trust the output is complete when it isn't. Guardrail: Add a completeness check that compares the count of extracted clauses against a heuristic expected count based on document structure. Flag outputs where extraction count is anomalously low for human review.

03

Hallucinated Clause Terms

What to watch: The model invents standard boilerplate language, adds industry-norm terms not present in the source, or fabricates dates and party names to fill perceived gaps. This is especially dangerous in legal contexts where fabricated terms create false obligations. Guardrail: Implement a grounding check that verifies every extracted field value appears verbatim or is a direct paraphrase traceable to the source text. Reject or flag records where field values can't be aligned to citations.

04

Risk Flag Overgeneration

What to watch: The model flags every clause as high-risk or generates vague risk descriptions that create alert fatigue. Legal teams start ignoring flags, and genuinely risky clauses slip through. Guardrail: Constrain risk flagging to a predefined taxonomy with specific triggers. Require the model to cite the exact language that triggers each risk flag. Add a post-extraction filter that suppresses flags without concrete source evidence.

05

Obligation Extraction Ambiguity

What to watch: The model confuses obligations of different parties, assigns obligations to the wrong entity, or extracts aspirational language as binding commitments. This corrupts obligation tracking systems and compliance calendars. Guardrail: Require the prompt to explicitly identify the obligated party for each extracted obligation. Add a validation step that checks party names against a known entity list from the contract header or signature block.

06

Date Normalization Collapse

What to watch: Relative dates, conditional effective dates, and dates expressed as offsets get normalized incorrectly or collapsed to a single interpretation. A clause effective "30 days after closing" becomes a fixed date that's wrong when the closing date changes. Guardrail: Preserve both the original date expression and the normalized value. Flag relative dates for recalculation rather than hard-resolving them. Add a temporal consistency check that verifies date ordering across extracted clauses.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of extracted legal clause records before shipping the prompt to production. Each criterion targets a specific failure mode common in contract extraction workflows.

CriterionPass StandardFailure SignalTest Method

Clause Boundary Accuracy

Extracted text matches the exact start and end of the clause in the source contract, without truncation or overrun into adjacent clauses.

Extracted text cuts off mid-sentence, includes text from a neighboring section, or omits a sub-clause that belongs to the target clause type.

Compare extracted [CLAUSE_TEXT] against source contract text using substring match. Flag if boundary offset exceeds 10 characters.

Required Field Completeness

Every record includes non-null values for [CLAUSE_TYPE], [CLAUSE_TEXT], [SOURCE_SECTION], and [RISK_FLAGS]. Optional fields may be null.

A record is missing [CLAUSE_TYPE] or [CLAUSE_TEXT]. [RISK_FLAGS] is null when the clause text contains a known risk pattern.

Run schema validator against output. Reject any record where required fields are null or absent. Log missing-field count per batch.

Source Citation Traceability

Every [SOURCE_SECTION] reference resolves to a real section heading or paragraph number present in the input contract text.

[SOURCE_SECTION] contains a hallucinated section number, a heading not found in the source, or a generic label like 'various sections'.

Extract all unique [SOURCE_SECTION] values. Cross-reference against section headings parsed from [CONTRACT_TEXT]. Flag any value with zero matches.

Risk Flag Accuracy

[RISK_FLAGS] correctly identifies clauses containing indemnification, limitation of liability, automatic renewal, or unilateral termination rights.

A clause with a clear unilateral termination right has an empty [RISK_FLAGS] array. A standard governing law clause is incorrectly flagged as high risk.

Curate a golden set of 20 clauses with known risk labels. Measure precision and recall of [RISK_FLAGS] against labels. Require precision >= 0.90.

Obligation Extraction Completeness

[OBLIGATIONS] array captures all party obligations stated in the clause, including payment, delivery, notice, and confidentiality duties.

A clause stating 'Customer shall pay within 30 days and provide quarterly reports' yields only the payment obligation, missing the reporting obligation.

For each clause in the golden set, count extracted obligations. Compare against human-annotated obligation count. Require recall >= 0.85.

Date Normalization Consistency

All dates in [EFFECTIVE_DATE], [EXPIRY_DATE], and [OBLIGATIONS] deadlines use ISO 8601 format and match the source contract date.

A date appears as 'next January' instead of a normalized date. A renewal date is extracted as the wrong year due to relative date misinterpretation.

Parse all date fields with a strict ISO 8601 validator. For golden-set clauses, compare normalized dates against annotated ground-truth dates. Require exact match rate >= 0.95.

Missing Clause Detection

The output explicitly returns an empty array or a 'not found' indicator when the contract contains no instance of the requested [CLAUSE_TYPE].

The model hallucinates a clause record when no such clause exists in the contract, or fabricates clause text to satisfy the output schema.

Test with contracts known to lack specific clause types. Assert that output array is empty or contains only records with [CONFIDENCE] below threshold. Zero false positives required.

Confidence Score Calibration

[CONFIDENCE] scores below 0.70 correlate with extraction errors, boundary issues, or ambiguous clause classification.

A record with a hallucinated source section receives a [CONFIDENCE] score of 0.95. A correctly extracted clause with clear text receives a score of 0.40.

Bin output records by [CONFIDENCE] decile. Measure error rate per bin. Require error rate in the 0.90-1.00 bin to be below 5% and error rate in the 0.00-0.50 bin to be above 50%.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small set of known contract types. Use a lightweight JSON schema with only required fields: clause_type, clause_text, source_location. Skip risk flags and obligation tracking initially. Run against 10–20 contracts and manually review every output.

Prompt snippet

code
Extract all clauses from [CONTRACT_TEXT]. Return JSON array with clause_type, clause_text, source_location.

Watch for

  • Clause boundaries bleeding into adjacent sections
  • Model inventing clause types not present in the contract
  • Source location references that don't match the original text
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.