DEV Community

Saqueib Ansari
Saqueib Ansari

Posted on • Originally published at qcode.in

Build Your First Laravel AI Agent

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
Enter fullscreen mode Exit fullscreen mode

Publish the configuration:

php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Run migrations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Add your API key to .env:

OPENAI_API_KEY=sk-...
Enter fullscreen mode Exit fullscreen mode

Creating Your First Agent

Use the Artisan command:

php artisan make:agent ProductAnalyzer
Enter fullscreen mode Exit fullscreen mode

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.';
    }
}
Enter fullscreen mode Exit fullscreen mode

Adding Tools

Tools let your agent call code:

php artisan make:tool FetchProductData
Enter fullscreen mode Exit fullscreen mode

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(),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Add the tool to your agent:

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

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
Enter fullscreen mode Exit fullscreen mode

The agent automatically:

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

Structured Output

Get JSON back instead of text:

php artisan make:agent ProductAnalyzer --structured
Enter fullscreen mode Exit fullscreen mode

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(),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Start a conversation:

$response = (new ProductAnalyzer)
    ->forUser($user)
    ->prompt('Tell me about product trends.');

$conversationId = $response->conversationId;
Enter fullscreen mode Exit fullscreen mode

Continue later:

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

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'),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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)