AI › AI Tools

Validating OpenRouter structured outputs with JSON Schema

Configure OpenRouter json_schema strict mode, require_parameters, and response-healing, then enforce a 4-stage Python validation pipeline for invoices.

Validating OpenRouter structured outputs with JSON Schema

Sending response_format with json_schema and strict: true to OpenRouter doesn’t guarantee safe database writes—unsupported endpoints, token truncation, syntax errors, and arithmetic mismatches still slip through. Here’s how to combine provider.require_parameters, response-healing, and a 4-stage Python validation pipeline with clear boundaries.

Verification environment and scope: The model and endpoint support numbers in this post (465 models and 7 endpoints for meta-llama/llama-3.3-70b-instruct) come from live, unauthenticated GET requests to OpenRouter’s public /api/v1/models and /endpoints APIs on 2026-12-02. The 7 invoice extraction test cases (9 runs) ran without an OPENROUTER_API_KEY against a local OpenRouter-compatible mock HTTP server using Python 3.14.7 and jsonschema 4.26.0 (Draft202012Validator). Live remote schema compliance rates and upstream latency weren’t measured.

Four reasons json_schema pipelines still break in production

When you build a backend worker that extracts invoice_number, vendor, currency, line_items, subtotal, tax, and total from raw invoice text, it’s tempting to pass type: "json_schema" with strict: true and assume json.loads() will always produce clean records. Behind a single OpenRouter model ID, multiple inference providers expose different capabilities, and structured pipelines break in four distinct ways:

  1. Endpoint parameter mismatch: A model can list structured_outputs in the catalog while an individual endpoint behind it only supports response_format—or supports neither. Without strict routing, the endpoint ignores the schema and returns plain prose.
  2. Truncation (finish_reason: "length") and refusals: Even with constrained decoding enabled, hitting max_completion_tokens cuts the JSON payload mid-object. Safety refusals return an empty content with the reason placed in message.refusal.
  3. Syntax defects vs. schema violations: Some fallback paths wrap JSON in json ` code fences or leave trailing commas. Other responses parse cleanly as JSON but drop required fields or inject unexpected keys.
  4. Domain invariant mismatches: JSON Schema checks types and required keys, not business arithmetic. An invoice where sum(quantity * unit_price) != subtotal or subtotal + tax != total passes schema validation and corrupts downstream accounting tables.

Checking structured_outputs support across endpoints

OpenRouter’s public REST API lets you inspect supported_parameters per model and per endpoint without an API key. Supporting response_format often means JSON object mode only; for schema-constrained decoding, you need structured_outputs on the target endpoint.

This Python script uses only the standard library to measure catalog-wide support and inspect every endpoint behind meta-llama/llama-3.3-70b-instruct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# check_structured_support.py
import json
import urllib.request
from datetime import datetime, timezone

MODELS_URL = "https://openrouter.ai/api/v1/models"
ENDPOINTS_URL = "https://openrouter.ai/api/v1/models/meta-llama/llama-3.3-70b-instruct/endpoints"


def fetch_json(url: str) -> dict:
    req = urllib.request.Request(
        url,
        headers={
            "Accept": "application/json",
            "User-Agent": "openrouter-structured-check/1.0",
        },
    )
    with urllib.request.urlopen(req, timeout=20) as resp:
        return json.loads(resp.read().decode("utf-8"))


def main() -> None:
    queried_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    models = fetch_json(MODELS_URL).get("data", [])
    endpoints = fetch_json(ENDPOINTS_URL).get("data", {}).get("endpoints", [])

    rf_count = sum("response_format" in (m.get("supported_parameters") or []) for m in models)
    so_count = sum("structured_outputs" in (m.get("supported_parameters") or []) for m in models)
    rf_only = sum(
        "response_format" in (m.get("supported_parameters") or [])
        and "structured_outputs" not in (m.get("supported_parameters") or [])
        for m in models
    )

    print(f"[LIVE API] Queried at: {queried_at}")
    print(f"Catalog ({len(models)} models): response_format={rf_count}, structured_outputs={so_count}, response_format_only={rf_only}")
    for ep in endpoints:
        params = set(ep.get("supported_parameters") or [])
        print(ep.get("tag"), ep.get("provider_name"), "response_format" in params, "structured_outputs" in params)


if __name__ == "__main__":
    main()

Queried live at 2026-12-02T12:44:31Z, the catalog held 465 models: 415 supported response_format, 404 supported structured_outputs, and 24 supported response_format only. Looking inside meta-llama/llama-3.3-70b-instruct showed why model-level checks aren’t enough:

Endpoint tag (tag)Provider (provider_name)response_formatstructured_outputs
deepinfra/turboDeepInfraYESYES
akashml/fp8AkashMLYESYES
parasail/fp8ParasailYESYES
cloudflare/fp8CloudflareYESNO
groqGroqYESNO
coreweave/fp16CoreWeaveYESYES
amazon-bedrock/us-east-1Amazon BedrockNONO

Out of 7 endpoints, only 4 support both parameters. cloudflare/fp8 and groq support response_format without structured_outputs, and amazon-bedrock/us-east-1 supports neither. Setting provider.require_parameters: true ensures OpenRouter filters out endpoints that cannot honor your response_format schema instead of silently falling back to an unsupported host.

Strict schema requests and the response-healing boundary

Once routing restricts requests to compatible endpoints, keep the boundary between strict: true and OpenRouter’s response-healing plugin (plugins: [{ "id": "response-healing" }]) clear. response-healing repairs JSON syntax defects on the server—such as markdown code fences (json `), trailing commas, or missing closing brackets.

