Mastodon Skip to main content
Available for Projects

I'm always excited to take on new projects and collaborate with innovative minds.

Laravel

Harnessing Laravel 13’s Official AI SDK for Multi-Model Systems

Laravel 13 is officially here, and with it comes the stable release of the first-party Laravel AI SDK. Here is a production-ready guide to building provider-agnostic, multi-model AI workflows.

Michael K. Laweh
2026-03-12 10:00:00 7 min read
Harnessing Laravel 13’s Official AI SDK for Multi-Model Systems

With the official release of Laravel 13 in March 2026, the Laravel ecosystem took a major leap forward by promoting the Laravel AI SDK to a stable, first-party package. For developers who have spent the last few years stitching together community packages or writing custom API wrappers for OpenAI, Anthropic, or Google Gemini, this is a game-changer.

The Laravel AI SDK provides a clean, provider-agnostic interface that makes swapping LLMs as simple as changing a driver in your config/ai.php.

Here is an engineering guide to setting up the Laravel AI SDK, implementing fallback model routing, and building tool-calling agents for production workloads.


1. Why Provider Agnosticism Matters in 2026

Relying on a single AI provider introduces systemic risks to your application. API rate limits, service degradation, model deprecations, and pricing changes can disrupt operations.

By building your AI integration on top of Laravel's unified SDK, you decouple your application logic from the underlying model provider. If Anthropic experiences an outage, your application can automatically reroute requests to Google Gemini or OpenAI with zero code changes.


2. Installation and Configuration

To begin, install the Laravel AI SDK via Composer:

composer require laravel/ai

After installing, publish the configuration file:

php artisan vendor:publish --tag=ai-config

This generates config/ai.php, which contains your driver configurations. Here is a production-ready setup defining drivers for Anthropic, Gemini, and OpenAI:

return [
    'default' => env('AI_DRIVER', 'openai'),

    'drivers' => [
        'openai' => [
            'driver' => 'openai',
            'key' => env('OPENAI_API_KEY'),
            'model' => 'gpt-4o',
        ],
        'anthropic' => [
            'driver' => 'anthropic',
            'key' => env('ANTHROPIC_API_KEY'),
            'model' => 'claude-3-5-sonnet',
        ],
        'gemini' => [
            'driver' => 'gemini',
            'key' => env('GEMINI_API_KEY'),
            'model' => 'gemini-1.5-pro',
        ],
    ],
];

3. Building a Multi-Model Fallback Service

To implement fallback routing, we can create a service class that intercepts API errors and attempts to run the prompt on a secondary driver. First, define the interface:

namespace App\Services;

interface AiModelServiceInterface
{
    public function generateText(string $prompt, array $options = []): string;
}

Now, implement the service with error handling:

namespace App\Services;

use Laravel\Ai\Facades\Ai;
use Illuminate\Support\Facades\Log;
use Exception;

class AiModelService implements AiModelServiceInterface
{
    protected array $driverChain = ['anthropic', 'openai', 'gemini'];

    public function generateText(string $prompt, array $options = []): string
    {
        foreach ($this->driverChain as $driver) {
            try {
                return Ai::driver($driver)->generate([
                    'prompt' => $prompt,
                    ...$options
                ])->text();
            } catch (Exception $e) {
                Log::warning("AI driver {$driver} failed. Error: {$e->getMessage()}. Swapping to next driver.");
            }
        }

        throw new Exception("All configured AI drivers failed to process the request.");
    }
}

4. Running Agentic Tool-Calling Workflows

One of the most powerful features of the Laravel AI SDK is its native support for tool calling. This allows LLMs to interact directly with your application code, executing database queries, firing webhooks, or fetching external data.

Let’s build a console command where an AI agent acts as a database assistant, running specific tools to retrieve information.

Step 1: Define the Tools

Create a class with methods containing clean PHP docstrings. The AI SDK reads these docstrings to understand what each tool does and what parameters it requires.

namespace App\Ai\Tools;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class DatabaseTools
{
    /**
     * Get the total number of registered users.
     */
    public function getUserCount(): int
    {
        return User::count();
    }

    /**
     * Get the registration count grouped by month.
     *
     * @param int $limit The number of months to retrieve.
     */
    public function getRegistrationTrends(int $limit = 6): array
    {
        return User::select(
            DB::raw("DATE_FORMAT(created_at, '%Y-%m') as month"),
            DB::raw("COUNT(*) as count")
        )
            ->groupBy('month')
            ->orderBy('month', 'desc')
            ->limit($limit)
            ->get()
            ->toArray();
    }
}

Step 2: Bind Tools and Run the Agent

Now, we can call the AI agent and provide our tools. The SDK handles executing the correct method when the LLM decides to trigger it:

use Laravel\Ai\Facades\Ai;
use App\Ai\Tools\DatabaseTools;

$response = Ai::withTools(new DatabaseTools)
    ->generate("Analyze the database and tell me how many users we have and how registrations have trended over the last 3 months.");

echo $response->text();

Behind the scenes, the SDK:

  1. Sends the tools and prompt to the model.
  2. Receives a request from the model to execute getUserCount() and getRegistrationTrends(limit: 3).
  3. Runs the PHP methods, gathers the outputs, and sends them back to the model.
  4. Returns the final natural language summary compiled by the LLM.

Conclusion

The first-party Laravel AI SDK marks a new era for PHP applications. By providing a clean interface for multi-model fallback and native tool execution, it enables developers to build resilient, AI-native software.

If you are looking to integrate intelligent workflows, implement multi-model agent systems, or audit your application architecture for AI capability, I can help you design and build a robust solution.

Get in touch to discuss your next project.

Michael K. Laweh
Michael K. Laweh
Author

Senior IT Consultant & Digital Solutions Architect with 16+ years of engineering experience. Founder of LAWEITECH, builder of ScrybaSMS, Nexus Retail OS, and 4 open-source packages on Packagist. Currently building the next generation of AI-integrated enterprise tools.

Have a project in mind?

From AI-integrated platforms to enterprise infrastructure, I architect solutions that deliver measurable business results. Let's talk.

Post Details
Read Time 7 min read
Published 2026-03-12 10:00:00
Category Laravel
Author Michael K. Laweh
Share Article

Related Articles

View All Posts
Apr 11, 2026 • 14 min read
How I Structure Large Laravel Projects (My Personal Architecture Blueprint)

After 16+ years of building production systems, I have a specific way...

Apr 09, 2026 • 6 min read
Production SQLite in 2026: Running Laravel Without a Database Server

SQLite is no longer just for prototyping. Since Laravel 11, it is the...

Mar 28, 2026 • 12 min read
How I Built a Markdown-Powered CMS in Laravel With Zero Database

A deep-dive into the flat-file content architecture powering klytron.c...