DEV Community

Cover image for Your LLM returned JSON. Is it the JSON you asked for? (Friday AI question)
M.T.Ramkrushna
M.T.Ramkrushna

Posted on

Your LLM returned JSON. Is it the JSON you asked for? (Friday AI question)

Friday AI Question. This one is about the line of code right after the model call: json.loads(...).

Your app asks an LLM for JSON and passes it to code. How do you make sure it's the JSON your code expects?

Pick one (and tell me in the comments):

  • A) The prompt says "respond only in JSON". Then we parse and hope.
  • B) JSON mode. The API guarantees valid JSON.
  • C) Structured outputs: a strict JSON Schema the model is constrained to follow.
  • D) C, plus handling refusals and cut-off responses, validating business rules in code, and evals on the field values.

My lean: C is the floor, D is the goal. Here's why.

Valid JSON is not the same as your JSON

This is the trap in option B. OpenAI's own announcement of Structured Outputs says it plainly: JSON mode "improves model reliability for generating valid JSON outputs," but "it does not guarantee that the model's response will conform to a particular schema."

So JSON mode protects you from a missing bracket. It doesn't protect you from a missing customer_id, a string where you expected a number, or a field name the model made up. json.loads passes, and the bug shows up three functions later.

Anthropic's structured outputs docs list the same failure modes you get without a schema, even with careful prompting: parsing errors from invalid JSON, missing required fields, inconsistent data types, and schema violations that need error handling and retries.

What option C actually buys you

Structured outputs use constrained decoding. OpenAI explains that for each JSON Schema they compute a grammar, and while sampling, after every token, the inference engine decides which tokens are valid to produce next. The model can't emit a token that breaks the schema.

The numbers from OpenAI's launch post: on their evals of complex JSON schema following, gpt-4o-2024-08-06 with Structured Outputs scored 100%. gpt-4-0613 scored less than 40%.

Both OpenAI and Anthropic now offer this (OpenAI as json_schema response format and strict function calling; Anthropic as JSON outputs in output_config.format and strict tool use). A few things to know:

  • Only a subset of JSON Schema is supported. Both vendors document limitations. Check yours before designing a clever schema.
  • The first request with a new schema is slower. The grammar is compiled once. Anthropic caches compiled grammars for 24 hours from last use, and changing the schema structure invalidates that cache.
  • Mark properties required and close the object. OpenAI's examples use required for every field and "additionalProperties": false.

Why C is still not the whole answer (option D)

Here's the part people miss. OpenAI's docs say Structured Outputs constrains completed, non-refusal output, and your application "still needs to handle refusals, incomplete responses, and API errors, and validate any business rules that the schema does not express."

Anthropic's docs list the same two cases where output might not match your schema:

  • Refusals. stop_reason: "refusal", still a 200 status code, still billed, and the output might not match your schema because the refusal takes precedence. (OpenAI exposes a refusal field for the same reason.)
  • Token limits. stop_reason: "max_tokens" means the output might be incomplete and not match the schema.

And a schema can't tell you if the values are right. "amount": 4200 is a valid integer whether the invoice said 4,200 or 42.00.

So my checklist for D:

  1. Use strict structured outputs (or strict tool use) instead of prompt-only JSON or JSON mode.
  2. Check why the model stopped before you parse. Refusal and max-token cut-offs get their own code path.
  3. Validate again in code with Pydantic, Zod or similar, including business rules the schema can't express (ranges, cross-field checks, IDs that must exist).
  4. Keep the schema small and flat where you can, inside the supported subset.
  5. Run evals on field values, not just "did it parse". Exact-match the fields that matter on a labeled set.
  6. Log validation failures and look at them weekly. They tell you where the schema or prompt is wrong.

So, A, B, C or D?

A lot of apps I see are still at A or B, with a retry loop that re-asks the model when parsing fails. If you're at D, I'd like to hear how you test field accuracy.

How does your app get JSON out of the model today? And what was the weirdest "valid" output that still broke your code?

References

Top comments (0)