Structured Output Patterns
”Make agents predictable: enforce schemas, validate outputs, and recover automatically when the model slips.”
TL;DR
Structured output is how you make LLM responses machine-parseable instead of hoping for clean text. Define your schemas with Pydantic using rich field descriptions (Schema-First design), and choose between function calling (hard constraint for tool use) and JSON mode (soft constraint for reasoning). Always include a thought_process field as the first key to preserve chain-of-thought accuracy. When output breaks, use a self-correction loop that feeds Pydantic validation errors back to the model for up to 3 retries. Grammar-based sampling (Outlines for open-weight models, schema-enforced modes on hosted APIs) guarantees schema-valid JSON unless the output is truncated. Related reading: these patterns pair directly with the validation layers in Error Handling and Recovery and the structured trace events in Observability and Tracing. For agent planning schemas, see Planning and Decomposition.

1. Introduction: The “AI Contract”
1.1 The History of the AI Contract
In the early days of LLMs (2020-2022), developers spent much of their time writing “Garbage Disposal” code, complex regex functions designed to clean up the conversation. You would ask for a list of fruits and get: “Sure, I love fruits! Here they are: 1. Apple, 2. Banana… hope this helps!”. This was the “Dark Ages” of agentic engineering. Today we handle this through Hard Constraints.
1.2 The Precision/Creativity Trade-off
There is a fundamental tension in LLMs. The more you force them to follow a structure (Precision), the less “Creative” they become. For an agent checking a bank balance, you want 100.0% precision and 0.0% creativity. Structured output is the dial you use to turn down the model’s “hallucination engine” and turn up its “logic engine.”
1.3 Why JSON Won the AI War
While LLMs can output XML or YAML, JSON is the undisputed champion. It is token-efficient, natively supported by all major model providers (OpenAI, Anthropic, Google), and perfectly matches the dict and class structures of modern programming languages like Python and TypeScript.
2. Implementing a “Drafting” Loop for JSON
Sometimes a single turn is not enough to get a complex JSON right.
The Workflow:
- Draft: Agent A outputs a draft JSON.
- Audit: An automated script checks for “Null” fields or type mismatches.
- Refactor: The script sends a prompt back: “Your JSON had 2 empty fields. Based on the source text, can you fill those in? Here is your previous attempt: [JSON]”
- Final: The agent outputs the complete, verified JSON.
3. The “Schema-First” vs. “Prompt-First” Debate
Should you define your logic in the JSON Schema or the System Prompt?
- Schema-First: Put all constraints in the
descriptionfields of the Pydantic model. - Prompt-First: Put the logic in the main instruction block and keep the schema “Dumb.”
- Verdict: Schema-First is more reliable. A rule attached to the field it governs is scoped and unambiguous: the model reads the field name, its type and its rule together, instead of matching a paragraph in a long prompt to the right key. The rule also travels with the schema when you reuse it in another agent.
4. Handling “Token Overflows” in JSON
What if the LLM’s JSON is 5,000 tokens but your max_tokens is 4,000? The JSON will be cut off at the end, usually looking like ... "key": "val.
The Fix: Partial Parsing.
Use a library like partialjson or json-stream. These can parse a “Broken” JSON string and return as many valid keys as were successfully generated before the cutoff. This prevents the entire request from being a total loss.
5. Security: The “JSON Bomb” and Denial of Service
Malicious agents (or poisoned data) can output thousands of nested brackets: [[[[[[[[...]]]]]]]].
The Defense:
- Max Size and Depth: Cap the raw payload size before parsing, and reject structures nested deeper than your schema allows (e.g., 5 levels). Python’s
jsonmodule has no depth option, so check size first and validate depth after. - Schema Enforcement: Never use
Dict[str, Any]in your production code. Always define every field. - Strict Typing: Use Pydantic’s strict mode so the model cannot pass
"10"where anint10 is required. - Sanitization: Treat string values as untrusted. Escape them before rendering in HTML (XSS) and never interpolate them into queries or shell commands (Section 19).
6. Advanced Pattern: The “CoT + JSON” Hybrid
One of the biggest mistakes developers make is asking for pure JSON (essentially asking for the result without the thinking). When you force a model to output only JSON, you are forcing it to skip its “Reasoning” step. The “Let Me Speak Freely?” study (Tam et al., 2024) found that strict format constraints measurably lower reasoning accuracy.
The Fix: The Reasoning Envelope.
Include a thought_process field as the first key in your schema. Because LLMs process tokens sequentially, this forces the model to “explain” its logic before it picks the final value for the data fields.
Example Schema:
{
"thought_process": "The user mentioned they are 25 but were born in 1998, which is consistent. They live in Paris, which is in France.",
"age": 25,
"country_code": "FR",
"confidence_score": 0.95
}
By allowing this “Internal Monologue,” you usually recover much of that lost accuracy, especially for complex extraction tasks. Measure it on your own data. With models that reason natively before answering, the field matters less, but it still gives you an auditable explanation per record.
7. Schema Design Patterns for Agents
7.1 The “Envelope” Pattern
Wrap your data in a metadata layer. This allows your code to distinguish between an “Agent Answer” and an “Agent Error” using the same consistent JSON structure.
{
"status": "success",
"payload": { ... },
"error_msg": null,
"execution_time_ms": 450
}
7.2 The “Polymorphic” Tool
Instead of having 10 different tools (which bloats the context window), use one perform_action tool that takes a Union of different types (e.g., CreateUser, UpdateUser).
7.3 The “Recursive Schema” Pattern
For tasks like summarizing a document’s table of contents, use a schema that allows a node to have child nodes.
class Header(BaseModel):
title: str
sub_headers: List["Header"] = [] # Recursive!
This is essential for capturing hierarchical information without losing the parent-child relationships.
8. Token Efficiency: The Math of JSON Keys
In a traditional API, key names like user_authentication_timestamp_registered are fine, they add clarity. In AI agents, Keys cost money.
8.1 The Compression Ratio
If you are processing 1 million requests a day:
- Key
"account_balance_in_usd"= 7 tokens (OpenAI’scl100k_baseando200k_basetokenizers, quotes included). - Key
"bal"= 3 tokens. - Savings: About 4 tokens per occurrence. Over 1M requests, that’s 4 million tokens a day. At $10 per million output tokens, one rename saves about $40/day, and the effect multiplies across every key in a large schema.
8.2 The “Schema-Mapping” Solution
You can use a “Compressed Schema” for the LLM (with 1-letter keys) and then have a small Python function that maps a -> "account_name", b -> "balance" before the data hits your database. This gives you token efficiency and human-readable code. Test it first: a cryptic key removes the meaning the model uses to fill it, so keep a clear description on every short key and check that accuracy holds.
9. Pydantic schemas and field descriptions
Use Pydantic classes to define your schemas. Pydantic handles the translation to JSON-Schema (which the LLM actually sees) and ensures that the model’s output is parsed into a clean Python object with full type safety.
The Mini-Prompt Power:
The Field(description="...") parameter in Pydantic is your most powerful tool.
class UserProfile(BaseModel):
mood: str = Field(description="One of [HAPPY, SAD, ANGRY]. Default to HAPPY if unclear.")
The LLM provider (like OpenAI or Anthropic) passes these descriptions to the model as part of the tool or response schema. A precise description like “Integer between 1 and 100. If unknown, return -1” is often more effective than a 5-page PDF of instructions, because the rule is attached to the exact field it governs.
10. Case Study: The “Messy Legal Contract” Parser
Structured output is the practical way to convert unstructured PDFs into a SQL database. A legal agent reads a 100-page lease, extracts clauses into a recursive JSON structure, and validates them against the source. Your code, not the model, then writes the validated records with parameterized INSERT statements.
11. JSON Mode vs. Function Calling: Which one to use?
This is a common point of confusion. Both features force the model to output JSON, but they do it in different ways.
11.1 JSON Mode (The “Soft” Constraint)
In “JSON Mode,” you simply tell the model: “You must output valid JSON.” You then provide your schema in the system prompt.
- Pros: Flexible. The model can be slightly more conversational if allowed.
- Cons: The model can still hallucinate a key or misspell a field name. You are responsible for all validation logic in your code.
11.2 Function Calling (The “Hard” Constraint)
In Function Calling, the schema is passed as a Separate Parameter in the API call (the tools or functions array).
- Pros: The model is trained specifically to fill these “Slots.” Many providers also use constrained sampling (see Grammar-Based Sampling in Section 13) to keep outputs valid.
- Cons: Slightly more restrictive. If your schema is too complex, the model might get confused and fail to “call” the function at all.
11.3 Schema-enforced response formats
Several hosted APIs now also accept a JSON Schema for the response itself and enforce it with constrained decoding (OpenAI calls this Structured Outputs with strict: true). You get the guarantees of function calling without pretending the answer is a tool call.
Verdict: Use Function Calling for 3rd-party tool use or database updates. Use a schema-enforced response format for data extraction when your provider offers one, and plain JSON Mode only when it doesn’t (or for loose internal reasoning).
12. Schema Evolution: Handling Versioning in Production
What happens when you need to add a middle_name field to a user profile that’s used by 1,000 agents currently running?
12.1 The “Backwards Compatibility” Rule
Never delete a mandatory field. If you must remove a field, make it optional first, wait for all agents to update, and then remove it 30 days later.
12.2 The “Schema Registry” Pattern
In a large team, store your Pydantic models in a central library.
- Version 1:
class UserV1(BaseModel): name: str - Version 2:
class UserV2(BaseModel): name: str; age: intBy keeping both versions in code, you can use a Transformation Agent to “Up-convert” any older checkpoints (State Management) from V1 to V2 as they are loaded. Tag schema versions (e.g.,invoice_schema_v2), and run a regression suite against every model you support whenever a schema changes (see Section 26).
13. Grammar-Based Sampling: The “Outlines” Revolution
For open-weight models, you can use Grammar-Based Sampling (Outlines, Guidance, XGrammar). This masks the model’s logits at every token, making it impossible for the model to emit JSON that violates the schema. Two gaps remain: output can still be truncated by max_tokens, and a schema-valid value can still be wrong. Syntax becomes guaranteed; correctness does not.
14. Multi-Modal Structured Output
Link AI Vision to UI Graphics. An agent looks at a photo, outputs the [x, y] coordinates of an object in JSON, and your React frontend uses that data to render an interactive label over the image.
15. The “Plan” Schema: Structuring Agent Thought (DAGs)
For complex agents, you don’t just want one step. You want a Plan.
The DAG Schema:
class Step(BaseModel):
id: int
tool: str
args: dict
dependencies: List[int] = []
class Plan(BaseModel):
steps: List[Step]
By structuring the plan as a Directed Acyclic Graph (DAG), your orchestrator can look at the dependencies list and execute steps 1, 3, and 5 in parallel if they don’t depend on each other. When many steps are independent, this cuts wall-clock latency substantially.
16. Data Integrity: The “Double Verification” Pattern
Even with structured output, the LLM can still “Lie” (Hallucinate) within the JSON.
The Workflow:
- Agent A (The Extractor): Takes an image and outputs
{ "price": 99.99 }. - Agent B (The Auditor): Takes the same image and the JSON from Agent A.
- Task: “Verify that the price in the JSON matches the image exactly. If not, output a corrected JSON.”
- Result: This “Cross-Check” catches many extraction errors cheaply. Use a different model (or at least a different prompt) for the auditor, because one model checking its own output tends to repeat the same mistake.
17. Performance Detail: Handling Dates & Decimals
LLMs are notoriously bad at formatting Dates and Decimals inside JSON.
- Fix: Force the agent to output dates as ISO-8601 strings and let your Python code handle the conversion to
datetimeobjects. - Fix: For currency, use a string or integer minor units (cents) in the schema and convert to
Decimalin code. Floats cannot represent most decimal amounts exactly.
18. The “Self-Documenting” Agent
Ask your agent to output a JSON object that describes its own capabilities. This allows your frontend to dynamically render “Help Tooltips” or “Command Menus” without you having to hardcode them.
19. Security: Sanitizing JSON Values (Parameter Injection)
Just because the output is JSON doesn’t mean it’s safe.
The Vulnerability: Imagine your agent outputs a JSON that you then pass directly into a SQL query:
{"user_id": "123; DROP TABLE users;"}
The Fix: Parameterized Queries, Then Strict Validation.
Never build SQL from model output by string concatenation; always pass values as query parameters. On top of that, use UUID or EmailStr types in Pydantic instead of raw strings, so the parser rejects anything that doesn’t follow the exact format before it reaches your database.
20. Future Trends: Native Structural Encoding
We are moving away from “Prompting” for JSON and toward Native Constraints.
20.1 Faster constrained decoding
When the schema fully determines the next tokens (braces, quotes, key names), a constrained decoder can emit them without a model forward pass. SGLang calls this jump-forward decoding. It makes structured output faster, not just safer.
20.2 Multi-Scale Schemas
Instead of one giant 1MB schema, agents will use Adaptive Schemas. The orchestrator detects the task and sends only the specific “Branch” of the schema needed, cutting input tokens.
21. The “Unit Test” for Schemas: How to Test Your Agent
How do you know if your Pydantic model is “Agent-Friendly”?
The Mock Test:
- Generate: Use a strong frontier model to generate 100 “Edge Case” JSONs that follow your schema.
- Validate: Try to parse those JSONs into your Pydantic objects.
- Refine: If the model struggles to generate valid data for a specific field, the field’s
descriptionis likely too vague. Update the description and repeat.
22. FAQ: Advanced Troubleshooting
Q: My agent keeps outputting ‘JSON’ as a string inside the value. Why? A: This is a “Conversational Drift” error. The model is confusing the format of the output with the content.
- Fix: Add a negative constraint: “Do not include the word ‘JSON’ inside the data values unless specifically requested.”
Q: How do I handle circular dependencies in my schema? A: Don’t. JSON cannot represent a cycle (A contains B, B contains A), and naive serializers recurse forever trying. Recursive types (Section 7.3) are fine; recursive instances are not. Instead, use “References” (IDs) and have the agent output a flat list of objects that link to each other.
Q: Is YAML better for small models? A: Sometimes. YAML is more human-readable and takes fewer tokens (no braces). However, because YAML relies on indentation, even a single space error can break the entire file. For reliability, JSON is still the winner.
Q: Can I use structured output to generate code?
A: Yes. Instead of raw text, have the agent output a JSON object: { "language": "python", "code": "...", "unit_tests": "..." }. This allows you to programmatically isolate the code and run it in a sandbox.
Q: Why does my agent hallucinate keys that aren’t in the schema?
A: This is often caused by “Leakage” from the model’s training data. If the model has seen a thousand “Invoice” schemas on GitHub, it will try to add tax_rate to your schema even if you didn’t ask for it. Force it to stop with extra='forbid' (see the security and strict typing guidance in Section 5).
23. Complex Example: The “E-commerce Support Ticket” Schema
Let’s look at a production-grade schema for a ticket-routing agent.
class Ticket(BaseModel):
thought: str = Field(..., description="Reasoning about the user's intent")
priority: int = Field(1, ge=1, le=5)
category: Literal["Billing", "Technical", "Shipping", "General"]
entities: Dict[str, str] = Field(default_factory=dict, description="Extracted IDs, emails, etc")
next_step: Literal["REPLY", "ESCALATE", "WAIT"] = Field(..., description="Action to take next")
23.1 Why this works
- Reasoning First: The
thoughtkey forces the model to categorize correctly. - Range Constraints:
ge=1, le=5prevents the model from outputtingpriority: 99. - Strict Categories:
Literalensures the database doesn’t crash on a “Billing support” category (or an unknown next step) it doesn’t recognize.
24. The Future: “Schema-Driven” Small Language Models (SLMs)
Small models in the 1.5B to 8B range are increasingly fine-tuned specifically on structured output and function calling.
- The Result: On narrow extraction tasks with a stable schema, a fine-tuned small model can often match a frontier model at a small fraction of the cost.
- The Strategy: Start with a big model to “Design the Schema,” then try to “Downgrade” to a smaller model once the schema is stable. Keep the small model only if your evals agree.
25. Handling Non-Latin Characters and Localization in JSON
LLMs can sometimes struggle with JSON formatting when the content is in Chinese, Arabic, or Emoji.
- The Problem: Unicode characters can take multiple tokens, sometimes “confusing” the model’s bracket-matching logic.
- The Fix: Use
ensure_ascii=Falsewhen testing your local parsers, and ensure your system prompt explicitly allows UTF-8 in string values.
26. Benchmarking Model Accuracy for JSON
Not all models are created equal for structured data, and the ranking changes with every release. Public leaderboards such as the Berkeley Function Calling Leaderboard compare tool-call accuracy across models, but your own schema is the benchmark that matters:
- Collect 100 to 200 real inputs, including messy and adversarial ones.
- Run each candidate model with the same schema and prompt.
- Measure parse rate, schema-validation rate, and field-level accuracy against hand-checked answers.
- Re-run the suite whenever you change model, schema or prompt.
- Pro Tip: If your agent is failing to output JSON, it’s often more effective to Change the Model than to write a 10-page prompt.
27. JSON vs. Python Code Generation: When to Use Which?
Sometimes, JSON isn’t enough. If you need the agent to perform a complex calculation (e.g., “Calculate the mortgage interest over 30 years with a variable rate”), a JSON object with a result field will likely be wrong.
- The Python Pattern: Instead of asking for JSON, ask the agent to output a Python Script.
- The Workflow:
- Agent writes a Python function.
- The orchestrator runs the code in a Secure Sandbox.
- The result of the code is the “Answer.”
- Verdict: Use JSON for data state and tool parameters. Use Code Generation for math, logic, and data transformation.
28. The “Self-Correction” Loop in Detail
Your first while loop should be a JSON Recovery Loop.
from pydantic import ValidationError
def generate_validated(llm, prompt: str, schema, max_retries: int = 3):
for _ in range(max_retries):
raw_output = llm.generate(prompt)
try:
return schema.model_validate_json(raw_output) # Success!
except ValidationError as e:
# Pass the SPECIFIC pydantic error back to the model
prompt += f"\nError in your last JSON: {e}. Please correct it."
raise RuntimeError(f"No valid output after {max_retries} attempts")
This simple loop fixes most formatting and type errors on the first or second retry, and it fails loudly instead of returning None when it can’t. By providing the model with the exact line and type of the error, you are giving it the “Map” it needs to fix itself.
29. Monitoring “Schema Drift”: The Silent Failure
Sometimes, an LLM provider updates their model and it starts adding extra whitespace or different escaping characters to its JSON.
The Fix: The “Consistency” Dashboard. Track the “Parsing Failure Rate” in your observability tool. If the rate jumps from 0.1% to 2% on a Tuesday morning, you know that the model provider has changed something behind the scenes, and you need to update your Retry Logic or your Validation Schema.
30. Key takeaways and roadmap
Structured output is the “Final Frontier” of agentic reliability.
Step 1: The Scraper
Learn to use Pydantic to extract data from messy text. This is the “Hello World” of structured output.
Step 2: The Action-Taker
Connect your Pydantic schemas to actual Python functions. When the agent outputs a ChargeCard object, the money actually moves. This requires High-Stakes Validation.
Step 3: The Architect
Design a recursive, self-healing system where agents can update their own schemas and communicate via complex DAGs.
Final Project Idea: build a “News Investigator.”
- Input: A broad topic (e.g., “AI Regulation”).
- Agent: Searches the web, parses 10 articles into a structured
ResearchNodeschema. - Orchestrator: Validates the nodes, identifies missing info, and sends a “Delta Schema” back to the agent to fill in the gaps.
- Output: A validated, structured knowledge graph in which every node cites its source article.
Further reading: With structured outputs in place, your agents can now interact with the web reliably. Continue with Web Browsing Agents.
FAQ
What is structured output in AI agents?
Structured output forces an LLM to produce machine-parseable data (typically JSON) instead of free-form text. This is done through JSON mode, function calling, or grammar-based sampling. Combined with Pydantic validation, it ensures agent outputs conform to exact schemas your code can process without brittle regex parsing.
What is the difference between JSON mode and function calling?
JSON mode is a soft constraint where you tell the model to output valid JSON and provide your schema in the system prompt. Function calling is a hard constraint where the schema is passed as a separate API parameter, and the model is specifically trained to fill those slots. Use function calling for tool use and database updates; use JSON mode for internal reasoning and flexible extraction.
How do you fix broken JSON output from an LLM?
Use a self-correction loop: parse the output with Pydantic, and if validation fails, inject the specific error message back into the prompt and retry up to 3 times. For truncated JSON (token overflow), use partial parsing libraries like partialjson. Grammar-based sampling (Outlines, or a hosted API’s schema-enforced mode) removes invalid JSON except for truncation.
Why should you put a thought_process field first in your JSON schema?
LLMs generate tokens sequentially. By making thought_process the first key, you force the model to reason through the problem before producing the data fields. This preserves chain-of-thought benefits, which matters because studies show strict format constraints can lower reasoning accuracy.