Guides
Structured Outputs
Learn how to use structured outputs with JSON schema validation for reliable data extraction and API integration.
Structured Outputs
Structured outputs allow you to constrain AI model responses to follow a specific JSON schema, ensuring reliable and predictable data formats. This feature is essential for building robust applications that need to parse and process AI responses programmatically.
Universal Support: All chat models on Tinfoil support structured outputs with JSON schema validation, enabling consistent data extraction across different models.
Benefits
- Guaranteed Format: Responses always match your specified JSON schema
- Type Safety: Enforce specific data types, required fields, and constraints
- Reliable Parsing: No need for complex text parsing or error handling
- API Integration: Perfect for building APIs that need consistent response formats
- Data Extraction: Extract structured information from unstructured text
Basic Example
Here’s how to use structured outputs to extract contact information:
Complex Schema Example
For more complex data structures with nested objects and arrays:
Data Analysis Example
Perfect for analyzing and structuring data from text:
Model Recommendations
Model | Best For | Structured Output Quality |
---|---|---|
Qwen 2.5 72B | Complex schemas, data processing, API responses | Excellent |
Mistral Small 3.1 24B | Simple to moderate schemas, fast responses | Very Good |
DeepSeek R1 70B | Analytical data, research outputs | Very Good |
Llama 3.3 70B | Content analysis, conversational data | Good |
Best Practices
- Define Clear Schemas: Use Zod or JSON Schema to define your data structure precisely
- Use Descriptive Field Names: Choose field names that clearly indicate their purpose
- Handle Nullable Fields: Use
.nullable()
in Zod for optional fields that can be null - Set Appropriate Types: Use specific types (string, number, boolean) rather than generic ones
- Validate Constraints: Add validation rules like
.min()
,.max()
,.email()
where appropriate - Handle Errors: Always wrap JSON parsing in try-catch blocks
- Use Nullish Coalescing: Handle null values gracefully with
??
operator
Error Handling
Use Cases
- API Development: Create consistent API responses
- Data Extraction: Extract structured data from documents
- Form Processing: Parse form submissions and surveys
- Content Analysis: Analyze reviews, feedback, and comments
- Report Generation: Create structured reports from unstructured data
- Database Integration: Generate database-ready records
- Workflow Automation: Structure data for automated processing