A technical guide to reliable document extraction with Claude: schemas, validation, honest confidence signals, cost math, and data handling.

Every finance and operations team has the same pile. Vendor invoices arrive as email attachments, receipts as phone photos, onboarding packets as scanned forms. Someone reads each one and types the numbers into another system.
For twenty years the automation answer was templates: draw boxes on a sample invoice from Vendor A, tell an OCR engine where the invoice number lives, and repeat for Vendor B. It works until Vendor A redesigns its invoice or someone scans a page upside down.
Vision language models changed the economics. Claude can read an invoice it has never seen, find the invoice number wherever it is printed, understand that "Amount Due" and "Balance Payable" mean the same thing, and return JSON that matches your schema. A new vendor costs nothing to set up.
That is the easy part, and it is where most demos stop. The hard part is knowing when an extraction is wrong, proving where every number came from, handling multi-page tables and scanned bundles, running at volume without the bill or the review queue exploding, and handling sensitive data correctly.
This guide covers all of it, for engineers and operations leads at a 20-person company processing a few hundred invoices a month or an enterprise processing a few hundred thousand: where document AI beats template OCR, a six-stage pipeline, input handling, schema design with working Python, validation, honest confidence signals, evaluation, cost math with current prices, data handling, integration, failure patterns, and a rollout plan. Every Anthropic API detail here was checked against Anthropic's documentation as of October 2026. Those details change, so check the pricing and model pages before you budget.
The deciding variable is not accuracy on a single document. It is how many different layouts you receive, and how many documents arrive per layout.
Template OCR converts the page to text with coordinates and maps fixed zones to fields. Each new layout needs a new template. Rules on OCR text replace zones with regular expressions and keyword rules ("the largest amount near Total is the total"), which handle more layouts but grow brittle as the vendor list grows. Document AI with a vision language model reads the page image (plus the text layer, for PDFs that have one) the way a person does, using labels, layout, and context. You describe what you want once, as a schema.

For most organizations the answer is a hybrid: parse structured data where it exists, keep templates that already work for your highest-volume layouts, and send everything else through Claude. The validation and review layers apply to all three paths, because trust belongs to the pipeline, not to the extractor.
One prerequisite matters before any of this. Extraction is only as useful as the reference data you validate against. A vendor master full of duplicates and stale tax IDs will match invoices to the wrong records. If you have not reviewed yours recently, start with Is Your Data Ready for AI? A 20-Question Audit.
A reliable document AI system is six stages, and only two of them call a model.

1. Ingest. Pull documents from the mailbox, shared drive, upload form, or API, and give each a stable identity. Hash every file (SHA-256 of the bytes) as your idempotency key, store the original untouched, and run preflight checks for encryption, page count, text layer, and size limits.
2. Classify. Decide what each document is and where it starts and ends. A mailroom scan often holds an invoice, a packing slip, and a remittance advice in one PDF. A small model with an enum schema returns document types and page ranges, and code verifies that the ranges cover every page exactly once before splitting the file with pypdf.
3. Extract. Send one document with the schema for its type and get back conforming JSON. The key decision: extraction produces candidates, not facts. Nothing moves until validation has looked at it.
4. Validate. Deterministic code checks types, reconciles arithmetic, matches the vendor master and purchase orders, checks dates, verifies quoted evidence, and looks for duplicates. Most of the system's reliability comes from this stage.
5. Review. Documents that fail a check, or that your policy always routes to a human, go to a queue where a reviewer sees the original next to the extracted fields with failed checks highlighted. Reviewer corrections become new labeled examples.
6. Export. Write approved records to the AP system, the ERP, or a database. Export must be idempotent and carry the source file hash, so every posted record links back to its original.
Three principles hold across the stages:
These are the same disciplines that turn any AI prototype into a production system, covered in general terms in From Prompt to Production: Turning an AI Prototype into Something a Team Can Use.
Anthropic's PDF documentation describes two steps: each page is converted into an image, and the text of each page is extracted and provided alongside that image. Claude analyzes both. That is why Claude can read a table whose structure exists only in the layout, and why a scanned PDF with no text layer still works.
It also means a PDF costs more than its text. Anthropic's guidance is that text typically uses 1,500 to 3,000 tokens per page, and page images are billed with the same calculation as any other image. Run the token counting endpoint on a sample of your real documents before you budget.
Anthropic also notes that dense PDFs can fill the context window before reaching the page limit, and recommends splitting large documents into sections.
A native PDF from accounting software has a text layer, and extraction quality is usually highest. A scanned PDF is images wrapped in a PDF. Claude still reads it, but Anthropic's vision documentation warns that Claude may make mistakes on low-quality, rotated, or very small images. Scans have a second cost: Anthropic's citations feature only works on extractable text, so a scan without a text layer is not citable. Detect which kind you have in preflight.
The 200-character threshold is a starting point. A cover page with only a logo can fall below it, so tune it on your documents.

