Laravel Daily's

Building AI-Powered Features with the Laravel AI SDK: A Practical Developer's Guide

hero image

Laravel has always focused on developer happiness. With the release of Laravel 13, that focus extends directly into artificial intelligence. The new first-party Laravel AI SDK provides a unified, elegant interface for integrating Large Language Models (LLMs) into your applications.

Building AI features used to mean juggling multiple proprietary SDKs and inconsistent response formats. The Laravel AI SDK changes this. It offers a consistent API that works across OpenAI, Anthropic, Gemini, and local models. Whether you need a simple chat interface or a complex autonomous agent, the tools are now native to the php web framework you already know.

Setup: Getting Started with Laravel AI

The AI SDK is a first-class citizen in the ecosystem. Installation is a single command. You don't need to learn new paradigms: it feels like standard Laravel.

composer require laravel/ai

After installation, publish the configuration file to define your providers. The config/ai.php file is where you'll map your API keys for OpenAI or Anthropic. This abstraction is powerful. It allows you to write code once and swap the underlying model by changing a single configuration value.

Most php developer tools require extensive boilerplate for AI. Laravel simplifies this to a few environment variables. Once your keys are set, the AI facade becomes your primary entry point for text generation, embeddings, and image synthesis.

Agents: Moving Beyond Simple Prompts

The core of modern AI development is the Agent. In Laravel 13, agents are dedicated PHP classes. They encapsulate instructions, tools, and memory. This keeps your controllers clean and your AI logic testable.

A friendly cartoony robot representing an AI support agent

You can generate a new agent using Artisan:

php artisan make:agent SupportAssistant

An agent defined this way can have a specific system prompt: like "You are a helpful support assistant for an e-commerce store." You can then call this agent from your application like any other service.

$response = SupportAssistant::ask("Where is my order #12345?");

The SDK handles the conversation history and context window management. It turns a stateless LLM into a persistent, helpful entity within your application.

Structured Output: Predictable Data

One of the biggest hurdles in AI is getting the model to return data you can actually use. You can't build a robust system if the AI returns "Here is your JSON:" followed by free-form text.

Laravel solves this with structured output. By implementing the HasStructuredOutput interface on your agent, you can define a JSON schema. The SDK then forces the model to return a response that matches your schema exactly.

This is essential when you build rest api with php. If your API needs to return a sentiment score or a categorized list of tags, the AI SDK ensures the response is a valid object you can cast directly to a DTO or an Eloquent model.

Tool Calling: Giving AI Hands

Agents are limited if they can only talk. Tool calling allows your agents to perform actions in your application. You can give an agent "tools" by simply annotating methods in your agent class with the #[Tool] attribute.

If your support agent needs to check a database, you give it a checkOrderStatus tool. When the user asks about their package, the AI realizes it needs that information, triggers your PHP method, receives the data, and then formulates a natural language answer. This seamless loop between LLM reasoning and PHP execution is the hallmark of the Laravel AI SDK.

Reliability: Provider Failover

In production, relying on a single AI provider is a risk. API outages happen. Laravel’s unified API makes implementing failover straightforward.

Since the interface remains the same regardless of the provider, you can wrap your AI calls in a simple try-catch block. If OpenAI fails, your application can instantly fallback to Anthropic. This ensures your AI features remain available even during third-party downtime. It’s the kind of production-grade thinking built into every part of the framework.

Vector Search: Semantic Retrieval with pgvector

Simple keyword search is no longer enough. Users expect to find what they mean, not just what they type. Laravel 13 introduces native vector query support, specifically optimized for pgvector.

A vibrant magnifying glass exploring a field of geometric data vectors

The AI SDK makes generating embeddings as simple as calling a string helper.

$vector = Str::of("Laravel is the best PHP framework")->toEmbeddings();

You can store these vectors in a standard PostgreSQL table using the new vector column type in your migrations. Searching then becomes a matter of a single Eloquent query.

$products = Product::query()
    ->whereVectorSimilarTo('embedding', $userQueryVector)
    ->limit(5)
    ->get();

This is the foundation for Retrieval-Augmented Generation (RAG). Your agents can "search" your own documentation or database to provide answers grounded in your specific data, reducing hallucinations and increasing accuracy.

Laravel Boost: AI-Assisted Development

The AI revolution isn't just for your users; it's for you. Laravel Boost integrates with the MCP (Model Context Protocol) to give your AI coding assistants a deep understanding of your application.

Through the skills system, Boost can expose your routes, database schemas, and logs to AI tools. This means your AI assistant can help you debug a specific error by looking at the actual log files or help you write a new feature by understanding your existing database relationships. It's a massive leap forward for developer productivity.

Production: Scaling and Safety

Shipping AI features requires a different set of considerations than standard web development. Costs can spiral, and LLM latency can frustrate users.

A cartoony robot mechanic monitoring a high-tech engine representing production reliability

Laravel provides the infrastructure to handle these challenges:

  • Queues: Always handle heavy AI processing in background jobs. Use Laravel's queue system to keep your UI responsive while the AI thinks.
  • Caching: AI responses are expensive. If a query is likely to be repeated, cache the response using Redis.
  • Rate Limiting: Protect your API budget by implementing strict rate limits on AI-powered endpoints.
  • Monitoring: Use tools like Laravel Nightwatch to monitor your AI provider's response times and error rates in real-time.

Building with the Laravel AI SDK means you aren't just adding a chatbot. You are building a sophisticated, AI-augmented application on a foundation designed for scale.

The era of "AI-first" development is here. Whether you're building a startup or enhancing an enterprise system, the tools to ship fast and ship reliably are now in your hands. Start by exploring the official documentation and see what you can build.

Previous
Laravel Trends 2026: The Streaming, Real-Time, and Multi-Platform PHP Revolution
Next
Supercharge Your Laravel + Vue SPA: Inertia 3.x Features You Should Be Using Now