Getting Started with Laravel AI SDK: Build Your First Agent

Learn how to use the new Laravel AI SDK to build intelligent agents. A practical guide with a real "StalkTechie" example for content summarization.

S

StalkTechie

Author

February 16, 2026
70 views

Build Your First AI Agent with Laravel's New AI SDK

Laravel 12 introduced a powerful AI SDK, bringing the magic of large language models directly into your PHP application. In this guide, we'll build a simple but useful agent for StalkTechie that summarizes our latest articles. No AI expertise required!

1. Installation: It's Just Composer

Installing the AI SDK is as straightforward as any other Laravel package. Open your terminal and run these commands in your Laravel project.

composer require laravel/ai

php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"

php artisan migrate

The migration creates two tables: agent_conversations and agent_conversation_messages. We'll use them later for memory.

Configure Your .env

Add your preferred AI provider's API key. Let's use OpenAI for this example.

OPENAI_API_KEY=your-openai-api-key-here

2. Your First Agent: A Simple Summarizer

Laravel provides an artisan command to scaffold a new agent. Think of an agent as a class that holds instructions and tools for a specific task.

php artisan make:agent ArticleSummarizer

This creates app/Ai/Agents/ArticleSummarizer.php. Let's edit it.

<?php

namespace App\Ai\Agents;

use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;

class ArticleSummarizer implements Agent
{
    use Promptable;

    public function instructions(): string
    {
        return 'You are a helpful assistant that summarizes technical articles. Keep summaries concise, under 100 words, and highlight the key takeaway.';
    }
}

That's it! Our agent now has a core instruction. Let's use it in a route.

// routes/web.php
use App\Ai\Agents\ArticleSummarizer;

Route::get('/summarize', function () {
    $articleText = "Laravel 12's new AI SDK allows developers to integrate large language models... (your full article text here)";

    $agent = new ArticleSummarizer();
    $response = $agent->prompt("Please summarize this article: {$articleText}");

    return "Summary: " . $response;
});

Visit the route, and you'll see an AI-generated summary of your article. This is the core of interacting with an AI from Laravel.

3. Getting Structured Output (JSON)

Often, you don't just want plain text; you want data you can use in your app. The SDK makes this easy with the HasStructuredOutput interface. Let's modify our summarizer to return a structured response.

<?php

namespace App\Ai\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;

class ArticleSummarizer implements Agent, HasStructuredOutput
{
    use Promptable;

    public function instructions(): string
    {
        return 'You are a helpful assistant that summarizes technical articles.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'title' => $schema->string()->required(),
            'summary' => $schema->string()->required(),
            'estimated_read_time_minutes' => $schema->integer()->min(1)->max(20)->required(),
        ];
    }
}

Now, when we prompt, we can access the result as an array.

Route::get('/summarize-structured', function () {
    $articleText = "Laravel 12's new AI SDK allows developers...";

    $agent = new ArticleSummarizer();
    $response = $agent->prompt("Summarize this article: {$articleText}");

    return [
        'title' => \$response['title'],
        'summary' => \$response['summary'],
        'read_time' => \$response['estimated_read_time_minutes'],
    ];
});

4. Real Example: StalkTechie Content Assistant

Let's build something more practical for StalkTechie. Imagine we want an agent that analyzes our blog posts and suggests social media snippets. We'll also use the RemembersConversations trait so the agent can remember past suggestions.

<?php

namespace App\Ai\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Concerns\RemembersConversations;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;

class StalkTechieSocialAgent implements Agent, Conversational, HasStructuredOutput
{
    use Promptable, RemembersConversations;

    public function instructions(): string
    {
        return 'You are a social media expert for a tech blog called "StalkTechie". You suggest engaging snippets for Twitter, LinkedIn, and Instagram based on the provided article content. Match the tone to each platform.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'twitter_post' => $schema->string()->required(),
            'linkedin_post' => $schema->string()->required(),
            'instagram_caption' => $schema->string()->required(),
            'hashtags' => $schema->array(
                items: $schema->string()
            )->required(),
        ];
    }
}

Now, in our controller, we can use it. Because it implements Conversational and uses RemembersConversations, we can track conversations per user.

Route::post('/generate-social-content', function (Request $request) {
    $user = auth()->user();

    $agent = (new StalkTechieSocialAgent())->forUser($user);

    $response = $agent->prompt(
        "Create social media content for this article: " . $request->article_content
    );

    // You can store the conversation ID to continue the thread later.
    return response()->json([
        'conversation_id' => $response->conversationId,
        'suggestions' => [
            'twitter' => $response['twitter_post'],
            'linkedin' => $response['linkedin_post'],
            'instagram' => $response['instagram_caption'],
            'hashtags' => $response['hashtags'],
        ]
    ]);
});

This agent can now be used by the StalkTechie content team to quickly generate platform-specific posts. The conversation memory allows them to refine the output by saying "make the Twitter post shorter" in a follow-up call using the continue() method.

5. Bonus: Giving Your Agent a Tool

Agents become truly powerful when they can interact with the outside world. Let's create a simple tool that allows our agent to "fetch" the latest StalkTechie article URL. We'll use a mock for simplicity.

First, create the tool:

php artisan make:tool FetchLatestArticle

Now, define what the tool does in app/Ai/Tools/FetchLatestArticle.php:

<?php

namespace App\Ai\Tools;

use Laravel\Ai\Tools\Tool as BaseTool;

class FetchLatestArticle extends BaseTool
{
    public function name(): string
    {
        return 'fetch_latest_article';
    }

    public function description(): string
    {
        return 'Fetch the URL and title of the most recent article from the StalkTechie blog.';
    }

    public function handle(): string
    {
        // In a real app, you'd query your database or RSS feed.
        return json_encode([
            'title' => 'Getting Started with Laravel AI SDK',
            'url' => 'https://stalktechie.com/blog/laravel-ai-sdk-guide',
            'published_at' => now()->toDateString(),
        ]);
    }
}

Finally, add the tool to your agent.

// Inside StalkTechieSocialAgent, add the HasTools interface
use Laravel\Ai\Contracts\HasTools;
use App\Ai\Tools\FetchLatestArticle;

class StalkTechieSocialAgent implements Agent, Conversational, HasStructuredOutput, HasTools
{
    // ... other methods

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

Now, if you prompt the agent with "Suggest social posts for the latest article", it has the ability to call the fetch_latest_article tool to get the necessary information before generating the posts. The SDK handles all the heavy lifting of function-calling with the AI provider.

Conclusion: What We Built

  • A reusable AI agent with clear instructions.
  • Structured output to get usable JSON data.
  • Conversation memory for a multi-turn chat experience.
  • A custom tool for the agent to fetch external data.

The Laravel AI SDK abstracts away the complexities of different AI providers. Whether you use OpenAI, Anthropic, or Gemini, your agent code remains the same. This is a game-changer for adding AI features to Laravel applications.

For more advanced features like streaming responses, file attachments, and queueing, be sure to check out the official documentation.

Share this post:

Related Articles

Discussion

0 comments

Please log in to join the discussion.

Login to Comment