Get In Touch
๐Ÿ‡ฎ๐Ÿ‡ณ Ahmedabad, India
[email protected]
+91 9925757082
Get In Touch
๐Ÿ‡ช๐Ÿ‡ธ Santa Cruz de la Palma, Spain
[email protected]
+1 (917) 668-2504
Get In Touch
๐Ÿ‡จ๐Ÿ‡ฆ Coming Soon, Canada
[email protected]
+1 (917) 668-2504
Back

Laravel AI SDK : A Complete Overview of Building AI Features in PHP

What Is the Laravel AI SDK?

The core idea is a unified API. You write your logic once against the `AI` facade, and the actual model running underneath can be OpenAI, Google Gemini, Anthropic Claude, Groq, Mistral, DeepSeek, or a local Ollama model. It works the same way Laravel’s database layer does: the same query code runs on MySQL, PostgreSQL, or SQLite because the driver underneath is swappable.

For Laravel developers, that means AI stops being a bolt-on integration and starts behaving like any other framework feature โ€” configured in `config/ai.php`, driven by environment variables, and wired into queues, caching, and events out of the box.

Why It Matters ?

Before a first-party SDK existed, adding AI to a Laravel app usually meant choosing a provider’s SDK, learning its response shapes and error types, and building an abstraction on top so you weren’t locked in. Switching from OpenAI to Gemini later meant rewriting that integration.

Laravel AI removes that friction. Every provider speaks the same interface, so switching models is a configuration change, not a refactor:

AI::text('Summarize this ticket...');                 // default provider
AI::provider('anthropic')->text('Summarize this...'); // Claude
AI::provider('ollama')->text('Summarize this...');    // local, no external API

This provider-agnostic approach means you can use a cheap, fast model for high-volume work and a smarter model for complex reasoning โ€” without touching your business logic.

What You Can Build With It ?

The SDK covers most of the AI surface area you’d reach for in a real product:

  1. Text and chat generation โ€” the foundation: prompts in, responses out.
  2. AI agents โ€” models that hold conversation history and act over multiple steps.
  3. Tool calling (function calling) โ€” let the AI run your PHP methods to fetch real data.
  4. Structured output โ€” force responses into a schema so you get clean data, not prose.
  5. Embeddings โ€” turn text into vectors for meaning-based comparison.
  6. Semantic search and RAG โ€” find content by meaning and ground answers in your own data.
  7. Image generation and vision โ€” create images or analyze uploaded ones.
  8. Audio โ€” transcribe speech to text and generate speech from text.
  9. Streaming โ€” deliver responses word-by-word for a live, ChatGPT-style feel.

Everything above runs through the same AI facade, so learning one part carries over to the rest.

Where It Fits ?

In practice, these capabilities map onto features teams build every day:

  1. Support chatbots that answer questions and look up live order or account data.
  2. Ticket triage that auto-classifies and routes incoming requests.
  3. Knowledge-base search that understands intent instead of matching keywords.
  4. Document and invoice extraction that pulls structured fields from PDFs or emails.
  5. Content and marketing pipelines that draft copy and generate SEO metadata.
  6. Voice-enabled portals that accept audio and reply in speech.

If a feature involves understanding language, extracting data, or searching by meaning, the SDK is usually the shortest path to it.

A Simple Example

The most basic operation is a single text prompt that returns a string:

$reply = AI::text('Write a 2-line welcome message for new users.');

Add a `system` prompt to control tone and behavior, and you have the core of a support assistant in two arguments:

AI::text(
    prompt: 'What is your refund policy?',
    system: 'You are a concise, friendly support agent. Keep it under 80 words.'
);

That is the whole pattern. From here, the other features are variations on the same idea.

AI Agents and Tool Calling

An agent is an AI that remembers the conversation and can call your own code when it needs real information. You mark a method with the `#[Tool]` attribute, and the model decides on its own when to use it:

class SupportAgent extends Agent
{
    protected string $instructions = 'You are a support agent.
        Always look up real order data instead of guessing.';

    #[Tool('Look up an order by its ID.')]
    public function lookUpOrder(int $orderId): string
    {
        return Order::find($orderId)?->toJson() ?? "No order {$orderId}.";
    }
}

When a user asks “where is order 4821?”, the agent recognizes it needs data, calls `lookUpOrder(4821)`, reads the result, and answers naturally โ€” no keyword matching or hardcoded rules. This is what makes agents useful for support and internal tooling.

Structured Output

