
Reading Any Document Layout from Photos and Scans Without Templates: A Schema-Driven Extraction Pattern with Amazon Bedrock
Enterprises receive the same kind of document from hundreds of senders, each with its own layout. This pattern makes the schema the contract: a versioned JSON record that a business user creates in a web app and picks at upload. The engine builds the Bedrock prompt and structured-output tool from that schema, treats the first read as a hypothesis, cross-checks it with an OCR witness and declarative rules, and re-reads only the required fields still in doubt.
The problem
As organizations put document intake on autopilot, a familiar tension surfaces. Operations teams need structured data from documents they do not control: weigh-scale tickets, supplier invoices, bills of lading, delivery notes, permits. Each sender prints a different layout, and phone photos arrive rotated, curled and shadowed. At the same time, nobody wants a human checking every result, so the system itself has to know when a reading is trustworthy.
The usual answers break down at scale. Template OCR needs a template per layout and fails silently when a sender changes theirs. A single prompt per document kind works in a demo, but it hardcodes what a field means, how to check it and when to give up, so every new document kind becomes a code change and a deployment. And a single model read, however good, gives you no signal about which values to trust.
This article presents a pattern that resolves the tension by separating what to read from how hard to look: put the description of each kind of document in data that business users own, and keep a generic engine that decides, per field, whether one read is enough.
The core idea: the schema is the contract
The guiding principle fits in one sentence:
“The schema defines what to read and what to save. The engine decides how hard to look. The code names no field and no document format.” |
|---|
Here is the lifecycle:
1. Define (once per kind of document). A schema editor creates a schema in the web app's Schema tab: the fields (type, description, printed-label synonyms, required, verify), reading instructions, and optional rules. Saving writes a new immutable version.
2. Upload (once per document). The user picks the schema, chooses the image, and can type the details the image does not show. The browser uploads straight to S3 with a short-lived presigned POST.
3. Read (once). A worker loads the chosen schema with a consistent read, builds the system prompt and a forced-tool spec from it, and asks a fast multimodal model for every field. Amazon Textract reads the same image as an independent witness.
4. Check (every field). Fields marked verify are voted across reads and checked against OCR; declarative rules such as gross − tare = net derive, confirm or repair values.
5. Escalate (only when needed). Required fields still in doubt get a targeted re-read by a stronger model on zoomed crops around their printed labels, at most twice.
6. Record (once). The fields, warnings, status, schema version, tokens and approximate cost go to DynamoDB; the exact prompt goes to S3 for audit.
The payoff: adding a field, a new layout or a whole new kind of document is a save in the Schema tab, with no code change and no deployment, and cost grows with how hard a document is to read, not with how many fields the schema has.
What about documents the schema doesn't cover?
Every read also returns raw_key_values: every label and value printed on the page, as printed. Nothing is lost when a field is not modelled yet, and the raw pairs show what to add to the next schema version. When a value is genuinely absent from the image (a hauler written on the truck, not the ticket), the uploader can supply it as a note, which is covered under Filling gaps with uploader notes.
An analogy: the experienced clerk with a field guide
Think of a data-entry clerk handed a new kind of form. You do not retrain the clerk; you give them a one-page field guide that says what each box means, what it is often labelled, and what it must not be confused with. A careful clerk reads the form once, cross-checks the numbers that should add up, and looks again, with a magnifying glass, only at the boxes that still look wrong. When something is missing, they write down where the value came from instead of guessing.
That is this pattern. The schema is the field guide. The fast model is the first read; Textract and the rules are the cross-check; the stronger model on zoomed crops is the magnifying glass; and every value carries its agreement status and source
Architecture

