Structured Output
Get type-safe, validated responses from AI using BoxLang classes, struct templates, or JSON schemas. Eliminate manual parsing with automatic data extraction.
Get type-safe, validated responses from AI providers by defining expected output schemas. The module automatically converts AI responses into properly typed objects, eliminating manual parsing and validation.
📋 Table of Contents
Why Use Structured Output?
🔄 Data Extraction Flow
Benefits:
Type Safety: Get validated objects with proper types, not generic structs
Automatic Validation: Schema constraints ensure correct data structure
Better Reliability: Reduces hallucinations by strictly constraining format
IDE Support: Full autocomplete and type checking with classes
No Manual Parsing: Direct access to typed properties and methods
Quick Start
📊 Class vs Struct Template
Recommendation: Use classes for production code, struct templates for quick prototypes.
Using a Class
Using a Struct Template
For quick prototyping without defining classes:
Extracting Arrays
Extract multiple items of the same type:
Multiple Schemas
Extract different entity types from the same text:
With Conversations
Use structured output in multi-turn conversations:
With Tools
Combine structured output with function calling:
Manual Population with aiPopulate()
Convert JSON or structs into typed objects without making AI calls:
Perfect for:
Testing with mock data
Using cached AI responses
Converting existing JSON to typed objects
Validating data structures
Comparison: Structured Output vs JSON Return Format
Type Safety
✅ Full type safety
❌ Generic structs
Validation
✅ Schema validation
⚠️ Manual validation
IDE Support
✅ Autocomplete
❌ No type info
Reliability
✅ Strict schema
⚠️ May return invalid JSON
Best For
Production code
Quick prototypes
Use Structured Output when:
Building production applications
Type safety is important
Working with complex nested data
Consistency is critical
Use JSON Return Format when:
Quick prototypes or scripts
Dynamic/unknown data structures
Flexibility is more important than type safety
Provider Support
All providers support structured output:
OpenAI
✅ Native
Best support with strict validation
Claude
✅ JSON Mode
Excellent results
Gemini
✅ JSON Mode
Good support
Ollama
✅ JSON Mode
Model dependent
Others
✅ JSON Mode
Schema-guided responses
Note: OpenAI provides native structured output with strict schema validation. Other providers use JSON mode with schema constraints, which provides excellent results.
Best Practices
1. Keep Schemas Simple
2. Use Descriptive Property Names
3. Handle Missing Data
4. Cache Pipelines with Structured Output
Error Handling
Next Steps
Advanced Chatting - More examples with tools, streaming, and conversations
Pipeline Structured Output - Use in composable workflows
Utility Functions - Learn about
aiPopulate()Examples - Complete working examples
Last updated