The release of Laravel 13 in March 2026 brought one of the most highly anticipated additions to the ecosystem: the first-party Laravel AI SDK (laravel/ai). If you are a senior developer who has spent the last few years spinning up disjointed Python microservices or wrestling with unmaintained third-party wrappers to handle LLM interactions, this update changes everything.
While the official documentation is still catching up to the sheer scope of this release, this complete laravel ai sdk tutorial will bridge the gap. We will dive deep into the architecture, practical implementation, and advanced features of the SDK so you can start building AI-native applications directly within your Laravel monolith.
Why the Laravel AI SDK Changes the Game
Before we look at the code, it is crucial to understand the philosophy behind this laravel ai package. Taylor Otwell and the team designed the SDK around strict provider agnosticism.
You no longer need to write provider-specific API calls. The SDK offers a unified interface for OpenAI, Anthropic, Gemini, DeepSeek, Ollama, and more. Switching from GPT-4o to Claude 3.5 Sonnet is now as simple as changing an environment variable. Furthermore, it natively handles text, agents, vector searches, and multimodal generation (images, audio) using the expressive Laravel syntax you already know.
Among all the laravel 13 features 2026 introduced, this is the one that will most significantly impact day-to-day enterprise development.
Installation and Configuration
To get started with the laravel 13 AI SDK, install the package via Composer:
composer require laravel/ai
Next, publish the configuration file and database migrations (for conversational memory and vector storage):
php artisan ai:install
php artisan migrate
Open config/ai.php. Here, you can define your default providers, configure custom base URLs (essential if you are routing through enterprise gateways like Azure or LiteLLM), and set up automatic failover mechanisms.
// config/ai.php
'default' => env('AI_PROVIDER', 'openai'),
'providers' => [
'openai' => [
'driver' => 'openai',
'key' => env('OPENAI_API_KEY'),
'fallback' => 'anthropic', // Automatic failover if OpenAI is down
],
'anthropic' => [
'driver' => 'anthropic',
'key' => env('ANTHROPIC_API_KEY'),
],
],
Core Concept 1: The Agent Architecture
In Laravel 13, AI interactions are encapsulated within “Agents.” Think of an Agent as a controller for your LLM logic. It holds the system prompts, memory configurations, available tools, and expected output schemas.
You can generate a new agent using Artisan:
php artisan make:agent SupportAssistant
This generates a dedicated PHP class in the app/Ai/Agents directory. Let’s build a practical example: a support agent that analyzes customer transcripts.
namespace App\\Ai\\Agents;
use Laravel\\Ai\\Agent;
use Laravel\\Ai\\Contracts\\Promptable;
class SupportAssistant extends Agent implements Promptable
{
/**
* Define the system instructions for this agent.
*/
public function instructions(): string
{
return 'You are an expert customer support analyst. Analyze the provided text and extract key frustrations.';
}
}
Calling this agent in your application is fluent and straightforward:
use App\\Ai\\Agents\\SupportAssistant;
$transcript = "I've been trying to reset my password for three days and the email never arrives!";
$response = SupportAssistant::make()->prompt($transcript);
echo $response->text();
Implementing Conversational Memory
LLMs are inherently stateless. To build a functional chatbot, you must manage chat history. The Laravel 13 AI SDK automates this entirely via the RemembersConversations trait.
use Laravel\\Ai\\Traits\\RemembersConversations;
class SupportAssistant extends Agent implements Promptable
{
use RemembersConversations;
protected int $memoryLimit = 10; // Retain the last 10 messages
}
When you use this trait, Laravel automatically persists the conversation to your database (using the published ai_messages table) and seamlessly injects the context window into the payload before making the API request.
Core Concept 2: Tools and Structured Output
Enterprise applications rarely rely on raw text generation alone. You need the AI to interact with your system and return predictable data structures.
Function Calling (Tools)
You can bind custom PHP classes as tools that the LLM can execute mid-thought.
namespace App\\Ai\\Tools;
class CheckOrderSetup
{
public string $description = 'Check the shipping status of an order ID.';
public function handle(string $orderId): string
{
$status = \\App\\Models\\Order::find($orderId)->status;
return "The status for order {$orderId} is {$status}.";
}
}
Attach it to your agent:
class SupportAssistant extends Agent implements HasTools
{
public function tools(): array
{
return [
new CheckOrderSetup(),
];
}
}
The SDK handles the complex handshake: the LLM requests the tool, Laravel executes the PHP method, and Laravel feeds the result back to the LLM automatically.
Structured Output
Stop parsing markdown blocks to find JSON. Use the HasStructuredOutput interface to enforce strict schema adherence.
use Laravel\\Ai\\Contracts\\HasStructuredOutput;
class SentimentAnalyzer extends Agent implements HasStructuredOutput
{
public function schema(): array
{
return [
'sentiment' => 'string (positive, negative, neutral)',
'confidence_score' => 'float',
'requires_human' => 'boolean',
];
}
}
When you call $response->json(), you are guaranteed an associative array matching your exact schema.
Core Concept 3: Native Vector & Semantic Search
Building Retrieval-Augmented Generation (RAG) pipelines previously meant managing Pinecone, Qdrant, or Weaviate. Laravel 13 integrates vector math directly into the framework, heavily leveraging PostgreSQL’s pgvector.
Generating Embeddings
Convert strings into vector embeddings using Laravel’s fluent string helpers:
$text = 'The Laravel 13 AI SDK natively supports embeddings.';
$embeddings = Str::of($text)->toEmbeddings();
Semantic Query Builder
You can now perform semantic similarity searches directly alongside your traditional Eloquent queries.
use Illuminate\\Support\\Facades\\DB;
$relevantDocs = DB::table('knowledge_base')
->whereVectorSimilarTo('embedding_column', 'How do I reset my password?')
->limit(5)
->get();
Hybrid Reranking
For optimal search results, the SDK allows you to combine traditional full-text search with AI-powered reranking models (like Cohere). Fetch a broad set of results via full-text, then let the AI rank the top 10 based on deep semantic meaning:
$articles = Article::query()
->whereFullText('content', request('query'))
->limit(50)
->get()
->rerank('content', request('query'), limit: 10);
Core Concept 4: Multimodal Capabilities
The laravel 13 AI SDK extends far beyond text. It provides a beautiful API for interacting with image and audio models, seamlessly integrated with Laravel’s Storage subsystem.
Image Generation
Generate images using DALL-E 3 or Gemini Pro Vision and store them instantly:
use Laravel\\Ai\\Facades\\Image;
$image = Image::of('A minimalist workspace with a laptop displaying Laravel code.')
->model('dall-e-3')
->generate();
// Save directly to your S3 bucket or local disk
Storage::disk('s3')->put('workspaces/img-1.png', $image->stream());
Audio Transcription (Speech-to-Text)
Process uploaded audio files to extract text, perfect for accessibility features or meeting summaries:
use Laravel\\Ai\\Facades\\Audio;
$transcript = Audio::transcribe(
request()->file('meeting_recording')->path()
);
echo $transcript->text();
Core Concept 5: Multi-Agent Workflows & Streaming
Advanced AI applications often require multiple specialized models working in tandem. Laravel 13 natively supports standard multi-agent patterns out of the box.
Parallel Execution
Need to run sentiment analysis, summarization, and entity extraction simultaneously? Use Laravel’s Concurrency facade with the AI SDK:
use Illuminate\\Support\\Facades\\Concurrency;
[$sentiment, $summary, $entities] = Concurrency::run([
fn () => SentimentAgent::make()->prompt($text),
fn () => SummaryAgent::make()->prompt($text),
fn () => EntityAgent::make()->prompt($text),
]);
Streaming Responses
To prevent users from staring at a loading spinner during long inference times, you can stream responses directly to your frontend:
return SupportAssistant::make()->stream('Analyze this report...')
->then(function (StreamedAgentResponse $response) {
// This closure fires when the stream completes
// Ideal for logging total token usage to the database
Log::info('Tokens used: ' . $response->tokenUsage()->total());
});
Core Concept 6: Testing with FakeAi
Historically, testing AI integrations was a nightmare involving mocked HTTP clients, unpredictable assertions, and expensive API bills. Laravel 13 solves this gracefully with the FakeAi facade.
You can completely isolate your test suite from external AI providers while verifying that your application’s logic is sound.
public function test_support_agent_is_called_with_correct_data()
{
FakeAi::shouldFake();
// Trigger the job or controller that runs the AI logic
$this->post('/api/analyze-ticket', [
'transcript' => 'My server is down.'
]);
// Assert the agent was utilized
FakeAi::assertAgentPrompted(SupportAssistant::class);
// You can also assert specific tools were called
FakeAi::assertToolCalled(CheckOrderSetup::class);
}
Conclusion: Future is AI-Native
The laravel 13 AI SDK is a massive leap forward. By standardizing interactions, abstracting vector math into Eloquent, and providing first-class testing tools, Laravel has transformed from a traditional web framework into a robust, AI-native ecosystem.
You no longer need to maintain disparate technology stacks to build highly intelligent applications. Everything you need to orchestrate complex RAG pipelines and multi-agent systems is now available right at your fingertips in PHP.
To learn more about optimizing your entire workflow with these new features, check out our broader analysis of Laravel 13 updates.
Ready to Code Smarter with Laravel?
Meet LaraCopilot — your AI full-stack assistant built for Laravel developers.
Skip the boilerplate, build faster, and focus on what matters: problem solving.
Ready to accelerate your Laravel AI development?
Stop wrestling with boilerplate and start shipping intelligent features faster. Try LaraCopilot Free today and seamlessly integrate advanced AI coding assistance tailored specifically for the Laravel ecosystem.