Installation
composer require subhashladumor1/laravel-ai-guard
php artisan vendor:publish --provider="SubhashLadumor\AiGuard\AiGuardServiceProvider" --tag="config"
Publish the config file to config/ai-guard.php and update your .env with:
AI_GUARD_ENABLED=true
AI_GUARD_DEFAULT_BUDGET=100 # in USD
AI_GUARD_CURRENCY=USD
First Use Case: Wrap an AI Call
Use the AiGuard facade to wrap your first AI SDK call:
use SubhashLadumor\AiGuard\Facades\AiGuard;
$response = AiGuard::execute(function () {
return \Laravel\AI\Facades\AI::complete('gpt-3.5-turbo', 'Explain Laravel AI Guard');
});
Verify Setup
Check the ai_guard_logs table for recorded usage:
php artisan tinker
>>> \SubhashLadumor\AiGuard\Facades\AiGuard::getUsageHistory();
Budget Enforcement
Define budgets per user/tenant in config/ai-guard.php:
'budgets' => [
'users' => [
'admin@example.com' => 50, // USD
],
'tenants' => [
'acme' => 200, // USD
],
],
Use middleware to auto-apply budgets:
\SubhashLadumor\AiGuard\Http\Middleware\EnforceAIBudget::class,
Dynamic Cost Estimation Estimate costs before execution:
$estimatedCost = AiGuard::estimateCost(
\Laravel\AI\Facades\AI::make('gpt-3.5-turbo')->prompt('Your prompt')
);
if ($estimatedCost > $user->ai_budget) {
abort(429, 'AI budget exceeded');
}
Rate Limiting Combine with Laravel’s rate limiting:
Route::middleware(['throttle:100,1', 'ai.guard'])->group(...);
Laravel\AI\Facades\AI (v12.x).SubhashLadumor\AiGuard\Contracts\CostCalculator for non-OpenAI LLMs.AiGuard::logManualUsage($cost, $model, $userId) for non-AI-SDK calls.AiGuard::webhook() events.// In a service class
public function generateReport(User $user, string $prompt)
{
$tenantBudget = config("ai-guard.budgets.tenants.{$user->tenant}");
return AiGuard::execute(function () use ($user, $prompt) {
return \Laravel\AI\Facades\AI::complete('gpt-4', $prompt)
->withBudget($tenantBudget)
->withUser($user);
});
}
Token vs. Cost Mismatch
config/ai-guard.php may become stale.AiGuard::syncPricing() to fetch live rates or extend CostCalculator to pull from an API.Budget Leaks
AiGuard::execute() bypasses budget checks.HandleIncomingAiRequests) to auto-wrap all AI routes.Concurrency Issues
AiGuard::execute(function () use ($aiCall) {
return DB::transaction(function () use ($aiCall) {
return $aiCall();
});
});
Logging Overhead
AiGuard::flushLogs() or disable logging in config/ai-guard.php for non-critical paths.php artisan ai-guard:logs --user=1 --limit=10
config/ai-guard.php for testing:
'pricing' => [
'gpt-3.5-turbo' => 0.001, // Test with $0.001/1k tokens
],
BudgetExceededException: Budget logic failed (check tenants vs. users keys).UnsupportedModelException: Model not in config/ai-guard.pricing.Custom Calculators Create a calculator for a new LLM (e.g., Anthropic):
namespace App\Services;
use SubhashLadumor\AiGuard\Contracts\CostCalculator;
class AnthropicCalculator implements CostCalculator
{
public function calculateCost(string $model, int $tokens): float
{
return match ($model) {
'claude-v1' => $tokens * 0.008,
default => throw new \InvalidArgumentException("Unsupported model: {$model}"),
};
}
}
Register it in config/ai-guard.php:
'calculators' => [
'anthropic' => \App\Services\AnthropicCalculator::class,
],
Webhook Events Listen for budget alerts:
AiGuard::onBudgetExceeded(function ($event) {
\Log::warning("Budget alert for user {$event->userId}: {$event->remaining} USD left");
// Send Slack/email notification
});
Slack/Email Alerts
Use Laravel Notifications with the AiGuard events:
AiGuard::onHighUsage(function ($event) {
$user = User::find($event->userId);
Notification::route('mail', $user->email)
->notify(new AIBudgetAlert($event->remaining));
});
USD is fully supported; extend CostCalculator for other currencies.AiGuard::withBudget($amount, now()->addDays(7)); // Weekly budget
0 to disable AI entirely for a user/tenant.How can I help you explore Laravel packages today?