Structured Output Returning 400? A JSON Schema Troubleshooting Guide

    When LLM structured output fails with a 400 error as soon as a JSON Schema constraint is enabled, the cause is usually request validation, not model quality. This article walks through a practical troubleshooting flow: print the raw response body first, apply the three strict-mode schema rules (all properties in required, no optional fields, additionalProperties set to false), rule out header and context-overflow false alarms, and adopt defensive practices such as local schema validation and layered error handling.

    1. The Symptom: Errors Appear as Soon as Constraints Are Enabled

    When building business systems on top of large language models, structured output is almost a mandatory capability. Extracting contract elements, generating forms, and producing records that can be written to a database all require the model to return JSON that strictly matches an agreed format. So developers naturally turn on JSON Schema constraint mode and put the field definitions into the request body, only to have the request rejected outright with a 400 status code.

    A typical minimal reproduction looks like this:

    1. schema = {
    2. 'type': 'object',
    3. 'properties': {
    4. 'name': {'type': 'string'},
    5. 'age': {'type': 'integer'}
    6. }
    7. }
    8. payload = {'model': '...', 'messages': [...], 'response_format': {'type': 'json_schema', 'json_schema': schema}}

    The most common mistake with this kind of error is to immediately suspect the model’s capability and start switching models, raising the temperature, and rewriting prompts over and over. In fact, a 400 means request parameter validation failed: the gateway or inference service rejected the request before entering model inference, which has nothing to do with generation quality. Going in the wrong direction multiplies the troubleshooting cost.

    2. Step One: Always Get the Raw Response Body

    The first principle of troubleshooting is to print what the server returned before the exception swallows it. Many wrapper libraries only surface the status code, while the real reason is hidden in the response body.

    1. try:
    2. resp = requests.post(endpoint, headers=headers, json=payload, timeout=30)
    3. resp.raise_for_status()
    4. except requests.exceptions.HTTPError:
    5. print(resp.status_code)
    6. print(resp.text) # Key: error details are here

    If the response body contains words such as strict, required, or additionalProperties, the problem lies in the schema rules themselves rather than in the business field design. This step narrows the search from “the entire business pipeline” to “one piece of configuration.”

    3. The Core Rules: Three Hard Constraints Under strict Mode

    Mainstream structured output implementations typically require a schema to satisfy three conditions in strict mode:

    1. Every field declared in properties must also appear in the required array;
    2. Optionality cannot be expressed by omitting fields; it can only be expressed by widening the type;
    3. The top-level object must explicitly declare additionalProperties as false, preventing the model from adding fields freely.

    In other words, the “age is optional” pattern in the original snippet is invalid. The correct approach is to change the type to a union type and keep the field in required:

    1. fixed_schema = {
    2. 'type': 'object',
    3. 'properties': {
    4. 'age': {'type': ['integer', 'null']}
    5. },
    6. 'required': ['age'],
    7. 'additionalProperties': False
    8. }

    The design intent is clear: strict mode aims to make output unambiguously consumable by programs. If a field may be missing, downstream parsing code has to add existence checks everywhere. Expressing “no value” explicitly with null confines uncertainty to the value level, so the structure stays stable.

    4. Rule Out Two Classes of False Alarms

    4.1 Header Validation Failures

    A malformed authorization header or a missing Content-Type also returns 400 or 401, and is easily mistaken for a schema problem. Adding two assertions before going live exposes it early:

    1. assert headers['Authorization'].startswith('Bearer ')
    2. assert headers['Content-Type'] == 'application/json'

    4.2 Context Overflow

    When an AI coding tool reads multiple files in a row and concatenates terminal logs and stack traces, the context length expands quickly. The error may then show up as a 400 (invalid parameter) or as truncation rather than a schema violation. It is advisable to set a length budget for the concatenated content and use strategies such as summarization, chunked retrieval, and keeping only relevant fragments to hold the input within the model’s context window.

    5. Defensive Engineering Practices

    • Local schema validation: run a general JSON Schema validator on the client before sending the request, so errors are caught on the client side;
    • Layered error handling: distinguish parameter 4xx, rate-limit 429, and server-side 5xx, and retry or degrade accordingly;
    • Observability: log request fingerprints and response body summaries, and combine log services with monitoring alerts to spot trend-level issues;
    • Fallback parsing: even with strict mode enabled, keep one tolerant parse and fill in field defaults so a single failure does not spread into the business.

    6. Conclusion

    When structured output goes off track, most of the time it is not the model that is at fault, but a schema that fails the formal requirements of strict mode, or a request with hidden problems at the header or context level. Proceeding in the order “get the raw error first, then validate the rules, and finally rule out false alarms” usually closes the issue within a few minutes. If you use the related model services from Baidu AI Cloud, following the same general conventions above is also recommended to obtain stable, parseable output.