AI Agent JSON Mode Output 2026
The agent answers in prose and your program needs regexes, keyword extraction and endless variant handling. Have it emit JSON instead and parsing drops to one field access. Three constraint levels, Pydantic schemas, and retry on validation failure.
📜 Table of Contents
📖 Keep reading
Structured Output for Agents: JSON Beats Prose
Ask for an intent and get a paragraph. Humans understand it; code does not. Regexes break the moment the wording changes. Structured output turns parsing into a field access, at the cost of a new failure mode: invalid JSON.
Three levels of constraint
| Approach | Mechanism | Reliability |
|---|---|---|
| Prompt-only format | model compliance | medium |
| JSON mode | valid JSON, schema unchecked | high |
| Strict schema | constrained decoding | highest |
Names differ by provider (OpenAI response_format with json_schema and strict, Gemini responseSchema, tool-call input_schema elsewhere). Use strict mode where available.
Define once with Pydantic
from pydantic import BaseModel, Field
from typing import Literal, Optional
class FlightIntent(BaseModel):
intent: Literal["book", "change", "cancel", "ask"]
destination: Optional[str] = Field(None, description="city, null if absent")
date: Optional[str] = Field(None, description="ISO date; resolve relative dates in code")
confidence: float = Field(ge=0, le=1)
Use enums over free strings, None defaults over empty strings, and compute dates in code rather than asking the model to do arithmetic.
Validate and retry
def extract(client, prompt, schema_cls, retries=2):
for _ in range(retries + 1):
raw = client.complete(prompt, response_schema=schema_cls.model_json_schema())
try:
return schema_cls.model_validate_json(raw)
except Exception as e:
prompt = f"{prompt}\n\nPrevious output failed validation: {e}. Emit schema-valid JSON only."
raise ValueError("structured output failed")
Feeding the validation error back is far more effective than a blind retry. Two retries is enough; more means the schema or prompt is wrong. Libraries such as instructor wrap this pattern.
Streaming
Accumulate and parse at the end, or use an incremental parser. Put fields you want to show early at the front of the schema.
Failure modes
| Symptom | Cause | Fix |
|---|---|---|
| ```json fences | habit | strip fences before parsing |
| trailing commas | typo-like output | tolerant parser or retry |
| full-width quotes | language habit | require ASCII quotes |
| missing fields | complex schema | flatten, fewer required |
| numbers as strings | weak typing | strict mode plus coercion |
| truncated JSON | low max_tokens | budget output by schema size |
Truncation masquerades as a parse error. Check finish_reason first.
Schema design
Flat over nested. Few but accurate required fields. Never let the model do arithmetic. Version your schemas so old records keep parsing.
FAQ
JSON mode versus strict schema? JSON mode guarantees syntax only; strict schema guarantees fields and types.
No strict mode available? Fall back to tool calling with an input schema, then prompt plus validation retry. Always validate.
Does it hurt answer quality? Yes for long-form writing; it suits extraction and classification. Split by task type.
Convert Markdown to JSON afterwards? No. Every conversion layer is another failure point.
Support and parameter names vary by provider; check the official API docs.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.