Skip to main content
Structured output constrains the LLM to return JSON matching your defined schema. Instead of parsing free-form text, you get predictable data structures that integrate seamlessly with your application.

Quick Start

Define a DataModel and use it as your response schema:

Using with Claude

Structured output works seamlessly with Claude models:

Setting Up Schemas

Using a DataModel Class

The recommended approach for type-safe responses:

Using an Array Schema

For simple cases or dynamic schemas:

Using the structuredOutput() Method

For dynamic schemas or complex logic, override the structuredOutput() method:
When you override structuredOutput(), also override getResponseSchemaClass() to enable automatic DataModel reconstruction. Or skip if you want response returned as array.

Runtime Schema

Set the schema at runtime using the fluent API:

DataModel Basics

DataModels are PHP classes that define your expected response structure.

Property Types

The #[Desc] Attribute

Add descriptions to guide the LLM on what each field should contain:
Descriptive #[Desc] attributes significantly improve the quality and accuracy of extracted data.

Optional Properties

Use nullable types or default values:
Use #[ExcludeFromSchema] to exclude properties from the schema passed to the LLM. These properties won’t be affected by the AI response β€” they remain completely controlled by you with their default values and defined methods.

Advanced DataModels

DataModels support powerful features for complex data structures:
  • Nested DataModels β€” Embed DataModels within other DataModels for hierarchical data
  • DataModelArray β€” Type-safe collections of DataModels
  • Polymorphic Collections β€” Collections containing different DataModel types with discriminators

DataModels In-Depth

Learn about nested structures, collections, polymorphic arrays, and advanced DataModel patterns.

Real-World Example

A complete example analyzing product reviews:
App/DataModels/ReviewSentiment.php
App/DataModels/ReviewSentimentArray.php
App/DataModels/ReviewAnalysis.php
App/AiAgents/ReviewAnalyzerAgent.php

Best Practices

Use DataModels for reusable, type-safe schemas with IDE autocompletion.
Add descriptive #[Desc] attributes to guide the LLM.
Use DataModelArray instead of raw arrays for typed collections.
Keep DataModels focused β€” split complex structures into nested models.
Avoid deeply nested schemas (4+ levels) as they can reduce response accuracy.
Always include critical fields in required β€” only omit truly optional properties.

Next Steps

Streaming

Stream responses in real-time.

Tools

Extend agents with custom tools.