Skip to main content
Web Development7 min read

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

By Purva Patel

AI SDK Laravel - library-1

What Is the Laravel AI SDK?

Laravel AI (https://laravel.com/ai) is Laravel’s official, first-party package for building AI features into PHP applications. Instead of pulling in a separate library for every AI provider and writing your own glue code, you get a single, Laravel-native interface that talks to all of them.

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.

laravel-ai-sdk.webp

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, with prompts in and 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, with 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

Landing page: [laravel.com/ai](https://laravel.com/ai)

Documentation: [laravel.com/docs/ai-sdk](https://laravel.com/docs/ai-sdk)

GitHub repository: [github.com/laravel/ai](https://github.com/laravel/ai)

Packagist: [packagist.org/packages/laravel/ai](https://packagist.org/packages/laravel/ai)

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, with 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.

Blogs

Field notes on shipping software, design, and everything in between.

AI SDK Laravel - library (1)
Web DevelopmentJul 3, 2026

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

Laravel AI is Laravel’s official, first-party package for building AI features into PHP applications. Instead of pulling in…

Playwright MCP
Web DevelopmentJun 2, 2026

How I Audited and Fixed My Next.js Mobile UI in Minutes Using Playwright MCP

Every developer knows the tedious dance of mobile UI auditing. You deploy your site, open Chrome DevTools, toggle…

agile team management thumbnail
StoriesJul 19, 2023

Agile Team Management Unleashed: Insights from Top 5 Management Books for Small IT Agencies

Welcome to our blog, where we embark on a journey to unlock the secrets of maintaining a small…

Ways to create Effective UI/UX Design Portfolio
UI/UXDec 15, 2022

Ways to create Effective UI/UX Design Portfolio

In an industry where education and experience are not necessarily requirements for a dream position, a UX design…

5 Prototyping Tools for UI/UX Designers
UI/UXSep 12, 2022

5 Prototyping Tools for UI/UX Designers

It may sound cliche, but it’s also true that prototyping plays an important role in communicating how the…

Dark UI Design : Best Practices
UI/UXAug 25, 2022

Dark UI Design : Best Practices

Dark theme was introduced with IOS 13 in September 2019 followed by Android 10(Q) in May 2020 after…

What is viewBinding in Android and How we can use it?
Android App DevelopmentAug 24, 2022

What is viewBinding in Android and How we can use it?

Till now when we want to connect an XML element to a java or kotlin file we always…

5 Figma Plugins that can be used to create Good User Interface
UI/UXAug 24, 2022

5 Figma Plugins that can be used to create Good User Interface

After the launch in 2016, Figma has grown to become one of the leading UI design tools on…

MySQL Tips & Tricks : Functions
Web DevelopmentAug 24, 2022

MySQL Tips & Tricks : Functions

In our previous article on MySQL, we covered Triggers. In this article we are covering another important feature…

Free consultation to scope your
creative projects

Book demo

FAQ

Ask AI to summarize QuriousClick
Have a project in mind?Tell us what you're planning and we'll help you shape the scope, timeline and next steps.
Book a discovery call
  • QuriousClick is a design and development studio. Since 2014 our in-house team has designed, built and supported websites, web and mobile apps, brands and AI products for 100+ customers worldwide.