Both work. Sending the PDF is simpler. Rendering pages yourself lets you deskew, rotate, crop, and pick the resolution, and resolution has a direct cost. Claude views images in 28 x 28 pixel patches, so an image costs ⌈width / 28⌉ × ⌈height / 28⌉ visual tokens. Claude 4.7 and later models, which includes every current model, use a high-resolution tier capped at a 2576-pixel long edge and 4,784 visual tokens. Larger images are downscaled.
A US letter page at 190 dots per inch is 1615 x 2090 pixels, or 58 × 75 = 4,350 visual tokens, just under the cap. Rendering at 300 dpi buys nothing because the image is downscaled anyway.
Anthropic's vision guide recommends labeling each image when you send several, and placing images and documents before the instructions.
Multi-page invoices are where extraction most often loses data quietly: the model captures page 1's rows and misses the continuation, or duplicates a "continued" line. Three defenses work together: ask for the page number of every line item, reconcile line items to the subtotal in validation, and for very long documents, split by page range and merge line items in code, passing page 1's column headers into later requests.
Treat handwritten fields (a date on a delivery receipt, an amount on a form) as review by default until your evaluation shows otherwise. Anthropic's documentation is explicit that high-stakes image interpretation needs human oversight. For receipt photos, crop, fix rotation, and avoid heavy JPEG compression, which Anthropic notes can make text hard to read.
Email bodies and other plain text go straight into a text block. Spreadsheets convert better to CSV text than to PDF, because the structure survives.
The schema is the contract between the model and the rest of your system, and most reliability decisions in extraction are schema decisions.
Structured outputs take a JSON schema in output_config.format and constrain the response through constrained decoding. Anthropic's documentation describes the guarantee as valid JSON, required fields present, and correct types, with no retries needed for schema violations. The feature is generally available on all current models. The documented exceptions:
stop_reason: "refusal" and may not match the schema. Anthropic also notes that a property asking for step-by-step reasoning can trigger a refusal, so ask for short notes instead.stop_reason: "max_tokens". Set max_tokens generously; thinking tokens count as output.The schema language is a subset of JSON Schema. Numeric constraints (minimum, maximum), string lengths, and array constraints beyond minItems of 0 or 1 are not supported. Basic types, enum, anyOf, $ref, simple patterns, and formats such as date are. Each request is limited to 24 optional parameters and 16 parameters with union types (such as ["string", "null"]) across all strict schemas.
Two consequences for invoices: a nullable field is a union type, so one request can hold at most 16 nullable fields, and because numeric constraints are not enforced, range checks belong in validation code. The Python SDK's transform_schema() (which client.messages.parse() also uses) strips unsupported constraints, appends them to field descriptions so the model still sees them, and leaves your stricter model available for local validation.
10/02/2026 is October 2 in the United States and 10 February in much of the world.other value for classification fields.notes list turns silent uncertainty into a routing signal.In Pydantic, an Optional[...] field with no default is required but nullable, which is rule 2. The schema has five nullable fields and no optional ones. When we ran it through transform_schema(), the amount and currency patterns were moved into field descriptions rather than sent as enforced constraints, so the local Pydantic validation below is what actually enforces them. Do not skip it.
Details worth noting:
claude-haiku-5-5) as built for high-volume tasks such as classification, extraction, and routing. Start there, and use Claude Sonnet 5.5 (claude-sonnet-5-5) or Claude Opus 5.5 (claude-opus-5-5) as the escalation path for documents that fail validation.medium effort and Sonnet 5.5 to high. Extraction is mostly reading, not reasoning, so test low first and step up only if your evaluation shows a gain.usage object from every call. It is the only reliable basis for a cost model.The classify stage uses the same pattern with a smaller schema: an array of objects with doc_type (an enum including other), first_page, and last_page. The pattern worth copying is the check after the call. If the returned ranges do not cover pages 1 to N exactly once, the bundle goes to review instead of being split.
Structured outputs guarantee the shape of the JSON, not the truth of its values. Validation is where you find out. Each check returns pass or fail and a severity: hard failures block posting without a human, and soft failures lower confidence.