Two constraints define its limits: it works only for non-streaming (stream: false) requests, and it never repairs schema or semantic violations. If the model returns syntactically valid JSON with missing required fields, extra keys, wrong types, or wrong totals, response-healing passes the payload through untouched.

Layer / optionWhat it fixesWhat it doesn’t fixWhen not to use it
response_format: json_objectNudges output into valid JSON syntaxKey names, types, or required fieldsProduction ingestion requiring fixed schemas
json_schema + strict: trueEnforces schema during constrained decodinglength truncation, refusal, domain arithmeticSchemas using keywords unsupported by target providers
provider.require_parameters: trueExcludes endpoints lacking structured_outputsRequest fails (404/503) if zero endpoints matchModels where no endpoint advertises the parameter
plugins: [{ id: "response-healing" }]Strips code fences, fixes trailing commas and bracketsMissing required keys, extra keys, type or sum errorsInteractive UIs that require stream: true
4-stage app validationBlocks truncation, refusal, parse, schema, and math errorsDoesn’t auto-correct bad values (caller must retry)Never skip before writing to downstream storage

Treat response-healing as a syntax safety net, not a schema validator. If you need streaming output or strict field guarantees, you still need full validation inside your application.

Building a four-stage application validation pipeline

Even with provider.require_parameters: true, strict: true (additionalProperties: false), and response-healing enabled, your worker should gate every response through four sequential stages before writing to storage:

flowchart TD
    A["OpenRouter request (require_parameters + strict + response-healing)"] --> B["Stage 1: Check HTTP/body error, refusal, finish_reason"]
    B -->|"finish_reason == stop"| C["Stage 2: Parse JSON syntax with json.loads"]
    C -->|"valid JSON"| D["Stage 3: Validate against Draft 2020-12 JSON Schema"]
    D -->|"schema pass"| E["Stage 4: Check domain arithmetic invariants"]
    E -->|"totals match"| F["Accept record for accounting ingestion"]

Reuse the exact same INVOICE_SCHEMA dictionary for both the OpenRouter request payload and Draft202012Validator so the request contract and local validator never drift apart. The snippet below is excerpted from the tested Python 3.14.7 + jsonschema 4.26.0 pipeline (pip install jsonschema):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# invoice_pipeline.py
from dataclasses import dataclass
import json
import urllib.error
import urllib.request
from jsonschema import Draft202012Validator

