Commit

ee100c7

A small Laravel AI SDK pattern worth sharing. đź‘‹ **Building safer AI agents with structured outputs in Laravel** When building AI-powered features, one common challenge is getting predictable responses from an LLM. For example, imagine building a support-ticket classification system. You don't just need a paragraph explaining the ticket. Your application needs predictable fields such as category, priority, and summary. Laravel's AI SDK provides structured output through the HasStructuredOutput contract. Here's a simple example:
php
<?php

namespace App\Ai\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;

class TicketTriage implements Agent, HasStructuredOutput
{
    use Promptable;

    public function instructions(): string
    {
        return 'Classify support tickets by category and priority.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'category' => $schema->string()
                ->enum(['billing', 'technical', 'account'])
                ->required(),

            'priority' => $schema->string()
                ->enum(['low', 'normal', 'urgent'])
                ->required(),

            'summary' => $schema->string()->required(),
        ];
    }
}
You can then prompt the agent:
php
$response = (new TicketTriage)
    ->prompt($ticket->body);

$category = $response['category'];
$priority = $response['priority'];
**Why does this matter?** 1. Predictable responses: Your application receives defined fields instead of having to parse arbitrary paragraphs. 2. Better integration: Structured data is easier to pass into services, database operations, and API responses. 3. Clearer responsibilities: The agent handles classification, while your application remains responsible for business rules and validation. One additional security consideration: structured output does not replace authorization or business validation. For actions that can modify or delete data, Laravel's AI SDK also supports human tool approval through the Approvable contract and InteractsWithApprovals trait. I think separating AI reasoning, structured output, and application-side actions is a useful design pattern when building reliable AI features with PHP. Official documentation: https://laravel.com/php/docs/ai-sdk Hope this is helpful to fellow Laravel developers! 🚀
LaravelLaravel AI SDK | Laravel PHP 13.xLaravel is a framework for building modern web apps and AI agents. Expressive syntax, built-in tools, and everything you need to ship fast.

commit ee100c7