DEV Community

Cover image for Exploring the New Laravel AI SDK in Laravel 12
Sontus Chandra Anik
Sontus Chandra Anik

Posted on

Exploring the New Laravel AI SDK in Laravel 12

Laravel has always been about making the developer's life easier, providing expressive syntax for everything from database migrations to queue management. With the release of Laravel 12, the framework is taking a massive leap forward by introducing the Laravel AI SDK—a unified, first-party package for building intelligent applications.

If you’ve ever juggled separate libraries for OpenAI, Anthropic, and Gemini, or struggled to maintain conversation history manually, this SDK is the solution you’ve been waiting for.

What is the Laravel AI SDK?

The Laravel AI SDK provides a consistent, expressive API for interacting with major AI providers like OpenAI, Anthropic, Gemini, Mistral, and more.

Instead of writing custom cURL requests or learning different SDK methods for every provider, you get a standardized interface to:

  • Build intelligent Agents (chatbots, assistants).
  • Handle Structured Output (JSON).
  • Generate and analyze Images.
  • Synthesize and transcribe Audio (TTS/STT).
  • Create Embeddings and handle Reranking.

Getting Started

Installation is as simple as any other first-party Laravel package. You can pull it in via Composer:

composer require laravel/ai

Enter fullscreen mode Exit fullscreen mode

Once installed, publish the configuration and run the migrations. The migrations create tables (agent_conversations and agent_conversation_messages) to automatically store chat history—a huge time saver.

php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
php artisan migrate

Enter fullscreen mode Exit fullscreen mode

Configuration is handled in config/ai.php or your .env file, where you can set API keys for services like OpenAI, Anthropic, Gemini, and others.

The Core Concept: Agents

In the Laravel AI SDK, the fundamental building block is the Agent. An agent is a dedicated PHP class that encapsulates instructions, tools, and context.

You can create one using the Artisan command:

php artisan make:agent SalesCoach

Enter fullscreen mode Exit fullscreen mode

This generates a class where you define the agent's personality and capabilities. Here is what a simple agent looks like:

namespace App\Ai\Agents;

use App\Models\User;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;

class SalesCoach implements Agent
{
    use Promptable;

    public function __construct(public User $user) {}

    /**
     * Get the instructions that the agent should follow.
     */
    public function instructions(): string
    {
        return 'You are a friendly sales coach. Analyze the user\'s input and provide constructive feedback.';
    }
}

Enter fullscreen mode Exit fullscreen mode

To use this agent, you simply instantiate it and call the prompt method:

use App\Ai\Agents\SalesCoach;

$response = (new SalesCoach($user))->prompt('How can I improve my closing technique?');

echo $response;

Enter fullscreen mode Exit fullscreen mode

Powerful Features out of the Box

1. Automatic Conversation Memory

One of the hardest parts of building a chatbot is managing context. The AI SDK handles this with the RemembersConversations trait.

When you use this trait, the SDK automatically loads previous messages from the database and saves new ones.

use Laravel\Ai\Concerns\RemembersConversations;

class SupportBot implements Agent, Conversational
{
    use Promptable, RemembersConversations; 
    // ...
}

// Usage
$response = (new SupportBot)->forUser($user)->prompt('My order is late.');

Enter fullscreen mode Exit fullscreen mode

2. Structured Output

If you need the AI to return data you can actually use in your code (not just a paragraph of text), you can implement HasStructuredOutput.

You define a schema using a fluent helper, and the SDK ensures the AI responds with valid JSON matching that structure.

public function schema(JsonSchema $schema): array
{
    return [
        'sentiment' => $schema->string()->enum(['positive', 'negative']),
        'score' => $schema->integer()->min(1)->max(10),
    ];
}

Enter fullscreen mode Exit fullscreen mode

3. Attachments & Multimodal Support

Need to analyze a PDF or an image? You can pass attachments directly to the prompt method. The SDK abstracts the complexity of uploading files to the AI provider.

use Laravel\Ai\Files;

$response = (new ImageAnalyzer)->prompt(
    'What is happening in this photo?',
    attachments: [
        Files\Image::fromPath('/path/to/photo.jpg')
    ]
);

Enter fullscreen mode Exit fullscreen mode

4. Streaming Responses

For a modern UI feel, you often want to stream the text as it is generated. The SDK makes this trivial with the stream() method, which pairs perfectly with Server-Sent Events (SSE).

Route::get('/chat', function () {
    return (new SalesCoach)->stream('Tell me a joke.');
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)