JSON Mode 400 Error: A Troubleshooting Guide for Structured LLM Output
This article walks through a real-world 400 error that appeared after enabling strict JSON structured output on a large language model API. It explains why structured output is a critical capability in production pipelines, how to capture the raw response body as evidence, the schema rules that strict mode enforces (required fields, union types for optional values, and additionalProperties: false), and two common false positives such as header validation failures and context overflow. It closes with practical engineering recommendations for request wrapping, error classification, fallback strategies, observability, and model switching.
1. Background: Why Structured Output Is a Dividing Line in Production
Discussion around the latest generation of coding-focused large models keeps heating up, but the real dividing line is not whether a conversation flows smoothly. It is four hard capabilities on the engineering side: the accuracy of code completion, the completeness of instruction following, the reliability of structured responses, and the continuity of tool-call chaining. If any one of these is unstable, the model stays in the “used manually by a human” stage and cannot be taken over by a system.
Take the model service access approach offered by the Baidu AI Cloud Qianfan large model platform as an example. Calling models through a unified API pulls authentication, timeouts, concurrency, retries, and model switching down into the protocol layer. What developers face is a stable interface rather than volatile page state. This matters most in high-friction scenarios such as long-running tasks, multi-turn constraints, and script generation: the business does not need one impressive answer, it needs results that keep being executable.
This article uses a high-frequency failure, “a 400 returned immediately after enabling JSON structured output,” as the entry point and lays out a reusable troubleshooting path.
2. The Failure Scene: A Typical 400 Error
A certain intelligent coding tool relies on the model’s function-calling ability when reading files and executing terminal commands, turning the file system and the terminal into operable tools. The team enabled strict structured output in the request body:
payload = {"model": "<your-model-name>","messages": [{"role": "user", "content": "Extract user information"}],"response_format": {"type": "json_schema","json_schema": {"name": "user_info","strict": True,"schema": {"type": "object","properties": {"name": {"type": "string"},"age": {"type": "integer"}}}}}}
The request came back with a 400 straight away, and the business fields themselves were fine. The easiest mistake at this point is to immediately suspect the model is not capable enough and start swapping models or repeatedly tuning the prompt.
3. Step 1: Capture the Raw Response Body, Do Not Guess
The first principle of troubleshooting is to preserve evidence. Error information must be captured in full rather than swallowed by an upper-layer framework:
import requeststry:resp = requests.post(endpoint, headers=headers, json=payload, timeout=30)resp.raise_for_status()except requests.exceptions.HTTPError:print(resp.status_code)print(resp.text) # Key: the reason is usually written in the response body
When the response body explicitly mentions constraints related to strict, the focus of the investigation is no longer the business fields but the schema rules themselves. Printing the error message to logs and keeping the request ID is the prerequisite for aligning on the issue with the platform side later.
4. Step 2: Understand the Schema Rules of Strict Mode
The core constraints of strict structured output can be summarized in three points:
- Every field listed in
propertiesmust appear in therequiredarray; - Fields that are “optional” from a business standpoint cannot be omitted from the definition; they can only be loosened through union types;
- Object levels must explicitly forbid extra fields to avoid the model improvising.
The corrected version looks like this:
fixed_schema = {"type": "object","properties": {"name": {"type": ["string", "null"]},"age": {"type": ["integer", "null"]}},"required": ["name", "age"],"additionalProperties": False}
The design philosophy here is to translate “optional” from “the field may be missing” into “the field must exist and its value may be null.” This satisfies the validator’s need for determinism while preserving flexibility in business semantics. Nested objects and array elements follow the same rule, and the deeper the hierarchy, the more carefully each level must be checked.
5. Step 3: Rule Out Two High-Frequency “False Failures”
5.1 Header Validation Failure
A fair share of 400s do not come from the schema but from the most basic protocol validation:
assert headers["Authorization"].startswith("Bearer ")assert headers["Content-Type"] == "application/json"
Spaces before or after the key, mistakenly using text/plain, or submitting the request body as a form will all get the request rejected before it ever reaches the model logic.
5.2 Context Overflow
When an intelligent coding tool reads files and concatenates terminal logs back to back, the input length balloons quickly. The error code here may show up as 400, or as 413 or 429, depending on the gateway implementation. The way to handle it: truncate and summarize concatenated content, dynamically trim history against a token budget, and write large logs to disk so only the key fragments are sent.
6. Actionable Engineering Recommendations
- Request wrapping: wrap the model call layer in one place and maintain
response_format, timeouts, and retries together; - Error classification: split 4xx into “authentication, parameter, and quota” categories and alert on each separately, avoiding all-in-one retries that amplify the failure;
- Fallback strategy: when structured output fails, degrade to plain text output plus client-side parsing so the pipeline is not interrupted;
- Observability: connect logging services and monitoring alerts, and build dashboards for structured output success rate and average token consumption;
- Model switching: under the unified interface of platforms such as Baidu AI Cloud Qianfan, switch between models of different sizes per scenario and let protocol-layer capabilities backstop business stability.
7. Conclusion
When structured output goes off the rails, most of the time it is not that the model “cannot do it” but that the request contract is not aligned. Follow the order of “get the evidence first, verify the rules next, check the environment last,” write the schema as a deterministic structure, and fold authentication and context into routine checks. Structured responses then turn from an occasional surprise into stable output, and only then does the model truly meet the conditions for being taken over by a production system.
