Structured outputs and JSON schemas: making agent responses reliable enough for code
If an agent's output is going to be read by another program rather than a person, free-form text becomes a liability. Structured outputs are the fix: you ask the model to return data in a defined shape, usually JSON matching a schema.
Ways to get structure, from weakest to strongest:
- Prompting only. "Respond in JSON with fields a, b, c." Works most of the time, fails occasionally with extra prose or missing fields.
- JSON mode. The API guarantees valid JSON, but not that it matches your schema.
- Schema-constrained output. Many APIs now accept a JSON schema and constrain generation to it, so field names and types are guaranteed.
- Tool/function calling. Defining a "tool" whose arguments are the structure you want is another common trick.
Things to keep in mind:
- Valid structure is not the same as correct content. Still validate values (ranges, IDs, dates).
- Very deep or complex schemas can reduce answer quality; flatter is often better.
- Include a field for "unsure" or "not found" so the model is not forced to invent a value.
- Libraries like Pydantic or Zod make it easy to define schemas once and validate responses.
Do you prefer schema-constrained output or tool calling for structure? And how do you handle cases where the model fills a required field with a plausible guess?
Comments · 4
Is JSON mode the same thing as a schema? I'm confused between "return valid JSON" and "return JSON matching this exact shape".
They're different. JSON mode only promises syntactically valid JSON, while a schema constrains the fields and types. Schema is the one you want if code depends on specific keys.
Always validate on your side too. Treat the model's output as untrusted input, even with a schema.
Business upside is fewer parse failures and retries, which means lower costs and better reliability for anything customer-facing.