Presentation and identity
Component | Role |
|---|---|
Amazon CloudFront + private S3 site bucket (OAC) | Serves the single-page app over HTTPS with a strict content security policy. The bucket is reachable only through the distribution. |
Amazon Cognito user pool | Admin-created users only, 12+ character passwords, 60-minute ID tokens. A doctype-admins group grants schema editing. |
Amazon API Gateway HTTP API + JWT authorizer | Every route requires a valid Cognito token. Code then enforces ownership (users see only their documents) and the admin group for schema writes. |
Asynchronous extraction
Component | Role |
|---|---|
Amazon S3 intake bucket | Receives presigned uploads (JPEG, up to about 3.5 MB after browser downscaling) and stores the per-document prompt file. |
Amazon SQS + dead-letter queue | Decouples upload from extraction. Transient Bedrock errors are retried; a document moves to the DLQ after five receives. |
AWS Lambda worker | One document per invocation, maximum concurrency 5 to protect Bedrock quotas. Idempotent: documents already in a final status are skipped. |
AI services
Component | Role |
|---|---|
Amazon Bedrock (Converse API) | A fast model for the first read and a stronger model for targeted re-reads. Both model IDs are stack parameters, so you can test a cheaper or newer model without a code change. |
Amazon Textract (DetectDocumentText) | Independent OCR witness used to confirm values, break ties and locate printed labels for zoomed crops. Failure is non-fatal. |
Data
Component | Role |
|---|---|
DynamoDB schemas table | Live schema, immutable version history and a listing entry, written in one transaction with an optimistic version check. Point-in-time recovery on. |
DynamoDB documents table | Extracted fields, raw key/values, warnings, status, schema version, tokens and cost. Indexes by owner, schema and source group. |
Because the worker reads the schema on every document, an edit applies to the very next upload, and every processed record names the schema version that produced it.
The schema in practice
The minimum schema is the input JSON a single-purpose pipeline would already have: reading instructions and a field map. Everything else is optional. A trimmed field from the example invoice schema:
{"invoice_number": {"type": "string","required": true,"verify": true,"description": "The unique number of this invoice. Not a purchase order, order, customer account or quote number.","synonyms": ["Invoice #","Invoice No","Inv No","Bill No","Document No"]}}
Key | What it does |
|---|---|
fields.*.description | The most important text in the system: it becomes part of the prompt. The best descriptions say what does not belong in the field (“Not a purchase order number”). |
fields.*.synonyms | Printed labels, used twice: as examples in the prompt, and to find the field on the page so a re-read can zoom in. |
required / verify | Required fields earn a re-read when in doubt. Verify fields are voted across reads and cross-checked against OCR. |
instructions | Reading rules for every field: never guess, copy identifiers exactly, how to score confidence. |
rules | Declarative checks: equation (with derive_missing and repair), compare, unit_convert, pattern. |
notes_prompt | The hint shown in the upload's Missing details box, also given to the model. |
status_policy | When a document is hopeless rather than merely uncertain, and which warnings are informational. |
Field types cover what business documents carry: string, number, date, time, enum, boolean, and array for repeating rows such as invoice lines.
Building the prompt from the schema
The code holds one short system prompt that names no field and no format. It is filled with the schema's display name and domain context, followed by the schema's instructions. The fields become a Converse tool spec with one top-level argument per field; each argument's description is the field description, a format hint derived from its type (YYYY-MM-DD, “one of” for enums, a column list for arrays) and the label synonyms.
Two details mattered in practice. First, keep fields at the top level of the tool arguments: an early version nested them under a fields object, and one model then returned the whole object as a JSON string. Second, the system prompt and tool spec are identical for every document of one schema version, so they sit in front of a Bedrock prompt-cache checkpoint. Images and per-document text, including uploader notes, come after it. After the first document of a schema version, the schema part of later prompts can be billed at the cache-read rate, while the cache is warm and if the prefix meets the model's minimum cacheable length. A hit is not guaranteed: the cache expires when no request reuses it within its time to live (often five minutes), so check the cached-token counts stored on each record.
The trade-off: images are not cached and are the larger share of input tokens, so caching lowers cost but does not remove it. Measure it on your own documents rather than assuming a figure.
Knowing when to look again

