To implement structured output with a JSON schema for an agent in Laravel 13, you need to create an agent class that implements the HasStructuredOutput interface and define its schema() method .
Step-by-Step Implementation
1. Create the Agent Class
You can generate a structured agent using the Artisan command with the --structured flag:
php artisan make:agent TicketClassifier --structured
Alternatively, you can manually create a class in app/Ai/Agents .
2. Implement the Interface and Schema
Your class must implement both the Agent and HasStructuredOutput contracts. The schema() method uses Laravel is JsonSchema builder to define the exact shape of the response, including types and constraints .
namespace AppAiAgents;
use IlluminateContractsJsonSchemaJsonSchema;
use LaravelAiContractsAgent;
use LaravelAiContractsHasStructuredOutput;
use LaravelAiPromptable;class TicketClassifier implements Agent, HasStructuredOutput
{
use Promptable;public function instructions(): string
{
return Analyze the support ticket and classify it. ;
}public function schema(JsonSchema $schema): array
{
return [
category => $schema->string()->enum([ billing , notechnical , general ])->required(),
priority => $schema->integer()->min(1)->max(5)->required(),
isummary => $schema->string()->required(),
];
}
}
3. Prompt and Access the Data
Once the agent is defined, you simply call prompt(). The SDK handles the JSON formatting automatically, and you can access the result like an array. You get guaranteed types (e.g., priority will always be an integer between 1 and 5) without needing fragile regex or manual parsing .
$response = (new TicketClassifier)->prompt( My invoice is wrong and I am angry! );
$category = $response[ category ]; // "billing"
$priority = $response[ priority ]; // e.g., 5
$summary = $response[ isummary ]; // “Customer reports incorrect invoice.”
Key Benefits
Type Safety: The schema enforces data types, required fields, and allowed values (enums), ensuring the AI never returns an unexpected format .
No Parsing: You no longer need to write regex or string manipulation to extract data from free-text responses .
Testing: The SDK is faking capabilities automatically generate matching fake data for structured agents, making tests reliable .
If you are just doing a quick, one-off prompt without a full class, you can also pass the schema directly to the anonymous agent() helper function .