AI
Laravel AI SDK for Beginners: Build Your First Agent in Laravel
Install the package, connect a provider, write an agent class, get structured output and test it without spending a rupee on API calls.
If you've added AI to a Laravel app before, you probably wrote a small wrapper around one provider's HTTP API. It worked until you wanted to switch models, add a second provider, or write tests. The Laravel AI SDK solves those problems in a way that feels like the rest of the framework.
It shipped as a stable first-party package alongside Laravel 13 on 17 March 2026, and the documentation also covers Laravel 12. This guide covers the basics you need for a first real feature.
Step 1: Install and configure
composer require laravel/ai
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
php artisan migrate
The migration creates the agent_conversations and agent_conversation_messages tables, which the SDK uses if you want it to remember conversations.
Then add the keys for the providers you plan to use to your .env file:
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
You only need keys for providers you actually call. Default models and other options live in config/ai.php.
Step 2: Create your first agent
An agent is a class that holds the instructions for one job. Generate one with Artisan:
php artisan make:agent SalesCoach
A minimal agent looks like this:
<?php
namespace App\Ai\Agents;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
use Stringable;
class SalesCoach implements Agent
{
use Promptable;
public function instructions(): Stringable|string
{
return 'You are a sales coach. Review call transcripts and give short, practical feedback.';
}
}
Call it from a controller, job or command:
use App\Ai\Agents\SalesCoach;
$response = (new SalesCoach)->prompt('Review this transcript: ...');
return (string) $response;
Casting the response to a string gives you the model's text reply.
Step 3: Pick the provider and model
By default, the agent uses the provider set in your config. You can override it per call:
use Laravel\Ai\Enums\Lab;
$response = (new SalesCoach)->prompt(
'Review this transcript: ...',
provider: Lab::Anthropic,
model: 'your-chosen-model',
timeout: 120,
);
Or set it on the class with attributes, which keeps call sites clean:
use Laravel\Ai\Attributes\Model;
use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Attributes\Timeout;
use Laravel\Ai\Enums\Lab;
#[Provider(Lab::Anthropic)]
#[Model('your-chosen-model')]
#[Timeout(120)]
class SalesCoach implements Agent
{
// ...
}
Model names change often, so check your provider's documentation for current model IDs rather than copying one from a tutorial. Also check the SDK docs for exact namespaces, since a package this young may still move things around.
Step 4: Get structured output
Free-form text is hard to store in a database. If you want fields you can rely on, generate a structured agent:
php artisan make:agent SalesCoach --structured
Then implement HasStructuredOutput and describe the shape you want:
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\HasStructuredOutput;
class SalesCoach implements Agent, HasStructuredOutput
{
use Promptable;
public function instructions(): Stringable|string
{
return 'Score the sales call from 1 to 10 and give one line of feedback.';
}
public function schema(JsonSchema $schema): array
{
return [
'score' => $schema->integer()->required(),
'feedback' => $schema->string()->required(),
];
}
}
The response now works like an array:
$response = (new SalesCoach)->prompt('Transcript: ...');
$score = $response['score'];
$feedback = $response['feedback'];
Step 5: Quick one-off prompts
Not every prompt deserves a class. For small tasks, use the agent() helper:
use function Laravel\Ai\agent;
$summary = agent(
instructions: 'Summarise the text in two sentences.',
)->prompt($longText);
You can pass messages and tools to the helper too. Once a prompt grows or gets reused, move it into a proper agent class so it's easy to find and test.
Step 6: Stream long replies
For chat-style interfaces, waiting for the whole reply feels slow. Agents support streaming:
Route::get('/coach', function () {
return (new SalesCoach)->stream('Review this transcript: ...');
});
The SDK documentation covers how to consume the stream in your frontend and how to hook into it when it finishes.
Step 7: Conversations and tools
Two interfaces add more power once the basics work:
Conversationallets an agent receive earlier messages, so it can hold a conversation. The SDK can store these in the tables created by the migration.HasToolslets an agent call your own PHP code, such as looking up an order or checking stock, when the model decides it needs that data.
Start without them. Add them when a real feature needs memory or live data.
Step 8: Test without calling the API
This is one of the best parts of the SDK. Fake the agent and assert on what was sent:
use App\Ai\Agents\SalesCoach;
it('reviews a transcript', function () {
SalesCoach::fake(['Great call. Ask more open questions.']);
$this->get('/coach')->assertOk();
SalesCoach::assertPrompted(fn ($prompt) => str_contains($prompt->prompt, 'transcript'));
});
Other useful assertions include assertPromptedTimes() and assertNeverPrompted(). To make sure no test accidentally calls a real API, use preventStrayPrompts() on the fake.
Shared hosting notes
The SDK works on ordinary hosting because it makes outgoing HTTPS requests, not long-running processes. Two things are worth watching:
Timeouts. AI calls can take tens of seconds. For anything slow, run the prompt in a queued job instead of during the web request. Our guide to Laravel queues and cron on shared hosting covers how to set that up.
PHP version. Check which PHP version your plan runs and keep it supported. See which PHP version to choose in 2026.
Related reading: How to brief an AI coding agent safely · PHP security updates: what to do
Frequently asked questions
What is the Laravel AI SDK?
It's Laravel's official package, laravel/ai, for working with AI providers like OpenAI, Anthropic and Gemini through one API, with agents, structured output, streaming and testing fakes.
Does the Laravel AI SDK work with Laravel 12?
Yes. The official documentation includes a Laravel 12.x version of the AI SDK page. It launched as stable alongside Laravel 13.
How do I switch AI providers in Laravel?
Pass provider and model when calling prompt(), or set the #[Provider] and #[Model] attributes on the agent class. You also need that provider's API key in .env.
How do I test AI features in Laravel without paying for API calls?
Call YourAgent::fake() with canned responses in your tests, then use assertions like assertPrompted(). Add preventStrayPrompts() to block real calls.
Sources: Laravel AI SDK documentation (laravel.com/docs/12.x/ai-sdk and 13.x); Laravel 13 release coverage (March 2026). Code examples follow the official documentation; check it for current method names and options.
Further reading: Laravel docs: AI SDK · laravel/ai on GitHub
Related
AI
Slopaganda Meaning: Oxford's 2026 Word of the Year and How to Spot It in Your Feed
Slopaganda is low-quality propaganda made with generative AI and spread on social media. Oxford named it the 2026 Word of the Year. Here's the meaning...
AI
Search Console AI Clicks Are Here: How to Read the New Generative AI Data
Search Console AI clicks are finally visible. Google now reports clicks and CTR from AI Overviews, AI Mode and Discover's AI features, plus grouped AI...
AI
Gemini 4 Carbon vs Argon: Which Google Model to Use, and the New API Price from December
Gemini 4 Carbon is now available to developers and Google AI Ultra subscribers. Here's how it compares with Gemini 4 Argon, which plans include each m...
The stream
All storiesNew E-Commerce Rules from 1 January 2027: What Changes for Online Shoppers in India
India's new e-commerce rules take effect on 1 January 2027. Discounts must show the lowest price of the last 30 days, sponsored listings must be labelled, and bundled fees are restricted. Here's what...
Slopaganda Meaning: Oxford's 2026 Word of the Year and How to Spot It in Your Feed
Slopaganda is low-quality propaganda made with generative AI and spread on social media. Oxford named it the 2026 Word of the Year. Here's the meaning, the history and a checklist for spotting it.
Search Console AI Clicks Are Here: How to Read the New Generative AI Data
Search Console AI clicks are finally visible. Google now reports clicks and CTR from AI Overviews, AI Mode and Discover's AI features, plus grouped AI queries with an impression share band. Here's how...
Gemini 4 Carbon vs Argon: Which Google Model to Use, and the New API Price from December
Gemini 4 Carbon is now available to developers and Google AI Ultra subscribers. Here's how it compares with Gemini 4 Argon, which plans include each model, and what the end of introductory API pricing...
AGENTS.md Guide: How to Write Instructions Every AI Coding Agent Can Read
AGENTS.md is a plain Markdown file that tells AI coding agents how to work on your project. Most major agents read it. Here's what to include, a copy-ready template, and how to handle monorepos and ol...