A single read is not enough when nobody checks the result, so the first read is treated as a hypothesis. The fast model reads the whole image plus zoomed bands so small print is legible. Textract reads the same image. Two model reads that agree settle a verify field; OCR support counts only as a tie-breaker, because OCR misreads blurry digits as confidently as it reads clean ones.
Then the rules run. An equation rule is the most useful: on a scale ticket, gross − tare = net within 1 kg derives a missing net weight, settles a lone conflicted weight, and, when it fails, searches the voted candidates for the single combination that satisfies it, repairing the record only when exactly one exists. On an invoice, subtotal + tax = total plays the same role. Rule expressions are user-editable, so they are parsed with Python's ast module into a small allowed subset and never reach eval.
Only required fields still in doubt (missing, unconfirmed, in conflict, below 0.6 confidence, or part of a failed equation) get a second look, by the stronger model on crops around their printed labels. There are at most two such passes. Optional fields keep the first read and carry a warning.
Status | Meaning | What to do with it |
|---|---|---|
VERIFIED | No blocking warning remains. | Consume directly downstream. |
ACCEPTED_WITH_WARNINGS | Values present; some warnings remain (stored on the record). | Route by warning type, or review a sample. |
UNRESOLVED | Every field in unresolved_if_all_missing is empty. | Re-capture the image or key the document |
Filling gaps with uploader notes
Some values are simply not on the page: a hauler painted on the truck, a currency the vendor never prints, a smudged ticket number the driver can read off the screen. The upload form has a Missing details box, with the schema's notes_prompt as its hint. Notes are limited to 1,000 characters, checked for control characters, and stored on the document record.
The moment a human can feed text into the prompt, the risk profile changes. Layer these controls:
- Data, not instructions. Notes go in the user message inside a fenced block that says so, never in the system prompt; fence markers typed by the user are stripped.
- Printed values win. A note may fill only a field that is not printed or not legible.
- Provenance on every value. The model must label values taken from notes as source_label “uploader_notes”. The engine marks them from_notes with a from_notes:<field> warning.
- No pointless re-reads. A value from notes cannot be confirmed by the image, so it is never sent for a re-read.
- Conservative status by default. A document with notes-filled fields is ACCEPTED_WITH_WARNINGS. A schema owner can list from_notes as informational to allow VERIFIED, as an explicit, versioned decision.
The trade-off: notes make a document complete, not more verified. Be explicit with downstream consumers that from_notes means “stated by the uploader”.
Guardrails for schema changes
A schema save changes how every new document of that kind is read, for every user, so treat it like a deployment even though it is not one:
- Separate permission. Only the doctype-admins Cognito group can create or edit schemas, checked in code on every write, not just hidden in the UI.
- Immutable versions, optimistic concurrency. Each save writes a new version in one DynamoDB transaction conditioned on the expected version, so two editors cannot overwrite each other; any older version can be loaded and saved again to roll back.
- Validate on save. Field names, types, lengths, enum values, rule syntax and references are validated before anything is written.
- Measure before publishing. scripts/evaluate.py runs a candidate schema on sample images (per-field accuracy against a labels CSV), or compares live and candidate on stored documents and lists every document whose status or values would change.
- Draft, don't hand-write. scripts/draft-doctype.py proposes a schema from one to five sample images; a human reviews every description, because each one is prompt text.
Security choices worth copying
- Admin-created Cognito users and a JWT authorizer on every API route. A missing document and someone else's document return the same 404.
- The deployment publishes the web app only after it proves an anonymous API call is rejected: gate first, content second.
- Buckets block public access; the site bucket is readable only by this CloudFront distribution. S3 and DynamoDB are encrypted. IAM is scoped to the stack's own bucket and tables and to the model ARNs the worker calls; the Textract permission applies to all resources because DetectDocumentText does not support resource-level permissions.
- Uploads are presigned for five minutes, JPEG only, with a size cap; the upload must name an existing, active schema.
- Scanned business documents carry names, addresses and plate numbers. Treat the tables, prompt files and evaluation reports as confidential.
Observability and FinOps
Governance without visibility is incomplete. Every record stores its token counts (including cached tokens), the models used, the number of reads, and an approximate cost split into LLM and OCR. The web app totals them, and the exact prompt for each document can be downloaded for audit and debugging.
- A clean, legible document needs one fast-model call and one Textract page; the stronger model runs only for required fields in doubt, on small crops.
- The per-schema prompt prefix is cached, and there is no classification call because the user picks the schema.
- Lambda maximum concurrency caps parallel Bedrock calls and the SQS queue absorbs bursts. Throttled calls are retried through the queue, and the DLQ catches poison messages; size the concurrency to your Bedrock quotas.
- Per-record costs are estimates from list prices. Reconcile them with Cost Explorer or CUR 2.0, and estimate a workload with the AWS Pricing Calculator using token counts measured during evaluation.
What belongs where: a rule of thumb
Decision | Frequency | Where it lives |
|---|---|---|
What a field means, its labels, required / verify | On schema change | Schema (data, versioned) |
Reading rules, arithmetic and consistency checks | On schema change | Schema (instructions, rules) |
When a document is unresolved | On schema change | Schema (status_policy) |
Which schema applies, details missing from the image | Every upload | Uploader (Schema list, Missing details) |
Voting, OCR cross-check, when to re-read | Every document | Engine (generic code) |
Prompt and tool construction, caching | Every read | Engine (generic code) |
Who may change a schema | Every write | API (Cognito group check) |
If it describes a kind of document, put it in the schema. If it describes how to read any document, put it in the engine. |
|---|
Validation checklist
This pattern is a starting point, not a turnkey blueprint. Before committing, confirm the following in your own account and Region rather than assuming:
- Bedrock model access and quotas for both models in your Region, including the inference profile you use.
- Accuracy measured on your own documents with an offline evaluation run and a labels CSV, per schema, before you trust VERIFIED downstream.
- Cost per document measured in-account (tokens, cache hit rate, re-read rate), not quoted from this article.
- Your data-classification and retention requirements for document images, prompt files and evaluation reports.
- Production hardening: AWS WAF on CloudFront and the API, Cognito MFA, log retention, alarms on the DLQ and error rate.
- Who owns each schema, and how changes are reviewed before they are saved.
- Input formats: this design reads images; multi-page PDFs need a page-splitting step.
Conclusion
Reading documents from hundreds of senders does not force a choice between flexibility and trust. By making the schema the contract (owned by business users, versioned, picked at upload) and keeping a generic engine that treats every read as a hypothesis, you get a pipeline where a new kind of document is a save, not a deployment, and where every value carries the evidence for trusting it. Start with one schema and a labelled sample set, measure before you publish, and let the warnings tell you what to add to the next version.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article