Structured Output
Structured output enables agents to return type-safe, validated data instead of plain text. This is essential for building reliable applications that integrate with your codebase.Why Structured Output?
Benefits:- Type safety - Full TypeScript types inferred from schemas
- Validation - Automatic validation of LLM responses
- Reliability - Guaranteed output format
- Integration - Easy to use in applications
- Error handling - Graceful fallbacks when parsing fails
Basic Usage
From:packages/core/src/agent/agent.test.ts
Generate with Schema
Stream Structured Output
Schema Definition
Simple Schema
Complex Nested Schema
Array Output
Configuration Options
Custom Instructions
Override the default structuring instructions:Error Strategies
Handle parsing failures gracefully:Custom Model
Use a different model for structuring:JSON Prompt Injection
For models without native structured output:Real-World Examples
Data Extraction
Classification
Form Generation
API Response Transformation
Test Case Generation
Combining with Tools
From:packages/core/src/agent/agent.test.ts
Type Inference
Zod schemas provide full TypeScript types:Best Practices
Add descriptions to fields
Add descriptions to fields
Help the LLM understand what each field represents:
Use enums for constrained values
Use enums for constrained values
Ensure valid categories:
Handle optional fields properly
Handle optional fields properly
Use
.optional() or .nullable() for fields that may not exist:Validate ranges and formats
Validate ranges and formats
Add constraints to ensure data quality:
Use error strategies in production
Use error strategies in production
Handle parsing failures gracefully:
Next Steps
Tools
Combine structured output with tools
Memory
Persist structured conversations
Workflows
Use structured output in workflows
API Reference
Complete API documentation