laravel/ai
Laravel AI SDK for a unified, Laravel-friendly API across providers like OpenAI, Anthropic, and Gemini. Build agents with tools and structured output, generate images, synthesize/transcribe audio, create embeddings, and more—all through one consistent interface.
Installation:
composer require laravel/ai
Publish the config file:
php artisan vendor:publish --provider="Laravel\AI\AIServiceProvider" --tag="ai-config"
Configure Providers:
Edit .env with your preferred provider (e.g., OpenAI, Anthropic, Gemini):
AI_PROVIDER=openai
OPENAI_API_KEY=your_api_key_here
First Use Case: Generate text with a simple prompt:
use Laravel\AI\Facades\AI;
$response = AI::generateText('Explain Laravel AI SDK in 3 bullet points');
echo $response->content;
Key Starting Points:
config/ai.php (provider configurations)app/Providers/AIServiceProvider.php (custom provider bindings)Basic Usage:
$response = AI::generateText('Summarize this: ' . $longText);
With Model Selection:
$response = AI::generateText('Summarize', [
'model' => 'gpt-4',
'temperature' => 0.2,
]);
Define Tools:
use Laravel\AI\Tools\Tool;
$tools = [
Tool::fromClass(CalculateTaxTool::class),
Tool::fromClass(FetchUserDataTool::class),
];
Run Agent:
$agent = AI::agent()
->tools($tools)
->create();
$response = $agent->call('Calculate tax for user ID 123');
Define Schema:
use Laravel\AI\Structured\StructuredOutput;
$schema = StructuredOutput::make()
->title('UserProfile')
->description('Extract user profile data')
->property('name', 'string')
->property('email', 'string')
->property('age', 'integer');
Generate Structured Data:
$response = AI::generateStructured($schema, 'Extract profile from: ' . $text);
$data = $response->content; // Parsed as array/object
Create Embeddings:
$embeddings = AI::embeddings()->for('Your text here')->create();
Similarity Search:
$results = AI::similaritySearch()
->usingModel(User::class, 'description')
->query('Find users interested in AI')
->limit(5)
->get();
Transcribe Audio:
$transcription = AI::transcribe('path/to/audio.mp3');
Generate Image:
$image = AI::generateImage('A futuristic cityscape');
$image->toHtml(); // Embed in Blade
Bind custom providers in AIServiceProvider:
public function register()
{
$this->app->bind('ai.provider.custom', function ($app) {
return new CustomAIProvider();
});
}
Add middleware to log/validate AI requests:
AI::extend('openai', function ($app) {
return new OpenAiGateway(
$app['config']['services.openai'],
new LogAIRequestsMiddleware()
);
});
Offload heavy AI tasks:
AI::queueEmbeddings('path/to/file.txt')->later();
Embed AI responses in views:
@php
$summary = AI::generateText('Summarize: ' . $article->content);
@endphp
<div>{{ $summary->content }}</div>
Use fake providers in tests:
AI::fake([
'openai' => [
'generateText' => 'Fake response',
],
]);
providerOptions for non-standard endpoints (e.g., Azure OpenAI):
AI::generateText('Prompt', ['providerOptions' => ['api_version' => '2023-05-15']]);
pause_turn tool continuations in agents:
$agent->handleToolContinuation(function ($tool, $response) {
if ($tool->name === 'pause_turn') {
return 'Resumed...';
}
});
parts matters):
AI::generateImage('Prompt', [
'parts' => [
['text' => 'A red apple'],
['image' => Storage::path('apple.jpg')],
],
]);
AI_DEBUG in .env to log token counts:
AI_DEBUG=true
config/ai.php:
'providers' => [
'openai' => [
'failover' => ['anthropic', 'gemini'],
],
],
AI::cache() for static prompts:
$response = AI::cache()->generateText('Static prompt', now()->addHours(1));
additionalProperties):
$schema->property('metadata', 'object', ['additionalProperties' => false]);
$response = AI::generateStructured($schema, 'Prompt', ['strict' => true]);
$agent->handleToolError(function ($tool, $error) {
Log::error("Tool {$tool->name} failed: {$error->getMessage()}");
return 'Fallback response';
});
$agent->stream(function ($chunk) {
echo $chunk->content;
});
RuntimeException:
if (empty($text)) {
throw new \InvalidArgumentException('Text cannot be empty');
}
$embeddings = AI::embeddings()->for($text)->create();
Schema::table('users', function ($table) {
$table->fullText('description');
});
Extend the SDK with new providers:
namespace App\Providers;
use Laravel\AI\Contracts\Gateway;
class CustomGateway implements Gateway
{
public function generateText(string $prompt, array $options = []): \Laravel\AI\Contracts\TextResponse
{
// Implement custom logic
}
}
Register in AIServiceProvider:
AI::extend('custom', function () {
return new CustomGateway();
});
Add dynamic tools to agents:
$agent->tools(function () {
return [
Tool::fromClass(DynamicTool::class, ['param' => request('param')]),
];
});
Intercept AI calls globally:
AI::macro('before', function ($callback) {
$originalGenerateText = AI::generateText(...);
return function (...$args) use ($originalGenerateText, $callback) {
$callback(...$args);
return $originalGenerateText(...$args);
};
});
Mock AI responses in tests:
AI::fake([
'openai' => [
'generateText' => fn($prompt) => 'Mock: ' . $prompt,
'embeddings' => fn($text) => [0.1, 0.2, 0.3],
],
]);
How can I help you explore Laravel packages today?