Web Development 5-8 minutes

Laravel 13 AI SDK: Build Agents and Sub-Agents in PHP Without External Services

Diego Cortés
Diego Cortés
Full Stack Developer & SEO Specialist
Share:
Laravel 13 AI SDK: Build Agents and Sub-Agents in PHP Without External Services

Laravel 13 "Atlas" took the AI SDK to production-stable on March 17, 2026: agents with tools, structured output, and native semantic search, plus sub-agents since May. Here is how you build an AI-native app without leaving PHP.

From Laravel 12's Beta to Laravel 13's Stable SDK

The Laravel AI SDK started as a beta package during the Laravel 12 cycle, a first-party way to integrate language models through a consistent API in the framework's style. With the release of Laravel 13 "Atlas" on March 17, 2026, the SDK reached production stability on day one, which changes the game: you no longer need to build your own orchestration or rely on third-party packages to connect your application to AI models.

What "Atlas" Changed: a 10-Minute Upgrade with Zero Breaking Changes

The Laravel team designed the move from 12.x to 13.x to be nearly painless. The official upgrade path takes about ten minutes for most projects, and the AI SDK introduces no breaking changes compared to the beta: if you already used the package on Laravel 12, upgrading leaves you with the same classes and methods, but with stability guarantees and long-term support. That makes Laravel 13 the first version where shipping AI-native features is a reasonable production decision rather than a gamble.

What You Can Generate: Text, Images, Audio, and Embeddings

The SDK is not limited to chat. Through a single interface you can generate text, create images, synthesize speech, transcribe audio, and compute embeddings for vector search. The official 13.x documentation presents these capabilities as one homogeneous set: the same configuration style and the same abstractions for any modality, so switching providers or tasks does not force you to rewrite your business logic.

Agents: The SDK's Building Block

The core concept of the AI SDK is the agent: a dedicated PHP class that encapsulates everything a language model needs to do a specific job. Instead of scattering LLM calls across controllers and services, you define an agent with its instructions, context, and tools, and the SDK handles the execution loop.

An Agent as a PHP Class: Instructions, Context, and Tools

A typical agent declares its system instructions, conversation context, and the tools it can invoke. Tools are ordinary PHP classes or methods that the model decides to call when it needs data or actions it cannot figure out on its own, such as querying a database or sending an email.

composer require laravel/ai
<?php

namespace App\Agents;

use Laravel\Ai\Agent;

class SupportAgent extends Agent
{
    protected string $instructions = '
        You are the store support agent.
        Always answer in the user language.
    ';

    protected array $tools = [
        SearchTickets::class,
        LookupOrder::class,
    ];
}

When the user asks "where is my order?", the agent decides to call the LookupOrder tool, gets the result, and builds the final answer. You only define what the agent can do; the model decides when to do it.

Structured Output and Blade Template Prompts

Two details set this apart from hand-rolling an OpenAI SDK integration. First, structured output: you declare the expected response schema and the SDK validates and types the result, eliminating manual JSON parsing and silent bugs from renamed fields. Second, prompts are written with Blade templates, so you can reuse partials, pass Laravel model data, and keep prompts versioned in your repository like any other view.

Swappable Providers: OpenAI, Anthropic, Ollama, and Mistral

The SDK abstracts the provider behind a configuration layer. OpenAI, Anthropic, Ollama, and Mistral are first-class citizens, and the list keeps growing with the ecosystem.

Switching Providers by Changing a Single Config Line

The driver architecture works like the rest of Laravel: you define providers in the config file and pick the active one with an environment variable. Changing providers touches no business code, only configuration.

// config/ai.php
'default' => env('AI_PROVIDER', 'openai'),