INVOICE_SCHEMA = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "additionalProperties": False,
    "required": [
        "invoice_number", "vendor", "currency",
        "line_items", "subtotal", "tax", "total",
    ],
    "properties": {
        "invoice_number": {"type": "string", "minLength": 1},
        "vendor": {"type": "string", "minLength": 1},
        "currency": {"type": "string", "enum": ["KRW", "USD", "EUR"]},
        "line_items": {
            "type": "array",
            "minItems": 1,
            "items": {
                "type": "object",
                "additionalProperties": False,
                "required": ["description", "quantity", "unit_price"],
                "properties": {
                    "description": {"type": "string", "minLength": 1},
                    "quantity": {"type": "integer", "minimum": 1},
                    "unit_price": {"type": "integer", "minimum": 0},
                },
            },
        },
        "subtotal": {"type": "integer", "minimum": 0},
        "tax": {"type": "integer", "minimum": 0},
        "total": {"type": "integer", "minimum": 0},
    },
}

VALIDATOR = Draft202012Validator(INVOICE_SCHEMA)


@dataclass
class PipelineResult:
    ok: bool
    failed_stage: str | None  # stage1_envelope | stage2_json_parse | stage3_schema | stage4_domain
    reason: str
    provider: str | None = None
    data: dict | None = None


