You turned on strict: true so the model's JSON always matches the schema. Then one of three things happened: a deploy started returning 400 on every call, one model or region rejects a schema that works somewhere else, or the first call after a release takes much longer than usual. This post covers why strict mode is pickier than JSON Schema, how to catch problems in CI, and what strict mode still leaves to you.
How strict mode works, and why it rejects valid JSON Schema
In strict mode the provider compiles your schema into a grammar and limits token sampling to tokens the grammar allows. That only works for a subset of JSON Schema where the output is fully determined. So the rules are stricter than a normal validator:
- Every object must set
additionalProperties: false. - Every key in
propertiesmust be listed inrequired. To make a field optional, keep it required and make it nullable ("type": ["string", "null"]). - The root must be an
object. A rootanyOf(a discriminated union at the top level) is rejected, butanyOfdeeper in the schema is allowed. - Composition keywords such as
allOf,notandif/then/elseare not supported. - There are caps on total properties, nesting depth, enum values and total string length. The caps are different on OpenAI and Azure OpenAI. Check the current limits for your provider rather than hard-coding a number.
The provider compiles the schema when it first sees it. OpenAI's documentation says the first request with a new schema has extra latency and later requests with the same schema do not.
Symptom → cause → fix
| Symptom | Likely cause | Fix |
|---|---|---|
400 mentioning additionalProperties | A nested object (often a Pydantic sub-model or $defs entry) lacks additionalProperties: false | Set extra="forbid" on every model, or patch the generated schema |
400 saying required must include every key | Field has a default or is Optional with = None | Remove the default and keep it nullable |
| 400 about unsupported keyword | allOf from model inheritance, or minLength/pattern/format on Azure | Flatten the inheritance and move constraints into app-side validation |
| Works on OpenAI, 400 on Azure | Azure lists more unsupported keywords and lower nesting and property caps | Lint against the stricter list and target the lowest common subset |
| 400 only for some tenants | Enum built per request grows past the enum caps | Replace the large enum with a string and validate it after the call |
| First call after every deploy is slow | Schema text changes each release (for example field order or descriptions built at runtime), so the provider recompiles it | Generate the schema at build time and keep it byte-stable |
| Tool calls don't match the schema | Parallel tool calls with strict tools | Set parallel_tool_calls: false |
| Parse fails although strict mode is on | Output truncated by max_output_tokens or the model refused | Check status and refusal before you parse (see below) |
Error text differs by provider and API version, but it usually names the schema and the path of the node that failed. Read that path first: it points to the sub-model you need to fix.
Reproduce outside your app
To find out whether the schema or your client code is the problem, send the schema straight to the API:
cat > req.json <<'EOF'
{
"model": "gpt-4.1-mini",
"input": "Classify: checkout-api returns 502 for 40% of requests since 09:10",
"text": {
"format": {
"type": "json_schema",
"name": "triage",
"strict": true,
"schema": {
"type": "object",
"additionalProperties": false,
"required": ["evidence", "severity", "service", "runbook_url"],
"properties": {
"evidence": {"type": "string"},
"severity": {"type": "string", "enum": ["sev1", "sev2", "sev3", "sev4"]},
"service": {"type": "string"},
"runbook_url": {"type": ["string", "null"]}
}
}
}
}
}
EOF
curl -sS https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @req.json | jq '.error // .output_text'
For Azure OpenAI, send the same body to https://<resource>.openai.azure.com/openai/v1/responses with an api-key header or an Entra ID bearer token, and set model to your deployment name. Structured outputs need api-version 2024-08-01-preview or later, or the GA v1 API. Older pinned api-versions in app config are a common cause of "works locally, fails in prod".
Lint the schema in CI
Don't wait for the API to reject a schema. The script below walks the schema your code actually sends and flags the common violations. Add the stricter Azure keyword list when you deploy there.
import json, sys
UNSUPPORTED_COMMON = {"allOf", "not", "if", "then", "else",
"dependentRequired", "dependentSchemas"}
UNSUPPORTED_AZURE = {"minLength", "maxLength", "pattern", "format",
"minimum", "maximum", "multipleOf",
"patternProperties", "unevaluatedProperties", "propertyNames",
"minProperties", "maxProperties", "unevaluatedItems",
"contains", "minContains", "maxContains",
"minItems", "maxItems", "uniqueItems"}
def lint(node, path, problems, banned, depth=0):
if not isinstance(node, dict):
return depth
for kw in banned & node.keys():
problems.append(f"{path}: unsupported keyword '{kw}'")
types = node.get("type")
is_obj = types == "object" or (isinstance(types, list) and "object" in types)
max_depth = depth
if is_obj:
depth += 1
max_depth = depth
if node.get("additionalProperties") is not False:
problems.append(f"{path}: additionalProperties must be false")
props = node.get("properties", {})
missing = set(props) - set(node.get("required", []))
if missing:
problems.append(f"{path}: not in required: {sorted(missing)}")
for name, sub in props.items():
max_depth = max(max_depth, lint(sub, f"{path}.{name}", problems, banned, depth))
if "items" in node:
max_depth = max(max_depth, lint(node["items"], f"{path}[]", problems, banned, depth))
for i, sub in enumerate(node.get("anyOf", [])):
max_depth = max(max_depth, lint(sub, f"{path}.anyOf[{i}]", problems, banned, depth))
for name, sub in node.get("$defs", {}).items():
lint(sub, f"$defs.{name}", problems, banned, 0)
return max_depth
schema = json.load(open(sys.argv[1]))
banned = UNSUPPORTED_COMMON | (UNSUPPORTED_AZURE if "--azure" in sys.argv else set())
problems = []
if "anyOf" in schema or schema.get("type") != "object":
problems.append("$: root must be a plain object, not anyOf")
depth = lint(schema, "$", problems, banned)
print(f"object nesting depth: {depth}")
print("\n".join(problems) or "OK")
sys.exit(1 if problems else 0)
Depth from $ref targets is not counted across references. If your provider's nesting cap is tight, resolve references before you lint.
Pydantic models that pass strict mode
Most rejections come from generated schemas. Pydantic v2 emits additionalProperties: false only when you forbid extra fields, and it leaves out of required any field with a default.
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict
from openai import OpenAI
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid")
class Evidence(Strict):
source: str
quote: str
class Triage(Strict):
evidence: list[Evidence] # put reasoning-style fields first
severity: Literal["sev1", "sev2", "sev3", "sev4"]
service: str
runbook_url: Optional[str] # nullable, but no default -> still required
client = OpenAI()
resp = client.responses.parse(
model="gpt-4.1-mini",
input=[{"role": "user", "content": "checkout-api 502s since 09:10"}],
text_format=Triage,
max_output_tokens=800,
)
if resp.status == "incomplete":
raise RuntimeError(f"truncated: {resp.incomplete_details.reason}")
if resp.output_parsed is None:
raise RuntimeError(f"no parsed output (refusal?): {resp.output}")
triage: Triage = resp.output_parsed
Export Triage.model_json_schema() to a file in CI and run the linter on it. The SDK helpers rewrite parts of the schema, but don't rely on them to fix defaults or inheritance. On Chat Completions the helper is client.beta.chat.completions.parse in older SDK versions, and it may be available without beta in newer ones. Check your installed version. There, check choices[0].finish_reason == "length" and message.refusal before you read message.parsed.
Warning
Class inheritance with shared base fields can produce
allOfin some generators. Flatten the models or use a mixin that only setsmodel_config, as shown above.
Design trade-offs strict mode forces on you
Constraints move into your code
Azure doesn't accept pattern, minLength or numeric bounds in the schema, so validate those after the call and send the model back to fix them once. The grammar guarantees the structure. Business rules are still up to you.
Key order matters
Output follows the order of keys in the schema. If you put evidence or a short reasoning field before severity, the model writes its evidence before it commits to a label. That often improves accuracy, and you can log the evidence for audits. Putting the label first gives the model nothing to base it on.
Nullable is not the same as honest
Because every field is required, the model has to produce something for each one. If it has no value, it may invent a plausible one rather than return null. Say in the field description when to use null, and track how often each nullable field is null. A sudden drop usually means the model is filling gaps with guesses.
Keep schemas static
If you build an enum per tenant, or put timestamps or IDs into descriptions, the schema text changes every time. Each change costs a compile on the first call and can run into the enum caps. Keep large or changing value sets out of the schema. Accept a string and check it against your lookup table.
Caution
Don't fall back silently from
strict: trueto plain JSON mode when a schema is rejected. Downstream automation would then receive JSON that isn't checked against the schema. Fail closed and alert instead.
Prevent it next time
- Generate schemas at build time, commit them, and run the linter with
--azureif you deploy to Azure. - Add a contract test per model and region that sends each schema once with a tiny prompt and checks the call doesn't return 400.
- Pin the api-version in config and alert on 400 responses that mention the schema, kept separate from other 400s.
- Track how often responses are truncated, refused or have null fields, per schema version.
- Set
parallel_tool_calls: falsewherever tools usestrict: true. - Before a release, compare the schema hash with the last release so you know when the first call will pay the compile cost.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get