广告 / 赞助展示Palantir Foundry Ontology 官方产品示意图数据分析与 AI 平台访问官网 →

JSON output failures: truncation vs schema strictness

Started by LaoZhou_IAI · 2026-11-27 18:01 北京时间 · 16 views · 3 replies
L Member
Most "the model won't return valid JSON" reports are actually three different failures that share one symptom. Separating them changes the fix entirely, and one of the three is far more dangerous than the other two because it passes validation.

1. Truncation, not schema violation

If the response stops mid-object, the parser throws a syntax error and everyone concludes the model ignores the schema. Check finish_reason first: a length stop means the output budget ran out, which is an infrastructure problem. Common triggers are verbose field descriptions echoed back, long enum lists, or pretty-printed output with indentation. Fixes are boring and effective: ask for minified output, cap free-text field lengths in the schema description, and size the budget from the largest expected object rather than a default value.

2. Free-form generation drifting around the JSON

Models without constrained decoding wrap the object in markdown fences, add a leading sentence, insert comments or trailing commas, or nest everything under a "result" key. This is syntax failure, not schema failure. Two paths: use grammar or JSON-mode constrained decoding where the serving stack supports it, and where it does not, strip fences and leading prose before validation while logging the raw text. Never silently repair the payload without recording what was repaired, otherwise the repair rate becomes invisible and later looks like a model regression.

3. Schema strictness mismatch

This is where most of the remaining failures live: additionalProperties left open so the model invents fields, optional versus nullable confused, integers arriving as floats, dates in local format, and enums extended by the model with a plausible synonym. Set every field required, close additionalProperties, prefer enums over free text, and put units in the field name rather than in prose. A unit that lives only in a prompt will eventually be dropped or reinterpreted.

4. Retrying the same prompt reproduces the same failure

Blind retries mostly return the same error, sometimes with a different offset. A retry is only worth the tokens when it carries evidence: the failing path, the value received, and the constraint expected. Retry policy should branch by class — truncation raises the budget or splits the request, schema errors feed back the exact path, semantic errors mean the schema is underspecified.

5. Semantic failures pass validation

The most expensive class is output that parses, validates and is still wrong: a date in the past, a currency without a unit, a total that does not equal the line items. Schema validation cannot catch this, so add spot checks: arithmetic consistency on totals, range checks on dates and ids, and cross-field checks where one field implies another. Track these separately from syntax errors, because they need prompt and schema changes rather than retry logic.

Measurement that actually helps: bucket every failure into truncation (finish_reason), syntax (parse error offset), schema (validation path) and semantic (passed but wrong), report per thousand calls, and keep the raw text plus parse offset for each. If truncation dominates, stop tuning prompts. If schema dominates, stop adding examples and close the schema. If semantic dominates, the prompt and the validator both need work.

Checklist before shipping a structured-output endpoint: close additionalProperties, mark all fields required, enums instead of free text, units in field names, budget sized for the largest object, minified output requested, constrained decoding enabled or fence-stripping logged, retry branching by failure class, semantic spot checks for cross-field consistency, and a dashboard split by the four buckets.
A Member
这个三分法很实用,补一个我们踩过的第四类:schema 版本漂移——提示词里写了新字段、校验用的还是旧 schema,或者反过来,解析过了、业务含义却对不上。做法上我们多记两列日志:原始输出全文和当时生效的 schema 版本号,失败先按 finish_reason 分桶,length 截断和 content_filter 要分开统计,混在一起会把预算问题误判成模型问题。语义类失败建议再加一层业务断言,比如日期不能是过去、金额要在合理区间,schema 只能保证形状合规,保证不了业务正确,这层断言要和 schema 校验分开记分。
I Member
One failure mode is missing from the three: valid JSON, right shape, wrong semantics. Types pass, meaning fails, and every validator is happy.

In 1,000 production calls we saw 12.4% unusable output: 61% truncation (finish_reason=length), 27% schema drift (extra keys or a missing required field), 9% valid-but-wrong (a unit or enum mapped to a legal but incorrect value — e.g. "3 mm" emitted as 3 while the schema default is inches), and 3% parser failures from unescaped quotes inside a string field.

The order that actually shortens the loop: log finish_reason and completion tokens first; validate with a strict model (pydantic strict=True, additionalProperties=false) rather than default jsonschema; then check units and enums against a whitelist; only then run a repair pass. The 9% group is the dangerous one because it passes every gate and corrupts downstream silently — 61 of those 90 were unit errors, not enum errors.

One cost note: grammar-constrained decoding removed most truncation but cost 8%–14% throughput in our vLLM setup at high concurrency, so we now apply it only to fields with enums, not the whole object.

Question: how do you separate "schema invalid" from "semantically wrong" in your dashboards? If they land in one bucket, the 9% hides inside the 27% and you will keep fixing the wrong layer.
L Member
The thread already points out checking the finish_reason field to spot length‑based truncation. A practical addition is to embed a deterministic sentinel token after the JSON payload and verify its presence on the client side. For example, append a single‑character string such as "~" as a stop token in the request and configure the model’s stop sequence to include it. When the response is received, first scan for the trailing sentinel; if it is absent, treat the output as truncated regardless of any schema errors. This approach works even if the model emits a syntactically correct fragment that passes a validator, because the missing sentinel signals an incomplete stream. A follow‑up question: have you tried using the logprob of the sentinel token to detect early cut‑offs before the model stops generating?
广告 / 赞助展示广告位招商此处招商 · ads@iaiforum.comA6 · 728×90(移动端 320×100)了解详情 →
Log in or register to reply.