Blog

Extracting invoice data with Claude on Bedrock and structured outputs, step by step

Bedrock now forces Claude to answer with JSON that matches your schema. How to set it up for invoices, its limits, and where you still need to validate.

If you extract invoice data with Claude on Amazon Bedrock, turn on structured outputs and delete the code that retries when the JSON comes back broken. The model can no longer return something that breaks your schema, though that does not mean the amounts are right.

What it is

Until now, asking a model to “return a JSON with these fields” worked almost every time. The problem is the almost. One extra comma, a field with a different name or a sentence before the opening brace, and the job that pushes the invoice into your accounting system breaks at three in the morning.

Structured outputs fix that with constrained decoding: while the model generates its answer, Bedrock only lets it write tokens that fit the JSON Schema you pass in. The result always parses and always includes the required fields.

AWS announced it on 19 October for every Claude model available on Bedrock. There are two ways to use it:

  • JSON Schema output format: the schema goes in output_config.format with InvokeModel, or in outputConfig.textFormat with the Converse API.
  • Strict tool use: you add "strict": true to a tool definition and the arguments the model generates match its input_schema.

To pull data out of a document, the first one is what you want.

How to use it with an invoice

1. Define the smallest schema that works

Start with the fields you will actually put into your accounting system, and nothing else:

{
  "type": "object",
  "properties": {
    "supplier": { "type": "string" },
    "supplier_tax_id": { "type": ["string", "null"] },
    "invoice_number": { "type": "string" },
    "date": { "type": "string", "format": "date" },
    "currency": { "type": "string", "enum": ["EUR", "USD", "MXN", "COP"] },
    "net_amount": { "type": "number" },
    "vat": { "type": "number" },
    "total": { "type": "number" }
  },
  "required": ["supplier", "supplier_tax_id", "invoice_number", "date", "currency", "net_amount", "vat", "total"],
  "additionalProperties": false
}

Two details matter. Every object needs additionalProperties: false; without it Bedrock returns a 400 error. And the field that may be missing (the tax ID on some foreign invoices) is required but nullable, with ["string", "null"]. That way the model writes null instead of making something up.

2. Call the model

With Python and boto3, using InvokeModel:

import json
import boto3

bedrock = boto3.client("bedrock-runtime")
MODEL_ID = "..."  # your Claude model ID or inference profile from the Bedrock console

with open("invoice_schema.json") as f:
    schema = json.load(f)

body = {
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 2000,
    "messages": [{
        "role": "user",
        "content": [
            {"type": "text", "text": "Extract the data from this invoice."},
            {"type": "text", "text": invoice_text},
        ],
    }],
    "output_config": {"format": {"type": "json_schema", "schema": schema}},
}

resp = bedrock.invoke_model(modelId=MODEL_ID, body=json.dumps(body))
result = json.loads(resp["body"].read())

if result["stop_reason"] != "end_turn":
    raise RuntimeError(f"Incomplete response: {result['stop_reason']}")

invoice = json.loads(result["content"][0]["text"])

Note the stop_reason check. If the model hits max_tokens before closing the JSON, the answer is cut off even with structured outputs on. Give max_tokens some room and treat any other stop reason as an error.

3. Validate what the schema cannot

The schema guarantees the shape, not the content. And Bedrock does not support numeric constraints (minimum, maximum) or string length constraints (minLength, maxLength). So you check these in code, which takes three lines:

assert abs(invoice["net_amount"] + invoice["vat"] - invoice["total"]) < 0.01
assert invoice["total"] > 0

If the numbers do not add up, the invoice goes to a manual review queue, not to accounting.

Limits worth knowing up front

From the Bedrock documentation:

  • Slow first call: the first time you use a schema, Bedrock compiles a grammar, which can take up to about 90 seconds. It is then cached for 24 hours for your account. Raise your client read timeout to 120 seconds or the first call will fail.
  • Changing the schema invalidates the cache. Changing only names or descriptions does not.
  • At most 12 optional properties across the whole schema. Beyond that you get “Schema is too complex”. That is why I prefer required-but-nullable fields, which are capped at 16.
  • No recursive schemas and no external $ref.
  • Not compatible with citations: turning on citations with Anthropic models returns a 400.

My take

I would use this today for any repetitive extraction in a small business: supplier invoices into accounting, inbound lead emails into the CRM, support tickets sorted by urgency. Broken JSON was the dumbest reason those pipelines failed, and now it goes away without switching providers or adding libraries.

What I would not do is trust the result without the step 3 checks. A perfect JSON with a misread VAT amount is worse than a broken one, because the broken one at least fails where you can see it. My rule: the schema handles the shape, your code handles the arithmetic, and a person handles whatever does not add up.

I would also start with few fields. The more optional ones you add, the closer you get to the limit of 12 and the slower the first compile. An invoice that is useful to accounting fits in eight fields.

If you already extract data with prompts and retries, the migration is small: add the schema, drop the defensive parsing and keep the business checks.

Sources

If practical guides like this help you, follow me on LinkedIn, where I share what I try with AI and AWS.

← All articles

Have a product to build or a tech stack to put in order?

Tell me what you are trying to achieve and where you are today. I reply personally, usually within a day.

Free · 30 minutes

Digital strategy session

30 minutes to map where to start digitalizing and transforming your business. You pay nothing, before or after.

When you book, you answer three short questions: what you need, what stage your project is at and when. That way the session starts with context.