The schema and local Pydantic validation already cover most of this. Add what a schema cannot express: an allowed currency list, tax ID formats per country, and a maximum plausible amount.
Invoices are self-checking. Lines multiply out, sum to a subtotal, and subtotal plus tax equals the total. A reading error almost never preserves these relationships by accident, which makes them your most powerful validation.
Line math is soft because real invoices have legitimate exceptions: per-line discounts, unit prices with extra decimals, fractional units. The sum check is hard because a dropped or duplicated row almost always breaks it. Tune tolerances to your vendors, since tax rounding per line versus on the total can differ by a few cents.
This is where keeping the as-printed date pays off. Store each vendor's date convention in the vendor master once a reviewer confirms it, and the flag stops firing for that vendor. A fuller version would also reinterpret the ISO date using the stored convention.
An extracted vendor name is a string, and your accounting system needs a vendor ID. A failed match is itself a signal: a new vendor, a misread name, or a fraudulent invoice.
A tax ID match passes outright, a name-only match passes as soft, and zero or several candidates is a hard failure. In production, also compare remittance address and bank details with the vendor record. A changed bank account on a familiar-looking invoice is a classic payment fraud pattern and should always route to a human. If you have purchase orders, add a PO check here (the PO exists, belongs to this vendor, and has open balance), the start of two-way matching.
The same invoice arrives from the vendor, forwarded by a colleague, and again as a second notice. The file hash catches exact copies, and a business key catches the rest.
In production, seen is a query against posted and pending invoices. Note what validation cannot catch: a misread invoice number like INV-20891 for INV-20391 breaks no arithmetic. That is what evidence checks and independent runs are for.
Every project eventually asks whether the model can say how confident it is. You can add a confidence field and the model will fill it with a number, but that number is not a calibrated probability. It is generated text like any other field. It has not been fit to your documents, it tends to cluster near the top of the scale, and a model that misreads a digit usually does not know it did. Routing on it puts wrong values into your ledger with a stamp of approval.
Some OCR engines and extraction products expose scores derived from the recognition engine or token probabilities. Those are more principled, but they still need calibration against labeled data, and they are not what you get from a schema field. The honest approach is to build confidence from signals you can verify, then calibrate routing thresholds on your own labeled sample.

