Build Your First Laravel AI Agent

under

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 to create conversation tables:

php artisan migrate

Add your AI provider API key to .env:

OPENAI_API_KEY=sk-...

That’s it. You’re ready to build.

Creating Your First Agent

Use the Artisan command to scaffold an agent:

php artisan make:agent ProductAnalyzer

This creates app/Ai/Agents/ProductAnalyzer.php. Open it:

<?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.';
    }
}

That’s your agent. Now let’s make it useful.

Adding Tools to Your Agent

Tools let your agent call code. Create a tool:

php artisan make:tool FetchProductData

Inside 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;
use Stringable;

class FetchProductData implements Tool
{
    public function description(): Stringable|string
    {
        return 'Fetch product details by product ID.';
    }

    public function handle(Request $request): Stringable|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(),
        ];
    }
}

The schema tells the AI what parameters it needs. Now add the tool to your agent:

use App\Ai\Tools\FetchProductData;

public function tools(): iterable
{
    return [
        new FetchProductData,
    ];
}

Now your agent can fetch product data when analyzing.

Using Your Agent

From any controller or command:

use App\Ai\Agents\ProductAnalyzer;

$response = (new ProductAnalyzer)->prompt(
    'Analyze product ID 42 for market fit.'
);

echo $response; // AI's analysis

The agent automatically:

  1. Receives your prompt
  2. Decides if it needs to call FetchProductData
  3. Calls your tool with the product ID
  4. Uses the returned data in its analysis
  5. Sends you a thoughtful response

Structured Output

Sometimes you want JSON back, not text. Create an agent with structured output:

php artisan make:agent ProductAnalyzer --structured

Define a schema:

use Illuminate\Contracts\JsonSchema\JsonSchema;
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(),
        ];
    }
}

Now 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 or database storage.

Conversation Memory

Keep multi-turn conversations going:

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 the conversation later:

$response = (new ProductAnalyzer)
    ->continue($conversationId, as: $user)
    ->prompt('What about pricing strategies?');

The agent remembers everything from before.

Real-World Pattern: RAG Agent

Retrieval-Augmented Generation (RAG) combines your data with AI. Use the SimilaritySearch tool:

use Laravel\Ai\Tools\SimilaritySearch;
use App\Models\Document;

class KnowledgeBaseAgent implements Agent, HasTools
{
    public function tools(): iterable
    {
        return [
            SimilaritySearch::usingModel(
                Document::class,
                'embedding'
            )->withDescription('Search your knowledge base'),
        ];
    }
}

Your agent can now search your database for relevant documents before answering questions. This grounds AI responses in your actual data.

Advanced: Custom Middleware

Want to log every prompt? Use middleware:

php artisan make:agent-middleware LogPrompts
<?php

namespace App\Ai\Middleware;

use Closure;
use Laravel\Ai\Prompts\AgentPrompt;
use Illuminate\Support\Facades\Log;

class LogPrompts
{
    public function handle(AgentPrompt $prompt, Closure $next)
    {
        Log::info('Agent prompt', ['text' => $prompt->prompt]);

        return $next($prompt);
    }
}

Add to your agent:

use Laravel\Ai\Contracts\HasMiddleware;

class ProductAnalyzer implements Agent, HasMiddleware
{
    public function middleware(): array
    {
        return [new LogPrompts];
    }
}

Every prompt gets logged automatically.

Testing Agents

In tests, fake the response:

use App\Ai\Agents\ProductAnalyzer;

ProductAnalyzer::fake('This is a test response');

$response = (new ProductAnalyzer)->prompt('Test prompt');

ProductAnalyzer::assertPrompted('Test prompt');

No API calls. Fast tests.

Key Takeaways

  • Laravel AI Agents are PHP classes that wrap AI capabilities—instructions, tools, and context
  • Tools let agents call your code (database queries, APIs, custom logic)
  • Structured output returns JSON instead of text—perfect for APIs
  • RemembersConversations trait stores conversation history automatically
  • RAG patterns let agents search your data before responding
  • Testing is simple—fake responses, assert calls, no API usage
  • Reuse everywhere—build once, use in controllers, commands, jobs, queues

Conclusion

Laravel AI Agents solve the 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.