goodport / laravel-ai-resilience
Rate limiting and retries for Laravel AI agent prompts.
Requires
- php: ^8.3
- laravel/ai: ^1.4
- laravel/framework: ^12.62|^13.0
Requires (Dev)
- laravel/pint: ^1.26
- orchestra/testbench: ^10.6|^11.0
- phpunit/phpunit: ^11.5|^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-26 15:05:44 UTC
README
Rate limiting and retries for laravel/ai agent prompts.
The package adds two independent capabilities:
- a step middleware that limits how often a provider and model are called;
- a retry handler that repeats a failed
Agent::prompt()call.
Both are disabled by default.
Requirements
- PHP 8.3 or newer;
- Laravel 12.62 or newer, or Laravel 13;
laravel/ai1.4 or newer.
Scope
The package is designed and supported for Agent::prompt().
- Rate limiting is attached to the agent step middleware and is applied by prompt calls.
- Retries are implemented only around
Agent::prompt(). - Streaming, queueing, broadcasting, embeddings, images, transcription, reranking, files and audio are outside the scope. Their behavior is not guaranteed by this package.
Installation
composer require goodport/laravel-ai-resilience
Publish the configuration file:
php artisan vendor:publish --tag=ai-resilience-config
Two entry points
The entry points are independent:
- adding the middleware enables rate limiting but does not enable retries;
- using the retry handler enables retries but does not enable rate limiting.
If both are required, use both.
Rate limiting
Add the limiter to the agent middleware. The package provides an interface and a trait:
use Goodport\AiResilience\Limits\Concerns\HasRateLimitMiddleware; use Goodport\AiResilience\Limits\Contracts\HasRateLimit; use Laravel\Ai\Contracts\Agent; use Laravel\Ai\Promptable; final class ExampleAgent implements Agent, HasRateLimit { use Promptable; use HasRateLimitMiddleware; public function instructions(): string { return 'You are a helpful assistant.'; } }
If the agent already declares middleware, register the limiter manually:
use Goodport\AiResilience\Limits\RateLimitStep; public function middleware(): array { return [ // Middleware that may answer without calling the next layer goes first. RateLimitStep::class, // Other middleware. ]; }
Place any middleware that can return a response without calling the next layer before the limiter. In that case the limiter must not wait and must not consume a limit.
Retries
Resolve the handler and assign the agent:
use Goodport\AiResilience\Retries\AgentCallRetry; $response = app(AgentCallRetry::class) ->withAgent($agent) ->prompt('Summarize the document.');
The prompt() method accepts the same arguments as Laravel\Ai\Contracts\Agent::prompt():
prompt(
AgentInput|UserMessage|Decisions|string $prompt,
array $attachments = [],
Lab|array|string|null $provider = null,
?string $model = null,
?int $timeout = null,
): AgentResponse
Structured responses are returned unchanged: StructuredAgentResponse is not converted or rebuilt.
Configuration
return [ 'correlation' => [ 'context_key' => 'ai.resilience.correlation_id', ], 'limits' => [ 'enabled' => true, 'store' => 'redis', 'prefix' => 'acme-production-ai', 'scope_context_key' => 'ai.resilience.scope', 'default' => [ 'max_requests' => 60, 'per_seconds' => 60, 'min_interval_seconds' => 1, 'mode' => 'wait', 'max_wait_seconds' => 30, ], 'rules' => [ [ 'provider' => 'acme', 'min_interval_seconds' => 2, ], [ 'provider' => 'acme', 'model' => 'example.model/2026', 'max_requests' => 30, 'per_seconds' => 60, ], ], ], 'retries' => [ 'enabled' => true, 'attempts' => 3, 'base_delay_ms' => 500, 'multiplier' => 2.0, 'jitter' => 0.2, 'max_delay_ms' => 30000, 'max_duration_ms' => 120000, 'honor_retry_after' => true, ], ];
Rule matching
Rules are matched from the most specific to the least specific:
- provider and model;
- provider;
- default.
Each rule must declare a provider. A model-only rule is rejected.
The model may be any non-empty string. Dots and slashes in model names are plain characters and are not parsed as configuration keys.
Rules override individual fields. Missing fields are inherited from the less specific rule. Duplicate rules for the same provider and model, or for the same provider alone, are rejected.
Rate limit modes
wait— wait until the interval or the window allows the next request. The total wait is limited bymax_wait_seconds.fail— throwRateLimitExceededExceptionimmediately.
The limiter checks both constraints before changing anything. The interval cursor is advanced only when the request is ready to be sent. A blocked window does not move the interval cursor.
Rate limit key
The key is built as:
prefix:provider:model[:scope]
The provider and model are taken from the agent step. The optional scope is read from Laravel Context by scope_context_key:
use Illuminate\Support\Facades\Context; Context::add('ai.resilience.scope', 'tenant-42');
The scope may isolate a tenant, a user or another workload. The package does not allow callers to pass an arbitrary full key.
Storage
The limiter uses the Laravel cache store configured in limits.store. null uses the default cache store.
The chosen store must support cache locks. All standard Laravel stores do.
| Store | Sharing |
|---|---|
| array | one process only |
| file | one host only |
| database | multiple processes and hosts |
| Redis | multiple processes and hosts |
The database store requires the standard cache and cache_locks tables.
All calls must go through the middleware. If another part of the application uses RateLimiter or cache locks directly with the same keys, the package cannot guarantee shared atomicity with those calls.
Retries
Retries are performed only for temporary errors:
- timeouts;
- connection failures;
429responses;5xxresponses.
Authorization errors, invalid requests, insufficient credits, tool errors and unknown exceptions are not retried.
The attempt count includes the first attempt. The delay grows from base_delay_ms by multiplier, is capped by max_delay_ms, and receives a random spread controlled by jitter. A Retry-After response header takes priority when honor_retry_after is enabled, but the resulting pause is also capped by max_delay_ms. The total duration of all attempts and pauses is limited by max_duration_ms.
Retries are not performed when:
- the agent declares tools;
- the agent declares skills;
- provider tools are declared;
- runtime tools are present in the resolved prompt;
- the prompt is an approval continuation (
Decisions); - a tool has already been invoked during the current attempt.
Declared tools and skills are inspected directly only when they are arrays. Any other iterable is treated conservatively as potentially non-empty, so retries are disabled without consuming a generator or another lazy iterable.
Tool invocation detection is bound to the concrete invocationId of the attempt. Runtime tools and approvals are read from the PromptingAgent event. If the installed laravel/ai version does not expose the required event data, the package throws IncompatibleSdkException instead of silently allowing a retry.
Each retry is a new prompt() call, so each real attempt has its own invocationId and its own response.
Correlation
All attempts of one retry run share a correlation identifier.
- If the configured context key already contains a value, the package uses it and does not overwrite it.
- If the key is absent, the package generates an identifier, passes it to events and removes it after the run, including the exception path.
- Nested retry runs reuse the identifier of the outer run.
Set an existing identifier when the application already has one:
use Illuminate\Support\Facades\Context; Context::add('ai.resilience.correlation_id', $correlationId);
Events
The package dispatches Laravel events. It does not write logs.
RateLimitWait— the limiter is about to wait. Contains the key, provider, model, step number, invocation id, correlation id, interval wait, window wait and total wait.RetryScheduled— a retry is scheduled. Contains the failed attempt, delay, error information and correlation id.FinalFailure— the handler gives up. Contains the stop reason, attempts, error information and correlation id.
RateLimitExceededException is not converted into FinalFailure. It is a limiter decision, not a retry outcome, and is thrown directly.
Error information
ErrorInfo contains:
- the error kind (
Transient,RateLimited,Timeout,Authorization,Permanent); - the exception code;
- the HTTP status when available;
- the provider request id when available;
- the provider error code when available;
- the recommended pause from
Retry-After.
A timeout is recognized only from a reliable transport type or code. The package does not parse error message text.
Internal SDK retry
The SDK may retry a provider request once on its own when the provider returns a short Retry-After value (up to 10 seconds). That retry happens below agent middleware.
The limiter counts logical steps. Therefore, at most one additional HTTP request per step is not counted by the limiter. This is a documented limitation; the package does not try to observe or alter the internal SDK retry.
Configuration errors
Configuration is validated on first use, not during application boot. An invalid configuration does not break artisan, migrations or tests.
Use the check command to validate it explicitly:
php artisan ai-resilience:check
When rate limits are enabled, the command also resolves the configured cache store and verifies that it supports locks. When limits are disabled, the store is not touched.
Testing
composer test
composer format
Changelog
See CHANGELOG.md.
License
The package is open source software licensed under the MIT license.