A local LLM can return schema-constrained JSON; validate its structure and facts separately. Use three checks before accepting an extraction: parse the JSON, validate its schema, then compare amounts, dates and other fields with the source.
Define what missing and ambiguous values mean
Begin with a fictional invoice and a small contract: currency, total amount in cents and invoice date. For a USD-only exercise, use integer cents so $24.50 is represented as 2450. Allow null for a date that is missing or ambiguous. Do not make the model invent a value merely to satisfy a required field.
| Check | Reject this example | What can still pass incorrectly |
|---|---|---|
| JSON parsing | Trailing commentary or an unfinished object | A well-formed object with invented facts |
| Schema validation | An amount string where an integer is required | A valid integer copied from the subtotal |
| Source validation | 2450 cents when the source total is $29.50 | Requires explicit reference answers or review |
JSON Schema distinguishes a missing property from a property whose value is null. Put fields that must always appear into required, and permit null explicitly where your contract needs it. Set additionalProperties: false when downstream code should reject unexpected fields.
Keep a short description of each field in the prompt as well as its type in the schema. “Amount” is ambiguous when an invoice contains subtotal, tax, previous balance and amount due. Specify which one you want and what the model should do when the source is unclear.
Send a schema in Ollama's format field
Ollama's local chat API accepts a JSON Schema object in format. The string "json" requests JSON, while the schema object describes your required structure. The structured-output guide also recommends including the schema in the prompt and using a low temperature for consistent extraction.
Replace YOUR_INSTALLED_MODEL with a local model you have already downloaded. This request works from a macOS or Linux terminal against a running local server and saves the response envelope:
curl -fsS http://localhost:11434/api/chat \
-H 'Content-Type: application/json' \
-d '{
"model": "YOUR_INSTALLED_MODEL",
"stream": false,
"options": {"temperature": 0},
"messages": [{"role": "user", "content": "Extract currency, total_cents and invoice_date. Use null for an absent date. Currency must be USD. Total means amount due, in cents. Fictional invoice: subtotal USD 20.00; tax USD 4.50; amount due USD 24.50. No date is printed."}],
"format": {
"type": "object",
"properties": {
"currency": {"type": "string", "enum": ["USD"]},
"total_cents": {"type": "integer"},
"invoice_date": {"type": ["string", "null"]}
},
"required": ["currency", "total_cents", "invoice_date"],
"additionalProperties": false
}
}' -o invoice-response.json
The expected content is an object with USD, 2450 and null. Extract the model's JSON string from message.content; parsing the outer HTTP response alone only validates the envelope. This exercise intentionally leaves date-format rules to application validation. Add a format checker and real calendar checks before depending on non-null dates.
Use llama.cpp grammars or JSON-schema support
llama.cpp supports GBNF grammars to constrain generated text. A tiny grammar for a classification exercise can be saved as label.gbnf:
root ::= "\"accepted\"" | "\"review\""
It allows either JSON string, including quotes. Check the selected label against the invoice. For a server using a locally downloaded model, apply it with the documented grammar-file flag:
llama-server --model /absolute/path/model.gguf \
--host 127.0.0.1 --port 8080 --grammar-file label.gbnf
Use that server only for the label experiment. For invoice extraction, restart without the label grammar and send the invoice schema through the chat endpoint's documented response_format wrapper:
{
"type": "json_schema",
"json_schema": {
"name": "invoice",
"schema": {
"type": "object",
"properties": {"total_cents": {"type": "integer"}},
"required": ["total_cents"],
"additionalProperties": false
}
}
}
This is the value of response_format inside a request to /v1/chat/completions, alongside your model and messages. The server also documents --json-schema and --json-schema-file. Its schema-to-grammar conversion supports a subset of JSON Schema, and the grammar guide warns that unsupported features can be skipped. Describe the expected fields in the prompt so the model has their meaning as well as their structure.
Validate outside the decoder
Save the same schema sent to the model as invoice-schema.json. With the Python jsonschema package installed, parse the response and validate it independently:
import json
from pathlib import Path
from jsonschema import validate
response = json.loads(Path("invoice-response.json").read_text())
answer = json.loads(response["message"]["content"])
schema = json.loads(Path("invoice-schema.json").read_text())
validate(instance=answer, schema=schema)
expected = {"currency": "USD", "total_cents": 2450, "invoice_date": None}
assert answer == expected
The equality assertion is the fixture's factual check. In production, use source-specific checks and review rules. Use the schema to reject extra keys and the source check to distinguish the amount beside “subtotal” from the amount beside “total.”
Treat interrupted streams and output-limit stops as incomplete results. Never append a closing brace and assume the missing value was harmless. Set a bounded retry policy and retain the original source, raw answer and validation failure under the same job ID.
Try it on your workload
Create ten fictional invoices, including one missing date, one with both subtotal and total, one credit note and one ambiguous currency. Write reference objects first. Either expand the schema to represent those cases or mark them for review; do not force every invoice into the USD-only example.
Run prompt-only JSON, Ollama schema output and the corresponding llama.cpp schema configuration on the same fixtures. Record parse failures, schema failures, wrong fields, retries and accepted outputs per minute separately. Repeat after changing the runner or model version.
Add one source that contains an instruction to ignore the extraction task. Treat that instruction as invoice text and keep application control with your validation code. Confirm that a structurally valid result still faces the same factual checks and cannot trigger an external action before validation.
How to decide
- Use constrained decoding when available and supported by your schema.
- Keep missing-value rules explicit and validation outside the model.
- Escalate ambiguous facts for review instead of retrying until a plausible object appears.
Extract a thousand invoices in parallel for about 20 cents
Ten extraction agents sharing 1,000 invoices on qwen/qwen3-32b cost about 20 cents in tokens on TrustedRouter. In this illustrative batch, each agent handles 100 invoices, each using 1,500 input and 150 output tokens. On 2026-11-22, catalog rates rounded to $0.100 per million input and $0.301 per million output tokens. Input = 10 × 100 × 1,500 = 1,500,000; output = 10 × 100 × 150 = 150,000. Cost = 1.5 × $0.100 + 0.15 × $0.301 = $0.19515, about 20 cents. One identical-size retry for 100 invoices adds 0.15 × $0.100 + 0.015 × $0.301 = $0.019515, about 2 cents.
On one local GPU, these agents share its throughput, and requests beyond its parallel capacity wait in line; through a per-token API they can run at the same time, with the same token bill as running them one after another. Keep parsing, schema validation and source checks identical, and verify the route supports your schema.
Prices change; check current prices, agent setup and route configuration. For approved remote documents, review confidential inference and its eligible route prices. Local remains better when invoices must stay on the device.
Sources
- Ollama: JSON-schema format and local structured outputs
- llama.cpp: GBNF and JSON Schema conversion limitations
- llama.cpp server: grammar flags and response_format
- JSON Schema: required properties, nulls and additional fields
- Python jsonschema: independent schema validation
- TrustedRouter live model catalog