'providers' => [
    'openai' => [
        'api_key' => env('OPENAI_API_KEY'),
        'model' => env('OPENAI_MODEL', 'gpt-5'),
    ],
    'anthropic' => [
        'api_key' => env('ANTHROPIC_API_KEY'),
        'model' => env('ANTHROPIC_MODEL', 'claude-sonnet-4'),
    ],
    'ollama' => [
        'url' => env('OLLAMA_URL', 'http://localhost:11434'),
        'model' => env('OLLAMA_MODEL', 'llama-3.3'),
    ],
    'mistral' => [
        'api_key' => env('MISTRAL_API_KEY'),
        'model' => env('MISTRAL_MODEL', 'mistral-large'),
    ],
],

This flexibility has a very practical consequence: you can develop and test with Ollama locally without paying API fees, then deploy to production against OpenAI or Anthropic by changing a single environment variable.

Sub-Agents: Orchestration Since May 2026

On May 12, 2026, the SDK jumped from a chat tool to an orchestration layer: you can now pass an agent as a tool to another agent. That is the birth of sub-agents, which let you break large problems into specialized agents.

Passing an Agent as a Tool to Another Agent

The mechanics are straightforward: you instantiate a specialized agent and include it in the main agent's tool list. When the main agent detects that a query belongs to the sub-agent's domain, it delegates the work with the right context and receives the answer.

$refundAgent = new RefundAgent();
$billingAgent = new BillingAgent();

$supportAgent = new SupportAgent([
    'tools' => [
        SearchTickets::class,
        $refundAgent,   // sub-agent
        $billingAgent,  // sub-agent
    ],
]);

$response = $supportAgent->ask(
    'I want to return order 4521 because it arrived broken.'
);

Each sub-agent can have its own instructions, its own tools, and even a different model: a billing sub-agent can use a cheaper, faster model while the main agent uses the most capable one. The result is a modular, testable, cost-efficient agent architecture.

When to Use Sub-Agents (and When Not To)

Sub-agents shine when there are clearly separated domains: support with refunds and billing, a content assistant with writing and proofreading sub-agents, or customer service that delegates per product. For linear tasks with a single tool, a single agent with several tools is simpler and consumes fewer tokens. The practical rule: add a sub-agent when the main agent starts dragging contradictory instructions or tools it rarely uses.

Native Semantic Search with Eloquent

The other big bet of Laravel 13 is semantic search integrated with Eloquent. Instead of depending on external vector search services, the SDK exposes embedding flows and vector queries that run on your own database.

Embeddings, Vector Queries, and Indexing Workflows

The typical pattern has three phases: you generate embeddings for your documents when saving them, store them in a vector column on the model, and query by similarity using the embedding of the user's question. The SDK also provides vector store management and result reranking to fine-tune the order of answers.

$question = 'How do I request a refund?';

$embedding = Ai::embed($question);

$articles = HelpArticle::query()
    ->orderByVector('embedding', $embedding)
    ->limit(5)
    ->get();

Combined with agents, this pattern enables retrieval-augmented generation (RAG) without leaving the framework: the agent fetches the relevant fragments with a vector query and uses them as context to answer with evidence instead of guessing.

Hands-On: a Support Agent with Sub-Agents

Let us put it all together. An online store wants a support chat that knows about refunds, billing, and order status. With the SDK you define three agents: a main agent with the general tone and policy instructions, a refund sub-agent with the tool that executes the return in the ERP, and a billing sub-agent with the tool that looks up and resends invoices. The main agent receives the query, decides which sub-agent it needs, and delegates. If the query is ambiguous, it asks for clarification or escalates to a human with a summary of the thread. The whole flow runs in PHP with response streaming, so the user sees the text arrive progressively, with no external orchestration service required.

To try it without spending a cent, just point the provider at local Ollama, as the config above shows. The same code that runs against a local model in development works against a commercial provider in production.

Conclusion

Laravel 13's AI SDK turns AI into just another framework capability: agents as PHP classes, swappable providers with a single config line, sub-agents to orchestrate complex tasks, and semantic search integrated with Eloquent. If you have not tried it yet, the best way to start is to build a small agent with Ollama and let the SDK do the heavy lifting. To review the rest of the version's features, this blog has a Laravel 13 upgrade guide and an introduction to local AI with Ollama.

Categories