Prompt Templates for Reliable Data Extraction from PDFs, Emails, and Web Pages
prompt templatesdata extractionJSON schemafew-shot promptingdocument AI

Prompt Templates for Reliable Data Extraction from PDFs, Emails, and Web Pages

PPromptCraft Editorial Team
2026-11-28
7 min read

Build reliable PDF, email, and web extraction prompts with JSON schemas, few-shot examples, validation rules, and uncertainty handling.

Reliable document extraction starts with a precise contract, not a clever one-line request. This guide provides reusable prompt templates, JSON schema patterns, few-shot examples, and validation checklists for extracting consistent fields from PDFs, emails, and web pages—even when values are missing, ambiguous, or contradictory.

Overview

Messy text creates predictable problems for an AI extraction workflow. A PDF may contain scanned pages, repeated headers, broken table rows, or fields split across lines. An email may mix a request, a quoted reply, a signature, and several dates. A web page may include navigation labels, advertisements, related content, and multiple values that look relevant.

A strong data extraction prompt reduces these problems by defining five things:

  1. The task: which fields to extract and what each field means.
  2. The source boundary: which text is authoritative and which surrounding content should be ignored.
  3. The output contract: the exact JSON shape, data types, and allowed values.
  4. The uncertainty policy: what to return when a value is absent, unclear, or conflicting.
  5. The evidence requirement: how to preserve the source text or location that supports each value.

Prompt engineering is only one part of a production-ready extraction feature. Parseable output should still pass application-level validation, and sensitive or consequential records may require human review. For a broader workflow covering OCR, validation, and review, see Build an AI Document Extraction Pipeline.

Checklist by scenario

1. General-purpose extraction prompt

Use a system instruction that establishes a narrow role and explicit rules. Keep the field definitions close to the output schema so the model has less room to interpret them differently.

You extract structured data from the provided source text.

Rules:
- Use only information explicitly present in the source.
- Do not infer, calculate, or fill in missing values unless a field rule allows it.
- If a value is not present, return null.
- If multiple values conflict, return the conflict in the issues array and do not choose silently.
- Preserve dates, amounts, and identifiers according to the output schema.
- Return valid JSON only. Do not include commentary outside the JSON object.

Then define each field operationally. “Customer name” should specify whether to use the billing entity, shipping entity, sender, or recipient. “Date” should identify whether it means the issue date, due date, publication date, or date of the latest message.

2. PDF information extraction

Before prompting, decide whether the input is machine-readable text or OCR output. OCR can introduce character substitutions, misplaced decimal points, and reading-order errors. Tell the model to report suspicious text instead of silently correcting it.

Extract the following invoice fields from the document text:
- invoice_number: the identifier labeled invoice number or invoice no.
- supplier_name: the legal or trading name of the issuing supplier.
- invoice_date: the date labeled invoice date.
- due_date: the payment due date, if present.
- total_amount: the final amount due, excluding subtotal and tax-only values.
- currency: the currency code or symbol associated with total_amount.

If OCR appears to have damaged a value, preserve the best-supported value and add an issue describing the suspected OCR problem. Do not calculate total_amount from line items.

For tables, specify whether line items are required and how to handle rows that cannot be read. A useful rule is to return a row with null fields and an evidence note rather than shifting values into the wrong columns.

3. Email parsing with an LLM

Email extraction needs boundary rules because quoted messages and signatures can contain stale information. State whether the current sender’s message takes precedence over quoted content, and identify the message portion to process.

Extract the action request from the newest unquoted portion of the email.
Ignore signatures, disclaimers, and quoted replies unless the current message explicitly refers to them.
Return:
- requester_name
- requested_action
- deadline
- referenced_id
- urgency: one of "low", "normal", "high", or null
- issues: an array of unresolved ambiguities

If the email says “please use the previous amount,” do not resolve that phrase from memory. Return null for the amount and record that the referenced value is unavailable or ambiguous. This makes downstream review visible instead of hiding uncertainty.

4. Web page extraction

Web content often repeats the same entity in metadata, navigation, body copy, and related links. Define a preference order, such as visible main-content text over navigation or footer text. If the page contains several products, locations, or authors, require the model to return an array rather than selecting the first match.

