Generating Structured Data
While text generation is useful, many applications need structured, typed data. The AI SDK Core provides built-in support for generating schema-validated structured data through theoutput property on generateText and streamText.
Why Structured Data?
Structured data generation is essential for:- Data extraction: Extract information from unstructured text
- Classification: Categorize content into predefined types
- Synthetic data: Generate test data or examples
- Form filling: Generate structured responses for forms
- API responses: Create typed data for downstream systems
Basic Usage
UseOutput.object() with a schema to generate structured data:
Output Types
The AI SDK supports multiple output formats through theOutput object:
Output.object()
Generate a structured object matching a schema:Output.array()
Generate an array of structured elements:Streaming Arrays
When streaming arrays, useelementStream to receive complete elements as they’re generated:
Output.choice()
Choose from a fixed set of options:Output.json()
Generate arbitrary JSON without schema validation:Output.json() only validates that the response is valid JSON. For type safety, use Output.object() or Output.array().Output.text()
Generate plain text (this is the default when nooutput is specified):
Schema Definitions
The AI SDK supports multiple schema libraries:Zod Schemas
JSON Schema
Property Descriptions
Add descriptions to schema properties to guide the model:- Clarify ambiguous property names
- Specify expected formats
- Provide context for nested structures
Output Name and Description
Provide a name and description for the output to improve generation quality:Streaming Structured Data
Stream structured data as it’s generated usingstreamText:
Partial outputs cannot be validated against the schema since they’re incomplete. Validation happens on the final output.
Combining with Tools
Structured output can be combined with tool calling:Generating structured output counts as a step. Configure
stopWhen to allow enough steps for both tool execution and output generation.Error Handling
WhengenerateText cannot generate valid structured data, it throws NoObjectGeneratedError:
onError callback:
Examples
Data Extraction
Content Classification
Next Steps
Tool Calling
Combine structured output with tools
Prompt Engineering
Tips for better structured data generation
Settings
Configure generation parameters