Build Your First Laravel AI Agent
Building AI-powered features shouldn't require complex integrations. Laravel's new AI SDK makes creating intelligent agents simple—even if you're not an AI expert.
An agent is a dedicated PHP class that wraps AI capabilities. Think of it as a specialized assistant—a sales coach, document analyzer, or customer support bot—that you configure once and reuse everywhere.
This guide walks you through building your first Laravel AI Agent from zero to working code.
What is a Laravel AI Agent?
An agent is fundamentally a class that encapsulates three things:
- Instructions: Your system prompt (what the agent should do)
- Tools: Functions the agent can call (like database lookups or API requests)
- Context: Conversation history and structured outputs
Instead of scattering AI logic across your controllers, you isolate it in a reusable class.
Setting Up Laravel AI SDK
First, install the package:
composer require laravel/ai
Publish the configuration:
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
Run migrations:
php artisan migrate
Add your API key to .env:
OPENAI_API_KEY=sk-...
Creating Your First Agent
Use the Artisan command:
php artisan make:agent ProductAnalyzer
This creates app/Ai/Agents/ProductAnalyzer.php:
<?php
namespace App\Ai\Agents;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
use Stringable;
class ProductAnalyzer implements Agent
{
use Promptable;
public function instructions(): Stringable|string
{
return 'You are a product analyst. Analyze product descriptions and return insights about market fit and pricing strategy.';
}
}
Adding Tools
Tools let your agent call code:
php artisan make:tool FetchProductData
In app/Ai/Tools/FetchProductData.php:
<?php
namespace App\Ai\Tools;
use App\Models\Product;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
class FetchProductData implements Tool
{
public function description(): string
{
return 'Fetch product details by product ID.';
}
public function handle(Request $request): string
{
$product = Product::find($request['product_id']);
return json_encode([
'name' => $product->name,
'price' => $product->price,
'category' => $product->category,
'sales_count' => $product->sales_count,
]);
}
public function schema(JsonSchema $schema): array
{
return [
'product_id' => $schema->integer()->required(),
];
}
}
Add the tool to your agent:
public function tools(): iterable
{
return [
new FetchProductData,
];
}
Using Your Agent
From any controller:
use App\Ai\Agents\ProductAnalyzer;
$response = (new ProductAnalyzer)->prompt(
'Analyze product ID 42 for market fit.'
);
echo $response; // AI's analysis
The agent automatically:
- Receives your prompt
- Decides if it needs to call tools
- Calls your tool with parameters
- Uses returned data in its analysis
- Sends you a response
Structured Output
Get JSON back instead of text:
php artisan make:agent ProductAnalyzer --structured
Define a schema:
use Laravel\Ai\Contracts\HasStructuredOutput;
class ProductAnalyzer implements Agent, HasStructuredOutput
{
public function schema(JsonSchema $schema): array
{
return [
'market_fit_score' => $schema->integer()->min(1)->max(10)->required(),
'suggested_price' => $schema->number()->required(),
'target_audience' => $schema->string()->required(),
];
}
}
Responses come back as structured data:
$response = (new ProductAnalyzer)->prompt('Analyze product 42');
echo $response['market_fit_score']; // 8
echo $response['suggested_price']; // 29.99
Perfect for APIs and databases.
Conversation Memory
Keep multi-turn conversations:
use Laravel\Ai\Concerns\RemembersConversations;
use Laravel\Ai\Contracts\Conversational;
class ProductAnalyzer implements Agent, Conversational
{
use Promptable, RemembersConversations;
}
Start a conversation:
$response = (new ProductAnalyzer)
->forUser($user)
->prompt('Tell me about product trends.');
$conversationId = $response->conversationId;
Continue later:
$response = (new ProductAnalyzer)
->continue($conversationId, as: $user)
->prompt('What about pricing strategies?');
Real-World Pattern: RAG Agents
Retrieval-Augmented Generation combines your data with AI:
use Laravel\Ai\Tools\SimilaritySearch;
class KnowledgeBaseAgent implements Agent
{
public function tools(): iterable
{
return [
SimilaritySearch::usingModel(
Document::class,
'embedding'
)->withDescription('Search your knowledge base'),
];
}
}
Your agent searches your database for relevant documents before answering.
Testing Agents
Fake responses in tests:
ProductAnalyzer::fake('This is a test response');
$response = (new ProductAnalyzer)->prompt('Test');
ProductAnalyzer::assertPrompted('Test');
No API calls, fast tests.
Key Takeaways
- Laravel AI Agents wrap instructions, tools, and context
- Tools let agents call your code (databases, APIs, custom logic)
- Structured output returns JSON instead of text
- Conversation memory stores multi-turn history
- RAG patterns ground AI in your actual data
- Testing is simple with fakes and assertions
- Reuse everywhere — controllers, commands, jobs, queues
Conclusion
Laravel AI Agents solve a real problem: most teams don't need generic AI, they need AI that knows their data and can call their tools.
The Laravel AI SDK makes this frictionless. You're not integrating a third-party service—you're extending your application with intelligent capabilities that feel native.
Start with a simple agent. Add tools. Build something useful. Share what you learn.
Read the full guide and code examples on qcode.in
Top comments (0)