def extract_invoice(
    base_url: str,
    api_key: str,
    invoice_text: str,
    *,
    require_parameters: bool = True,
    use_response_healing: bool = True,
) -> PipelineResult:
    payload: dict = {
        "model": "meta-llama/llama-3.3-70b-instruct",
        "provider": {
            "order": ["amazon-bedrock/us-east-1", "deepinfra/turbo"],
            "require_parameters": require_parameters,
        },
        "response_format": {
            "type": "json_schema",
            "json_schema": {
                "name": "invoice_extraction",
                "strict": True,
                "schema": INVOICE_SCHEMA,
            },
        },
        "messages": [
            {"role": "system", "content": "Extract invoice fields strictly matching the JSON schema."},
            {"role": "user", "content": invoice_text},
        ],
    }
    if use_response_healing:
        payload["plugins"] = [{"id": "response-healing"}]

    req = urllib.request.Request(
        f"{base_url.rstrip('/')}/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            body = json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        with exc:
            return PipelineResult(False, "stage1_envelope", f"HTTP {exc.code}")

    provider = body.get("provider")

    # Stage 1: Envelope, body error, refusal, and finish_reason
    if body.get("error"):
        return PipelineResult(False, "stage1_envelope", f"body_error: {body['error']}", provider)
    choices = body.get("choices") or []
    if not choices:
        return PipelineResult(False, "stage1_envelope", "empty_choices", provider)
    choice = choices[0]
    message = choice.get("message") or {}
    if message.get("refusal"):
        return PipelineResult(False, "stage1_envelope", f"refusal: {message['refusal']}", provider)
    if choice.get("finish_reason") != "stop":
        return PipelineResult(False, "stage1_envelope", f"finish_reason={choice.get('finish_reason')}", provider)

    # Stage 2: JSON syntax parsing
    raw_content = message.get("content")
    if not isinstance(raw_content, str):
        return PipelineResult(False, "stage2_json_parse", "content_not_string", provider)
    try:
        parsed = json.loads(raw_content)
    except json.JSONDecodeError as exc:
        return PipelineResult(False, "stage2_json_parse", f"json_decode_error: {exc.msg}", provider)

    # Stage 3: Draft 2020-12 JSON Schema validation
    errors = sorted(VALIDATOR.iter_errors(parsed), key=lambda e: list(e.path))
    if errors:
        return PipelineResult(False, "stage3_schema", "; ".join(e.message for e in errors[:2]), provider)

    # Stage 4: Domain arithmetic invariants
    calc_subtotal = sum(item["quantity"] * item["unit_price"] for item in parsed["line_items"])
    if calc_subtotal != parsed["subtotal"]:
        return PipelineResult(False, "stage4_domain", f"subtotal_mismatch: expected {calc_subtotal}, got {parsed['subtotal']}", provider)
    if parsed["subtotal"] + parsed["tax"] != parsed["total"]:
        return PipelineResult(False, "stage4_domain", f"total_mismatch: {parsed['subtotal']}+{parsed['tax']}!={parsed['total']}", provider)

    return PipelineResult(True, None, "passed_all_4_stages", provider, parsed)

To run this client against live OpenRouter without code changes, pass base_url="https://openrouter.ai/api/v1" and read api_key from OPENROUTER_API_KEY.

Verifying seven failure and recovery cases locally

To verify every routing, recovery, and rejection path deterministically without spending credits, I ran the client against a local OpenRouter-compatible mock HTTP server bound to an ephemeral 127.0.0.1 port. The unittest suite executed 7 cases across 9 runs:

1
2
python3 check_structured_support.py
PRINT_TABLE=1 python3 -m unittest -v test_invoice_pipeline.py

| Test case | Result | Provider | Blocked stage | Observed behavior | | :— | :—: | :— | :— | :— | | C7_req_params_off | FAIL | Amazon Bedrock | stage2_json_parse | Routed to unsupported endpoint returning prose; JSON parse failed | | C7_req_params_on | PASS | DeepInfra | - | Skipped unsupported endpoint and routed to deepinfra/turbo; passed all 4 stages | | C9_valid_invoice | PASS | DeepInfra | - | Extracted valid invoice (total: 165000); passed all 4 stages | | C8_syntax_heal_off | FAIL | DeepInfra | stage2_json_parse | json code fence + trailing comma broke json.loads | | C8_syntax_heal_on | **PASS** | DeepInfra | - | response-healing stripped fence and trailing comma; passed all 4 stages | | C9_length_truncated | FAIL | DeepInfra | stage1_envelope | finish_reason=length caught before parsing at Stage 1 | | C9_model_refusal | FAIL | DeepInfra | stage1_envelope | message.refusal caught before parsing at Stage 1 | | C8_schema_violation | FAIL | DeepInfra | stage3_schema | Missing required keys + extra_unexpected_key bypassed syntax healing; blocked at Stage 3 | | C9_domain_mismatch | FAIL | DeepInfra | stage4_domain | Passed JSON Schema, then blocked at Stage 4 on 150000+15000!=170000` |

OpenRouter live structured_outputs endpoint matrix and local 4-stage invoice validation pipeline test output Figure 1. Live 2026-12-02 public API endpoint matrix (top) and 9 runs of the 4-stage invoice validation pipeline against the local OpenRouter-compatible mock server (bottom).

The last two rows highlight why each layer earns its keep. With response-healing enabled, C8_schema_violation still reached the client because the JSON syntax was valid—only Stage 3 rejected the missing required keys and unexpected property. C9_domain_mismatch passed JSON Schema cleanly and was caught only by Stage 4’s arithmetic check.

Production caveats and checklist

Before shipping a structured-output worker on OpenRouter, run through these four checks:

  • Verify provider-specific JSON Schema limits: Strict mode commonly requires additionalProperties: false and every property listed under required. Support for anyOf, $ref, and complex pattern regexes varies across providers, so smoke-test your exact schema on target endpoints before deployment.
  • Leave headroom in max_completion_tokens: Invoices with many line items expand output length quickly. Even if response-healing closes a truncated bracket, fields are already lost—treat finish_reason == "length" as a Stage 1 failure and retry with a higher token cap.
  • Separate streaming UIs from ingestion workers: response-healing applies to non-streaming calls only. If your product needs token streaming, keep structured persistence on a non-streaming worker or run the full 4-stage validator once the final message completes.
  • Monitor /endpoints parameter changes: Provider availability and supported_parameters shift over time. With require_parameters: true, a model loses all eligible routes if its remaining providers drop structured_outputs; include an /endpoints check in your pre-deploy health check.

References

Enforce JSON Schema validation on AI model responses. Get consistent, type-safe outputs and avoid parsing errors with OpenRouter's structured output feature.
Automatically validate and repair malformed JSON responses from AI models. Ensure your responses match your schema even when models return imperfect formatting.
Route AI model requests across multiple providers intelligently. Learn how to optimize for cost, performance, and reliability with OpenRouter's provider routing.
This post is licensed under CC BY 4.0 by the author.