An invoice whose lines, subtotal, tax, and total reconcile, whose vendor matched on tax ID, and whose dates are sane has passed several independent tests that a misreading would have to survive by coincidence.
For PDFs with a text layer, check that each quote appears on the cited page and contains the extracted value.
Get page_text with [p.extract_text() for p in PdfReader(path).pages]. PDF text extraction is imperfect (columns interleave, ligatures change characters), so a failed evidence check is soft, not proof of an error. Scans have no text layer to check, one more reason to route them more strictly.
Anthropic's citations feature would return verified pointers into the document, but it cannot be combined with structured outputs and does not work on scans. A second, targeted call with citations enabled ("Where is the amount due stated?") is a valid design for high-value documents. For most pipelines, quote checking is cheaper.
For high-value documents, extract twice (same model or a different one) and compare key fields. Disagreement strongly signals a hard document. Agreement is weaker evidence, because two runs can make the same mistake, so it adds to other signals rather than replacing them.
The notes field is not a probability, but "two different totals appear on page 1" is a concrete, checkable observation. Route on the presence of notes, not their wording. And some fields are hard for structural reasons: handwriting, low-quality scans, a vendor's first invoice. Track correction rates per field and per vendor from the review queue and use them as routing inputs.
The why list is what the reviewer sees first. "Lines do not sum to subtotal: 1,180.00 vs 1,280.00" leads to the dropped row in seconds. "Confidence 0.71" means checking everything.
To calibrate, run the full pipeline on your labeled sample and measure how many would-be auto-posted documents had any field wrong. That auto-post error rate is the number your controller cares about. Tighten rules until it is acceptable, then measure the share that still auto-posts. Both numbers come from your documents, not from a model's opinion of itself.
The minimum viable evaluation is a set of real documents with correct values entered by a careful person, a script that scores the pipeline against them, and the discipline to rerun it whenever the prompt, schema, model, or rules change. Two hundred documents is a reasonable start for one document type, sampled to match what you receive: big vendors, the long tail, scans, multi-page documents, and credit notes.
Score each field separately. Per-document accuracy hides that totals are nearly always right while PO numbers are not.
Precision asks "when the pipeline returns a value, how often is it right?" and recall asks "when the document has a value, how often does the pipeline return it correctly?" Invented PO numbers lower precision and need tighter null instructions. Missed PO numbers in small type lower recall and need better resolution or prompting. Normalize before comparing, or you will measure formatting instead of reading. For evaluation sets, regression testing, and shadow runs in general, see From Prompt to Production.
Anthropic's list prices as of October 2026, in US dollars per million tokens:
Details that matter for documents: Haiku 5.5 is priced by prompt length, so a request over 100,000 tokens pays the higher row for the whole request, and a long PDF can cross that line. Cache reads cost 10 percent of base input on Haiku 5.5 and 5 percent on Sonnet 5.5 and Opus 5.5. A 5-minute cache write costs 1.25 times base input and a 1-hour write 2 times. The minimum cacheable prompt on current models is 512 tokens. Batch and caching discounts stack, and US-only inference through inference_geo adds a 1.1 times multiplier.
The Message Batches API runs requests asynchronously at half price. Anthropic says most batches finish within an hour, and a batch expires if processing does not complete within 24 hours. A batch holds up to 100,000 requests or 256MB, and results remain available for 29 days. Invoices rarely need processing in seconds, so this fits well, with two cautions. The 256MB cap fills quickly with base64 PDFs, which add about a third to file size, so group documents by size. And use the 1-hour cache TTL: batch requests run concurrently and in any order, cache hits are best effort, and Anthropic recommends the 1-hour cache because batches commonly run longer than 5 minutes.
In extraction, the document changes every request, so what you cache is the prefix: instructions, worked examples, and the format instructions that come with structured outputs. Cache prefixes build in the order tools, system, messages, so keep everything stable in the system prompt with the breakpoint at its end, and put the document in the user message. Confirm hits through cache_read_input_tokens in the usage. Changing the output format invalidates the cache, so do not vary the schema between requests that should share one. Savings scale with prefix length: two or three worked examples (which often help on hard layouts) become nearly free after the first request.
Most documents are easy. Run everything on the cheapest model that meets your quality bar, re-run only documents that fail validation on a stronger model, and send what still fails to a human. Validation gives you a cheap, objective trigger: you escalate documents whose numbers did not reconcile, not documents the model says it found hard.
For one document:
cost = (D × P_in + C × P_cache + O × P_out) ÷ 1,000,000 × B
D is uncached input tokens (mostly the document), C is cached prefix tokens, O is output tokens including thinking, the P values are prices per million tokens, and B is 0.5 for batch or 1 otherwise. Cache writes are omitted because a stable prefix is written once per cache lifetime, not once per document.
Assume 10,000 documents a month, 10,000 document tokens each (roughly a two to three page invoice, but measure yours), a 2,000-token cached prefix, and 1,000 output tokens. Applying the formula with the prices above gives:

