Handling truncated JSON and missing fields in OpenRouter
Request JSON Schema output from OpenRouter and use Python to distinguish a truncated completion, malformed JSON, and missing required fields.
A Chat Completions request can carry a JSON Schema. Before storing the result, check how generation ended and whether the returned JSON contains the fields the application needs. I use the Jekyll 4.4.0 release notes to show which check catches each failure.
I ran the snippets with Python 3.14.7, OpenAI Python SDK 3.60.0, and jsonschema 4.26.0 against mock HTTP responses. I checked model support in the public endpoint catalog on December 1, 2026. OpenAI Python SDK · jsonschema package
Define the format the next program will read
In my OpenRouter release-note walkthrough, I read the summaries as prose. If another program needs to show compatibility changes under a separate heading, I want a stable shape. The example uses a version string and two string arrays named features and breaking_changes. A release can have an empty list. Keeping the key present gives the application a way to distinguish that result from a missing field. Jekyll 4.4.0 release
| Result you need | Request format |
|---|---|
| A summary for a person | Free-form text |
| A JSON object with flexible keys | response_format.type: json_object |
| Fixed keys and types | response_format.type: json_schema and application validation |
There are two JSON layers on this request path. The outer Chat Completions HTTP body is a JSON object. The model’s generated text is inside choices[0].message.content. Parse that string before applying the schema. This division also gives an error handler enough context to tell a malformed API body from broken JSON in the generated text. OpenRouter structured outputs · Chat Completions API
Check which endpoints advertise structured output
The public GPT-6 Luna endpoint response listed response_format and structured_outputs in supported_parameters for the endpoint tagged openai. I use those fields to identify a candidate that advertises the feature. An authenticated completion response identifies the route and result for an actual request. In the request below, provider.require_parameters: true narrows routing to providers that support the request parameters. GPT-6 Luna endpoint response · Provider routing
Reuse the same schema in the request and validator
Set up an OpenAI Python SDK client with base_url set to https://openrouter.ai/api/v1 and read the key from the environment. I disabled retries for the tests. Prepare messages with the Jekyll excerpt and an instruction to preserve the version and put compatibility-breaking changes under breaking_changes. The first block uses that client and message list. A live completion with this model can use credits. OpenRouter quickstart · GPT-6 Luna model details
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from jsonschema import Draft202012Validator
SCHEMA = {
"type": "object",
"properties": {
"version": {"type": "string"},
"features": {"type": "array", "items": {"type": "string"}},
"breaking_changes": {"type": "array", "items": {"type": "string"}},
},
"required": ["version", "features", "breaking_changes"],
"additionalProperties": False,
}
validator = Draft202012Validator(SCHEMA)
response = client.chat.completions.with_raw_response.create(
model="openai/gpt-6-luna",
messages=messages,
response_format={
"type": "json_schema",
"json_schema": {"name": "release_summary", "strict": True, "schema": SCHEMA},
},
extra_body={"provider": {"require_parameters": True}},
max_completion_tokens=1024,
)
I request strict application of the schema with strict: true. All three properties are required, and additionalProperties: false rejects extra keys. The local Draft202012Validator gets the same schema object. A change to the app’s expected fields can then be made in one place. Provider support for individual keywords can vary, so check the endpoint before extending the schema. JSON Schema object rules · jsonschema validation API
Read the finish reason before parsing text
Check for errors on the response envelope and its first choice. Then read the finish reason and look for a refusal or missing text. The Python SDK raises APIStatusError for HTTP error statuses. This fragment handles the body of a successful HTTP response, including a provider error that may still appear inside it. OpenRouter error handling
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
import json
def parse_completion(body):
if not isinstance(body, dict) or body.get("error"):
raise ValueError("Invalid or failed completion response")
choices = body.get("choices")
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
raise ValueError("No valid completion choice")
choice = choices[0]
if choice.get("error"):
raise ValueError("Provider error in completion choice")
reason = choice.get("finish_reason")
if reason != "stop":
raise ValueError(f"Completion finished with {reason}")
message = choice.get("message")
if not isinstance(message, dict) or message.get("refusal"):
raise ValueError("Missing message or model refusal")
content = message.get("content")
if not isinstance(content, str) or not content.strip():
raise ValueError("No text content to parse")
summary = json.loads(content)
validator.validate(summary)
return summary
summary = parse_completion(response.http_response.json())
Compare the failures on a fixed response set
I passed mock HTTP responses through the actual OpenAI SDK. The requests contained the schema and the provider parameter requirement. I then changed the returned body to check where a failure was caught.
| Mock response | Observed result |
|---|---|
stop with all three expected fields | Returns the parsed object |
JSON looks complete but the finish reason is length | Raises ValueError before parsing |
stop with malformed generated JSON | Raises JSONDecodeError |
Missing breaking_changes or a number in features | Raises ValidationError |
Correct shape with version 4.5.0 | Returns the object. A source check must catch the version mismatch. |
A string field describes a type. Check separately that the value matches the release in the input. Here the source version is 4.4.0, and the raised minimum Ruby version can break an existing deployment. When logging a parsing failure, keep the stage with the exception type. Both decoding the outer HTTP body and parsing the generated string can raise JSONDecodeError. The stage tells you which input to inspect. If you configure fallback models, check structured-output support for each candidate and apply the same validation to every response.
- Keep HTTP errors, errors inside a completion, and output parsing errors separate.
- Check the output cap and request conditions when you see
finish_reason=length. - Verify the version and claims against the source after the shape passes validation.