Extract product records only from the page's main content section.
Ignore navigation, recommendations, advertisements, comments, and footer links.
For each product, return name, stated_price, availability, and source_excerpt.
Do not treat a crossed-out former price as the current stated_price.
If availability is not explicitly stated, return null.

5. Few-shot prompting for extraction

Few-shot examples are most useful when they demonstrate edge cases, not only clean inputs. Include at least one example with a missing field, one with competing values, and one with a value that must remain a string.

Example input:
Invoice No. A-104
Total: 1,250.00 USD

Example output:
{
  "invoice_number": "A-104",
  "total_amount": 1250.00,
  "currency": "USD",
  "issues": []
}

Example input:
Invoice number: A-105
Total due: not shown

Example output:
{
  "invoice_number": "A-105",
  "total_amount": null,
  "currency": null,
  "issues": ["Total due is not present in the source."]
}

Keep examples consistent with the schema. An example that returns an empty string for a missing value can undermine a later instruction to use null.

What to double-check

  • Schema types: Decide whether identifiers such as order numbers and postal codes are strings. Numeric-looking identifiers can contain leading zeroes.
  • Null behavior: Use one convention for absent values. Avoid mixing null, empty strings, “unknown,” and omitted keys unless each has a defined meaning.
  • Dates and time zones: Specify the accepted format and whether the source’s original date should be preserved alongside a normalized value.
  • Amounts and currencies: Separate numeric amount from currency. Do not ask the model to perform arithmetic unless calculation is explicitly required and independently checked.
  • Conflicts: Define what happens when a header, table, or quoted email contains different values. Prefer evidence and an explicit issue over silent selection.
  • Evidence: Ask for a short source excerpt, page number, line reference, or character span when your application can provide it. Evidence makes review and debugging faster.
  • Input limits: Long documents may need page-level or section-level extraction followed by a consolidation step. Make sure the consolidation prompt knows which records can be merged.
  • Validation: Validate JSON syntax, required keys, enumerated values, formats, and business rules in application code. Structured output support helps with shape, but it does not prove that the extracted value is correct.

For an evaluation workflow, create a small test set of representative documents and label the expected fields before changing the prompt. Compare field-level errors, missing values, false extractions, and conflict handling rather than judging only whether the response looks plausible. The LLM Evaluation Guide provides a useful framework for this process.

Common mistakes

Asking for “all relevant information.” This produces inconsistent field selection. Name the fields and define their boundaries.

Overloading one field. A field called date may represent several dates. Use separate fields such as issued_date, due_date, and received_date.

Instructing the model to be helpful. General helpfulness can encourage guessing. Use “extract only explicit evidence” and specify how to report uncertainty.

Using prose as the only validation. A response can be valid JSON and still contain a wrong supplier, shifted table value, or unsupported inference. Combine schema validation with evidence checks and business rules.

Ignoring document structure. Tell the model about page breaks, quoted email sections, repeated headers, and the main-content boundary when those distinctions affect meaning.

Testing only ideal examples. Include rotated scans, missing fields, duplicated labels, conflicting totals, blank cells, and mixed date formats in your test set.

When to revisit

Revisit the prompt whenever the source documents, schema, or surrounding workflow changes. This includes adding a new supplier template, accepting a different email format, changing a web-page parser, introducing OCR, or adding fields to the output contract.

It is also worth reviewing extraction prompts before seasonal planning cycles if document volume or document types change during those periods. Sample new inputs from the actual workflow, then rerun the test set and inspect failures by category.

Use this practical update checklist:

  1. Collect recent examples, including failures and ambiguous records.
  2. Confirm field definitions, null rules, formats, and allowed values.
  3. Update few-shot examples only when they clarify a recurring edge case.
  4. Run schema, validation, and field-level quality checks.
  5. Review records that contain conflicts, low-quality OCR, or missing evidence.
  6. Deploy the prompt with version metadata so results can be compared over time.

When model APIs add or change structured-output features, tool behavior, or input handling, verify the prompt against the current integration rather than assuming compatibility. For implementation patterns involving structured outputs and tool calls, see the OpenAI API production AI feature tutorial. A reliable extraction prompt is not a one-time artifact: it is a documented contract that should be tested whenever its inputs or outputs change.

Related Topics

#prompt templates#data extraction#JSON schema#few-shot prompting#document AI
P

PromptCraft Editorial Team

AI Development Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.