Laravel has always focused on developer happiness. We build tools that make complex tasks feel like a breeze. The new Laravel AI SDK continues this tradition. It provides a unified, expressive interface for interacting with Large Language Models.
Integrating AI used to mean wrestling with custom HTTP clients. You had to manage prompt engineering, handle rate limits, and parse messy JSON. The Laravel AI SDK changes that. It treats AI as a first-class citizen within the php web framework.
This guide shows you how to connect your application to OpenAI. We will move from a fresh installation to a working AI agent in five minutes.
The Philosophy: AI as a Service
Before we touch code, understand the approach. Laravel treats AI providers like mail drivers or database connections. You shouldn't care if you're using OpenAI, Anthropic, or a local Ollama instance. The syntax remains the same.
This abstraction allows you to swap providers without rewriting your business logic. It makes AI features maintainable. You build for the long term, not just for the current hype cycle. This is why Laravel remains the premier choice for php developer tools.
Step 1: Install the Package
Open your terminal. Navigate to your project root. Install the AI SDK using Composer.
composer require laravel/ai
This package pulls in the core contracts and the default providers. It sets the foundation for your intelligent features.
Next, publish the configuration file. This file lives in config/ai.php.
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
Run the migrations. The SDK includes tables for managing conversations and message history. This is vital for building chatbots that remember past interactions.
php artisan migrate

Step 2: Configure Your Credentials
Open your .env file. You need an API key from OpenAI. Paste it into the following variable:
OPENAI_API_KEY=sk-your-actual-key-here
AI_PROVIDER=openai
Now, look at config/ai.php. The SDK uses the openai driver by default. It looks for the key you just added. You can also specify the base URL if you use a proxy or a compatible service like Groq.
'providers' => [
'openai' => [
'driver' => 'openai',
'key' => env('OPENAI_API_KEY'),
'url' => env('OPENAI_URL'),
],
],
The configuration is straightforward. We avoid deep nesting. Each provider has its own block. This keeps your environment clean and readable.
Step 3: Create Your First Agent
In the Laravel AI SDK, an Agent is a specialized class. It represents a specific persona or task. You might have a SupportAgent, a ContentWriterAgent, or a CodeReviewAgent.
Generate a new agent using Artisan:
php artisan make:agent AssistantAgent
Open app/Ai/Agents/AssistantAgent.php. This class defines how the AI behaves. We use PHP attributes to configure the provider and the model.
namespace App\Ai\Agents;
use Laravel\Ai\Attributes\Model;
use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
#[Provider('openai')]
#[Model('gpt-4o-mini')]
class AssistantAgent implements Agent
{
use Promptable;
public function instructions(): string
{
return 'You are a helpful assistant for a Laravel application. Be concise and professional.';
}
}
The instructions method acts as the system prompt. It tells the model its identity. The gpt-4o-mini model is an excellent choice for speed and cost-efficiency.

Step 4: Build the REST API Endpoint
Now we integrate the agent into your application flow. Most developers want to build rest api with php to serve frontend clients or mobile apps.
Open routes/api.php. Create a new route that accepts a prompt and returns a response from our agent.
use App\Ai\Agents\AssistantAgent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/ask', function (Request $request) {
$request->validate(['prompt' => 'required|string']);
$agent = new AssistantAgent();
$response = $agent->respond($request->prompt);
return response()->json([
'answer' => $response->content(),
'tokens' => $response->usage()->total_tokens,
]);
});
This simple block does a lot of heavy lifting. The respond method sends the prompt to OpenAI. It includes your system instructions automatically. The returned object gives you access to the text content and metadata like token usage.
Step 5: Handling Streaming Responses
For a better user experience, use streaming. This allows the AI to send text as it is generated. It eliminates the "waiting" feeling for the user.
Laravel makes this effortless with a generator pattern.
Route::post('/stream', function (Request $request) {
$agent = new AssistantAgent();
$stream = $agent->stream($request->prompt);
return response()->stream(function () use ($stream) {
foreach ($stream as $chunk) {
echo "data: " . json_encode(['text' => $chunk]) . "\n\n";
ob_flush();
flush();
}
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
]);
});
Streaming is vital for modern interfaces. It mirrors the behavior of ChatGPT. Your application feels responsive and alive.

Step 6: Testing and Fakes
Laravel developers value testing. The AI SDK provides a built-in way to fake AI responses. This prevents you from hitting your OpenAI quota during CI/CD runs.
use App\Ai\Agents\AssistantAgent;
public function test_ai_responds_correctly()
{
AssistantAgent::fake([
'Hello' => 'Hi there! How can I help you today?',
]);
$agent = new AssistantAgent();
$response = $agent->respond('Hello');
$this->assertEquals('Hi there! How can I help you today?', $response->content());
}
Faking is a powerful feature. It allows you to test your application's logic without dependency on an external API.
Advanced Patterns: Tools and RAG
Integration is just the start. The Laravel AI SDK supports Tools. These are PHP methods that your agent can choose to call. For example, an agent could call a searchDatabase tool to find real-time info.
You can also implement Retrieval Augmented Generation (RAG). By combining the AI SDK with Laravel Scout and a vector database, your agent can answer questions based on your own documentation or data.
Deployment with Laravel Cloud
Once your AI features are ready, you need a stable home for them. Laravel Cloud is the managed infrastructure solution built for this. It handles scaling your PHP workers as AI demand grows.

Deployment is a single command. You don't have to worry about server configuration or environment synchronization. Cloud manages your .env variables securely, ensuring your OPENAI_API_KEY stays protected.
Final Thoughts
The Laravel AI SDK removes the friction of adding intelligence to your apps. You get a clean, testable, and provider-agnostic interface. Whether you are building a simple chatbot or a complex automation engine, the workflow remains elegant.
The future of web development involves AI. With Laravel, you aren't just reacting to this change. You are leading it. We'd love to hear what you build with these new tools. Share your progress with the community.
Your story belongs here.