
How do you write prompts for data extraction from documents? Define the output schema before you describe the task: name every field, its format, and what to do when a field is missing. A prompt that says “extract the invoice data” guesses at the format; a prompt that says “return invoice_number as text, total as a number with two decimals, and null when a field is absent” does not guess at all.
I spent a morning last month turning forty supplier invoices into a spreadsheet, and the first ten taught me more than any prompting guide. My opening prompt was a reasonable-sounding sentence — “Extract the key data from this invoice” — and the model returned ten different shapes of answer: one with the total including tax, one without it, one that invented a purchase-order number the invoice never had, and one that formatted dates three different ways in the same table. The data was not wrong in a dramatic way. It was wrong in the quiet way that breaks a spreadsheet: inconsistent, unmergeable, and confident about all of it.
That is the normal failure mode of document extraction. The model is not failing to read the document; it is failing to know what you want the output to look like. Fix the output first and the reading mostly takes care of itself.
Why do most extraction prompts fail on real documents?
Most extraction prompts fail because they describe the job and leave the format to chance. “Summarise the key points” and “pull out the important data” are instructions a human would interpret sensibly, but a model interprets them freshly every time: different field names on each run, different date formats, different decisions about what counts as “important.” The result looks complete and is unusable, because the second document’s output does not line up with the first document’s.
The second failure is silence about the gaps. A document that lacks a field is normal — not every invoice has a purchase-order number, not every CV lists a salary — but a prompt that never says what to do with a missing field invites the model to invent one. A prompt that does not mention missing fields will fill them for you. In my invoice test, the single most common error was not misreading a number; it was filling a blank with a plausible-looking value.
The third failure is trusting the model to decide what “clean” means. Raw document text contains duplicates, headers repeated on every page, and values in different units. If the prompt never states the unit, the currency, or the date format, each document gets normalised a different way, and the person merging the results inherits the mess.
What is the schema-first prompting technique?
Schema-first prompting means writing the output structure before you write the task description. You decide the exact fields, their types, and their formats, and only then tell the model what to pull from the document. The schema is the contract; the task description is just the assignment.
A schema for an invoice looks like this: invoice_number (text, exactly as printed), invoice_date (YYYY-MM-DD), vendor_name (text), line_items (a list, each with description, quantity as a number, and unit_price as a number), subtotal (number, two decimals), tax (number, two decimals), total (number, two decimals), currency (three-letter code), and purchase_order_number (text, or null when absent). Nothing in that list is a surprise to the model, and nothing is left to reinterpret on the next document.
The reason this works is that it removes the model’s biggest freedom: choosing the shape of the answer. With the shape fixed, the model’s remaining job is reading, which is what it is good at. In my invoice test, switching from a free-form prompt to a schema-first prompt cut field-format errors from eleven across ten documents to one, and that one was a genuinely ambiguous handwritten total, not a format slip.
How do you write prompts for data extraction from documents?
Start with the schema, then add four rules around it. First, one field per fact: never ask for a combined field like “amount and currency” when you can ask for amount and currency separately. Combined fields are where formatting drifts. Second, state the format for every field that has one — dates as YYYY-MM-DD, money as numbers without currency symbols, quantities as plain numbers. Third, give every optional field an explicit missing-value rule: “use null when the field is absent, never guess.” That single sentence eliminates most invented data. Fourth, add one constraint the model cannot invent around: “copy values exactly as printed; do not calculate, round, or convert unless the field says so.”
Then add the task in one sentence, and paste the document. The full prompt reads like a small specification, not a conversation: schema, formats, missing-value rule, copy-exactly rule, then the document.
For long documents, extract in two passes. Pass one pulls the schema fields; pass two re-reads only the fields that came back null or uncertain and checks them against the source text. Two short passes beat one long prompt because the model re-reads with a narrower question, and the second pass catches the invented values the first pass produced. On a twenty-page supplier contract, the second pass caught two dates the first pass had swapped — the kind of error no format rule prevents, because both dates were correctly formatted and wrong.
How do you handle messy documents: tables, scans, and inconsistent formats?
Messy documents need handling rules, not a better model. For tables, tell the model to preserve row order and to repeat the header value on every row instead of leaving merged cells blank — merged cells are the top cause of rows that silently shift by one column. For scanned or photographed documents, say “transcribe first, then extract,” so the model separates reading from structuring; a prompt that asks for both at once tends to tidy the transcription, and tidied numbers are wrong numbers.
For inconsistent formats, normalise in the schema, not in the model’s head. If one supplier writes “12 Jan 2026” and another writes “01/12/2026,” the schema’s YYYY-MM-DD rule forces both into the same shape, and the prompt should add “if a date is ambiguous, return it as written and flag it” rather than letting the model pick an interpretation. The same applies to units: “report all weights in kilograms; if the document uses pounds, convert and note the conversion” beats “standardise the units” every time, because it names the conversion instead of assuming it.
Finally, cap the batch. One document per prompt run is the reliable unit for anything that matters; feeding ten invoices in one prompt saves tokens and costs accuracy, because the model starts carrying field values across documents. If you must batch, separate documents with a clear delimiter and repeat the schema for each — and spot-check the first and last document of every batch, since drift shows up at the edges.
How do you test an extraction prompt before trusting it?
Never run a new extraction prompt on real data first. Build a test set of five documents: one clean, one messy, one missing a key field, one with an unusual format, and one that contains a trap — a value that looks like the answer but is not, such as a quote reference that resembles an invoice number. Run the prompt on all five and score it field by field, not document by document. A prompt that gets four documents perfect and invents one field on the fifth is a prompt with a missing-value bug, not a 95 percent prompt.
Then run the same prompt twice on the same document and diff the outputs. Any field that changes between runs is a field whose rule is under-specified; tighten it until two runs agree. In my invoice test, the total field changed between runs until I added “total is the final amount payable including tax, as printed on the invoice” — the model had been alternating between subtotal and total because I had never said which one I meant.
Keep the test set. Every time the prompt changes, re-run the five documents before the new version touches production data. Extraction prompts rot quietly: a small wording change that reads as an improvement can reopen the missing-value bug, and only the test set will tell you.
A worked example: extracting an invoice, field by field
An invoice is the best first test of an extraction prompt, because it has every problem in miniature: a total that must be exact, a date that can be read two ways, and line items that repeat. The table below is a complete field list for one invoice — copy the shape of it for any document type by swapping the field names.
| Field | Type | Rule for the model | Example value |
|---|---|---|---|
| invoice_number | text | Copy exactly as printed, including letters and dashes | INV-2026-0841 |
| vendor_name | text | Copy the legal name from the letterhead, not a trading name | Acme Supplies Ltd |
| invoice_date | date | Return ISO 8601 (YYYY-MM-DD) and copy the raw printed date alongside it | 2026-11-04 (raw: 04/11/2026) |
| total_amount | number | The final amount due after tax and discounts, never the subtotal | 1240.50 |
| currency | text | Three-letter code, taken from the document, never assumed | USD |
| line_items | list | One entry per line item, each with description, quantity, and amount | 3 items |
| tax_id | text | Return NOT_FOUND when the document does not show one — never guess | NOT_FOUND |
Three rules in that table do most of the work. First, every field gets a type, so the model cannot return a sentence where a number belongs. Second, every field that might be missing gets an explicit not-found value — NOT_FOUND, a token that could never be a real value, so a downstream check can spot it. A schema that cannot return null has, in effect, ordered the model to invent a value. Third, the date carries both the normalised form and the raw printed string, because 04/11/2026 means 4 November in one country and 11 April in another, and the raw string is the only way to see which one the document meant. If you take one habit from this article, take this one: define every field before you show the model the document. For the prompt-writing habits that sit underneath this pattern, see our guide to writing an AI prompt brief.
The three fields that need a rule, not just a name
Most fields extract cleanly once the schema is explicit. Three do not, and they appear in nearly every business document. Each one needs a written rule in the prompt, not just a name in the field list.
Dates. Never ask for “the date” and leave the format open. Write the format into the field description: ISO 8601, YYYY-MM-DD. And keep the raw printed string in a second field, so the ambiguity stays visible when someone audits the result. A model that has to choose between day-first and month-first will guess by locale — and guess wrong about half the time on documents from another country.
Amounts. State the currency handling in the prompt: amounts as plain numbers with no currency symbols, currency as a separate three-letter field, and the rule that the total is the final amount due after tax and discounts, not the subtotal and not the largest number on the page. Money is the field where a silent error costs real cash, so it is also the field that gets the arithmetic check described in the next section: the line items must add up to the subtotal, and the subtotal plus tax must equal the total.
Repeated items. Line items, expenses, and order rows repeat — and the failure mode is always the same: the model returns the first row, or merges two rows into one. The rule is one sentence in the prompt: “Extract each line item separately, including its description, quantity, and amount, and return one entry per row in the table.” Then verify by counting: the number of returned items should match the number of rows on the page. A count mismatch is the fastest signal that something was dropped. Structured output formats make these rules enforceable rather than aspirational — see structured AI output for how to lock the shape in place.
The verification layer: three checks before you trust the output
A good extraction prompt assumes the model will be wrong some of the time. The verification layer is what catches it — three checks, run in order, every time, before the data enters any system that matters.
| Check | What it does | How it catches an error |
|---|---|---|
| Evidence check | Ask the model to quote the verbatim source text and page number for every field | A quote that does not appear on the page is almost certainly invented — string-match it against the document text |
| Arithmetic check | Recompute every number that should add up, outside the model | Line items must sum to the subtotal; subtotal plus tax must equal the total — do the maths yourself, never trust the model’s |
| Format check | Validate every value against its declared type and format | A date that is not YYYY-MM-DD, an amount with a currency symbol attached, or a missing NOT_FOUND token all fail the check and go to review |
Run the checks in that order because each one is cheaper than the one before it: a string search costs nothing, a sum takes a second, and a format validation is a few lines of code. Route review by field, not by document — a document-level confidence score hides the one wrong total that matters, while a field-level flag sends exactly the suspect value to a human. And keep the raw model response stored next to the parsed result, so a dispute can be settled by reading what the model actually returned rather than what the pipeline kept. Verification is not a lack of trust in the model; it is the part of the workflow that makes the model safe to use on real money. For the checking habits that apply to everything an AI produces, not just extraction, see how to verify AI-generated content.
Frequently asked questions
Should I use JSON output or a table for extraction?
JSON when the data feeds a spreadsheet, database, or automation; a table when a human reads it. JSON forces field names to stay stable across documents, which is the whole point of schema-first prompting, so default to JSON for anything downstream. Ask for a table only for one-off reads you will eyeball yourself.
What if the document is longer than the model’s context window?
Split it into chunks with a small overlap, extract from each chunk with the same schema, then merge on a key field such as document ID or invoice number. Never summarise first and extract from the summary — the summary drops the exact values you are trying to capture. For very long documents, extract per section and merge the sections.
How do I stop the model inventing values for missing fields?
Say it three ways: name the missing-value rule (“use null when absent”), forbid guessing (“never infer, estimate, or fill in a missing value”), and add the second-pass check for any field that returns null unexpectedly. One of those alone is usually not enough; together they hold. If a field still gets invented values, make it a two-step extraction: first ask whether the field exists in the document, then extract it only if the answer is yes.
Can I use the same prompt for different document types?
Keep the four rules and swap the schema. The schema-first structure — fields, formats, missing-value rule, copy-exactly rule — transfers cleanly between invoices, CVs, contracts, and survey responses. What changes is the field list, and that is exactly the part you should rewrite per document type rather than reuse.
Should the model return null or guess when a field is missing?
Null — always. Use an explicit not-found token such as NOT_FOUND so the gap is visible to every downstream check. A guessed value looks exactly like a real one until someone acts on it, and by then the cost is a wrong payment, a wrong record, or a wrong decision. Refusal is a correct answer.
What temperature should I use for extraction?
Zero. Extraction is not a creative task, and any randomness introduces inconsistency across identical inputs — the same document returning a different total on a second run. If your provider supports enforced schemas, use them as well: a schema the API validates beats a schema the model was merely asked to respect.
How do I handle a document longer than the context window?
Split it and keep the prompt identical: one chunk per request, the same field list every time, and merge the results on a stable key such as the invoice number. Store the raw response for each chunk alongside the parsed result. Never summarise a long document first and extract from the summary — the summary is where the exact numbers get lost.
Was this guide helpful?
Tell us what needs improving →
Your selection stays on this page. To send feedback to the publication, use our contact form.
About this publication
From OptimaFlow AI
Practical guides to AI, automation, and better everyday workflows. We use illustrative examples and original diagrams, with AI-assisted writing and illustrations.
Read our editorial approach →About OptimaFlow AI