Sometimes you want a saveable record, not a paragraph. Structured output makes the model fill in a schema you define and hands you back a ready-to-use PHP array:

$triage = AI::structured(
    prompt: "Classify: {$ticket->body}",
    schema: [
        'type' => 'object',
        'properties' => [
            'category' => ['type' => 'string', 'enum' => ['billing', 'technical', 'account']],
            'priority' => ['type' => 'string', 'enum' => ['low', 'high', 'urgent']],
        ],
    ]
);

$ticket->update($triage);

The same approach reads invoice fields from PDF text, extracts details from resumes, or scores sentiment โ€” anywhere you’d otherwise write a fragile parser.

Embeddings, Semantic Search, and RAG

Keyword search matches words; semantic search matches meaning. Embeddings make that possible by converting text into vectors, so “I forgot my login” lands near “reset password” even with no shared words.

$vector = AI::embed('How do I reset my password?');

Store those vectors, find the closest matches to a query, then feed them back to the model as context. That pattern is **Retrieval-Augmented Generation (RAG)** โ€” answers grounded in your own documents rather than the model’s general knowledge:

$context = $faqs->pluck('answer')->implode("\n");

AI::text(
    prompt: $userQuestion,
    system: "Answer using ONLY these notes:\n{$context}"
);

This is the foundation of accurate knowledge-base search and document Q&A.

Images, Audio, and Streaming

The same facade also handles media and real-time delivery.

Generate an image from a prompt:

$image = AI::image(prompt: 'A modern data center, wide angle, photorealistic');

Transcribe speech to text, and turn text back into speech:

$text  = AI::transcribe($request->file('audio')->get())->text;
$audio = AI::speech('Thanks for contacting support!');

Stream a response chunk-by-chunk for the familiar live-typing effect:

AI::stream(
    prompt: $message,
    onChunk: fn ($chunk) => print("data: {$chunk}\n\n")
);

Each of these uses the same `AI` facade you started with, so there’s no new mental model to learn.

The Laravel AI SDK turns AI into a first-class part of the framework. Text generation, agents, tool calling, structured output, embeddings, semantic search, images, audio, and streaming all live behind one consistent, provider-agnostic API โ€” which means less integration code and far more flexibility in which models you run.

For any Laravel team, the question is no longer whether to add AI, but which feature to ship first. With Laravel AI, that first feature is a lot closer than it used to be.

Official Resources

What is the Laravel AI SDK?

The Laravel AI SDK (`laravel/ai`) is Laravel’s official, first-party package for building AI features in PHP. It provides a single, unified API for text generation, AI agents, tool calling, structured output, embeddings, semantic search, image generation, audio, and streaming across many AI providers.

How do I install the Laravel AI SDK?

Install it with Composer by running `composer require laravel/ai`, then publish the configuration and migrations with `php artisan vendor:publish`. Add your provider API keys to the `.env` file and you’re ready to build.

Which AI providers does `laravel/ai` support?

The Laravel AI SDK supports around 14 providers, including OpenAI, Anthropic Claude, Google Gemini, Groq, Mistral, DeepSeek, xAI (Grok), and Ollama for local models. Because the API is unified, you can switch providers with a configuration change instead of rewriting code.

Can I build AI agents with Laravel?

Yes. The Laravel AI SDK lets you build AI agents as PHP classes with custom instructions, conversation memory, and tools. Using the `#[Tool]` attribute, an agent can call your own methods to fetch live data, making it ideal for support chatbots and internal automation.

What is structured output in the Laravel AI SDK?

Structured output forces an AI model to return data that matches a schema you define, so you receive a clean, validated PHP array instead of free-form text. It’s used for ticket classification, invoice and document extraction, and any task that needs machine-readable results.

Does the Laravel AI SDK support embeddings and RAG?

Yes. It can generate vector embeddings for semantic search and includes vector store support for Retrieval-Augmented Generation (RAG), letting you ground AI answers in your own documents and knowledge base.

Can Laravel stream AI responses like ChatGPT?

Yes. The SDK supports streaming, so responses arrive chunk-by-chunk for a real-time, ChatGPT-style typing effect โ€” no custom WebSocket setup required.

Do I need Python to build AI apps with Laravel?

No. The Laravel AI SDK lets you build AI agents, chatbots, and AI-powered features entirely in PHP, with no Python or separate AI service required.

Is the Laravel AI SDK free?

The `laravel/ai` package is free and open-source. You only pay usage fees to whichever AI provider you use, or you can run local models with Ollama at no external cost.

Purva P
Purva P