Three conclusions follow. The model tier matters most: Sonnet 5.5 costs about 20 times Haiku 5.5 here, and tiering gives hard documents the stronger model for $22.70 instead of $151 to $302. Caching helps but is not the main event at this prefix size: on Sonnet 5.5 standard it saves $38 per 10,000 documents, more once the prefix carries examples.
Most important, the review queue costs more than the model. Assume 15 percent of documents go to review, each takes two minutes, and a reviewer costs $40 an hour loaded (substitute your own numbers). That is 50 hours, or $2,000 a month, about 90 times the token cost of the tiered pipeline. Every point of review rate you remove with better validation, evidence checks, and vendor data is worth more than any token optimization.
For flows where someone is waiting (an employee uploads a receipt), use the synchronous Messages API with Haiku 5.5 and run documents concurrently within your rate limits, which depend on your usage tier. For backlogs and nightly runs, use batches. Both paths feed the same validation code.
Invoices contain bank account numbers and tax IDs, receipts contain names and card digits, and claims contain protected health information. Treat a document pipeline as a sensitive data system from day one.
ZDR and HIPAA eligibility are per feature, and some cost-saving features are not eligible.
This table summarizes Anthropic's API and data retention documentation as of October 2026. Your contract is the final word.
For ZDR or HIPAA workloads, then, send documents inline through the synchronous API, cache the prefix, and give up the batch discount. At Haiku 5.5 prices that is usually an easy trade. Also note that Claude Fable 5.1 and the Claude Mythos models require 30-day retention and are not available under ZDR unless Anthropic authorizes it.
enum and const values, and patterns.file_id values from untrusted sources. For multi-tenant products it recommends a workspace per tenant, which is also the prompt cache isolation boundary on the Claude API. Set expires_in_seconds at upload and delete files after processing.Four patterns cover most small and mid-sized businesses, and they scale to enterprise.
A dedicated inbox. Ask vendors to send to an address such as [email protected]. A small service polls the mailbox or subscribes to new-mail notifications through your email provider's API, saves and hashes each attachment, and queues it. The sender address is a useful vendor matching signal. Watch for forwarded chains, logo images mistaken for documents, and password-protected PDFs.
A shared drive folder. A watcher on the folder picks up new files and moves each to processed or needs-review when done. For small teams, that folder structure doubles as a simple review interface.
Direct to the AP system. If your AP or accounting system has an API, create draft bills, not posted transactions. The system's approval workflow stays in place, and the pipeline becomes a fast data entry clerk rather than an unsupervised one. Attach the PDF and store the file hash in a reference field.
CSV for ERP import. Many ERPs accept a scheduled CSV import with a fixed template. It is often the fastest integration to ship and the easiest to audit.
The temporary file and rename mean the import job never reads a half-written file, and the deterministic name means a rerun replaces the day's file. The ERP's duplicate check is the final safety net, not the first.
Once extraction is reliable, teams usually want more: look up the PO, check the receiving record, draft a query to the vendor. That is where Claude becomes an agent with tools, and MCP Explained: The Integration Layer Behind Production AI Agents covers how the Model Context Protocol connects it to business systems. Keep the Part 2 boundary even then: read-only tools for lookups, and human approval before anything posts or pays.
Most failures come from skipping a stage, not from the model.
The same sequence works for a small business and an enterprise shared services center. The enterprise version adds document types, reviewers, and formal change control.

Document AI with Claude removes what templates handle badly: the endless variety of layouts. One schema reads invoices from vendors you have never seen, and structured outputs return JSON your systems can consume directly.
It does not remove the need to know when an extraction is wrong. That knowledge comes from engineering, not from the model's opinion of itself: arithmetic that reconciles, evidence that exists on the page, reference data that matches, runs that agree, and a labeled sample that says how often the whole system is right. Build those layers, measure field by field, and start narrow. The token bill will be the smallest line in the budget. The review queue, and the trust of the people who sign off on the numbers, are what you are really optimizing.
Need help building a reliable document automation pipeline with Claude? Brightter, Inc. is an official Anthropic Claude Partner that helps small and mid-sized businesses and enterprise teams design and roll out AI document extraction workflows, from schema design and validation rules to review queues, evaluation sets, and secure integration with AP and ERP systems. Talk to our team about automating your first document type.
Yes. Claude processes each PDF page as an image alongside any extracted text, so scanned pages and photos can be read. Quality depends on scan quality, and scans without a text layer cannot use citations or quote checks, so route them to review more strictly.
Use structured outputs by passing a JSON schema in output_config.format, which constrains the response through constrained decoding. Handle the documented exceptions (refusals and max_tokens truncation), and validate constraints the API does not enforce, such as numeric ranges and patterns, in your own code.
No. A self-reported confidence number is generated text, not a calibrated probability. Route documents to review using signals you can verify, such as arithmetic that reconciles, quotes found on the cited page, vendor master matches, and agreement between independent runs.
It depends on tokens per document and the model. With Claude Haiku 5.5 at $0.10 per million input tokens and the Batches API at half price, an illustrative workload of 10,000 multi-page invoices costs under $25 a month in tokens, while human review time usually costs far more.
Partly. Inline PDF support, prompt caching, and structured outputs are eligible for zero data retention, but the Message Batches API and the Files API are not. For ZDR or HIPAA workloads, send documents inline through the synchronous Messages API and confirm eligibility in your contract.
New articles, one framework, and what we are seeing in AI and search. Once a month, five minutes to read.
Reading is a good start. A 30 minute call with a senior lead is faster.