laravel/ai
Laravel AI SDK offers a unified, Laravel-friendly API for OpenAI, Anthropic, Gemini, and more. Build agents with tools and structured output, generate images, transcribe/synthesize audio, and create embeddings—all through one consistent interface.
Installation:
composer require laravel/ai
Publish the config file (if needed):
php artisan vendor:publish --provider="Laravel\AI\AIServiceProvider"
Configure Provider:
Add your API key to .env (e.g., OPENAI_API_KEY=your_key_here) and define the provider in config/ai.php:
'default' => env('AI_PROVIDER', 'openai'),
'providers' => [
'openai' => [
'key' => env('OPENAI_API_KEY'),
'options' => [], // Support for provider-specific options
'strict' => env('AI_STRICT_MODE', false), // New: Opt-in strict mode
],
// Add other providers (e.g., 'anthropic', 'gemini', 'openrouter')
],
First Use Case: Generate a simple completion in a controller or service:
use Laravel\AI\Facades\AI;
$response = AI::make('openai')->get('gpt-3.5-turbo')->complete('Explain Laravel AI SDK in 3 bullet points.');
return $response->choices[0]->text;
New: Strict Mode Enable strict mode for OpenAI providers via config or attribute:
// Config
'providers' => [
'openai' => [
'strict' => true,
],
],
// Or via attribute
#[Strict]
public function generateStrictResponse() {
$response = AI::make('openai')->get('gpt-3.5-turbo')->complete('Strict prompt');
}
New: Conversation List Retrieval Fetch conversations directly from the store:
$conversations = AI::conversations()->all();
config/ai.php for strict mode and provider options.Laravel\AI\Facades\AI for quick access to AI services.InsufficientCreditsException and improved validation.#[Strict] attribute usage and strict config option.Basic Prompting (Updated):
$result = AI::make('openai')->get('gpt-4')->complete('Summarize this: ' . $longText);
Strict Mode Responses (New):
// Via config
AI::make('openai')->get('gpt-3.5-turbo')->strict()->complete('Strict prompt');
// Via attribute
#[Strict]
public function strictResponse() {
$response = AI::make('openai')->get('gpt-3.5-turbo')->complete('Strict prompt');
}
Tools and Agents (Updated):
$agent = new Agent('bedrock', 'anthropic.claude-v2', [
'providerOptions' => ['temperature' => 0.5],
]);
$response = $agent->call('Query', 'Analyze this document');
Embeddings with Closure Options (New):
$embedding = AI::make('openai')->get()->embed('Laravel AI SDK', [
'options' => fn() => ['cached' => true],
]);
Audio Support (Updated):
$transcription = AI::make('openrouter')->get('whisper')->transcribe($audioFile, [
'providerOptions' => ['language' => 'en'],
]);
Conversations (Updated):
$conversations = AI::conversations()->all();
$conversation = AI::conversations()->find(1);
$history = $conversation->history()->withAttachments()->get();
Image Generation (Updated):
$image = AI::make('openrouter')->get('dall-e-3')->generate(
'A futuristic Laravel logo with the text "AI Powered"',
['size' => '1024x1024']
);
Document Validation (New):
try {
$reranked = AI::make('cohere')->rerank($query, []); // Throws exception
} catch (\Laravel\AI\Exceptions\InvalidInputException $e) {
// Handle empty document list
}
Service Layer: Encapsulate AI logic with strict mode and error handling:
class AIContentGenerator {
public function __construct(private AI $ai) {}
#[Strict]
public function generateSummary(string $content): string {
return $this->ai->make('openai')->get('gpt-3.5-turbo')->complete(
"Summarize this in 3 bullet points: $content"
)->choices[0]->text;
}
}
Error Handling: Leverage new exceptions:
try {
$response = AI::make('openrouter')->get()->complete($prompt);
} catch (\Laravel\AI\Exceptions\InsufficientCreditsException $e) {
// Handle credit errors
} catch (\Laravel\AI\Exceptions\InvalidInputException $e) {
// Handle blank/empty inputs
}
Testing: Use updated fake methods:
AI::fake(['openai']);
AI::shouldReceive('complete')
->once()
->andThrow(new \Laravel\AI\Exceptions\InsufficientCreditsException());
Database Connection: Respect configured connection in models:
// Use a specific connection
AI::conversations()->setConnection('mysql_secondary')->all();
Documentation: Check updated PHPDoc for @throws in methods like:
AI::make('azure-openai')->get()->generateImage(); // Throws RuntimeException
Strict Mode (New):
#[Strict] will send strict: false to providers.#[Strict] or configure strict: true in config/ai.php.Input Validation (Updated):
try {
AI::make('openai')->get()->embed(''); // Throws InvalidInputException
} catch (\Laravel\AI\Exceptions\InvalidInputException $e) {}
Provider-Specific Quirks (Updated):
529 overloaded responses and insufficient credits.providerOptions for reasoning_content:
$agent = new Agent('anthropic', 'claude-3', [
'providerOptions' => ['reasoning_content' => 'Previous context...'],
]);
InsufficientCreditsException for credit errors.providerOptions through to Converse:
$agent->call('Query', 'Analyze', ['providerOptions' => ['temperature' => 0.3]]);
Conversations:
withAttachments() is used when loading history.mysql_secondary).Image Generation:
image+text restriction for supported models.Documentation:
@throws annotations for methods like:
OpenAiGateway::generateTranscription()AzureOpenAiGateway::generateImage()Image::of() and Embeddings::for()// Check if strict mode is active
if (AI::make('openai')->get()->isStrict()) {
logger()->debug('Strict mode enabled');
}
How can I help you explore Laravel packages today?