RateLimit
Rejects a run once a key exceeds its request rate within a sliding window.
Parameters
Section titled “Parameters”| Parameter | Type | Default | Description |
|---|---|---|---|
max_requests |
int |
required | Requests allowed per window (must be > 0) |
window_seconds |
float |
60.0 |
Window length |
key |
Callable[[RunContext], str] | None |
None |
Derives the bucket from the run context. Without it, one global bucket is used |
store |
RateLimitStore |
process-wide store | Counter storage. Pass your own to isolate counters |
on_fail |
'raise' | 'warn' |
'raise' |
Raise InputBlocked or log and continue |
If the key function raises, the exception propagates out of agent.run().
Examples
Section titled “Examples”from dataclasses import dataclass
from pydantic_ai import Agentfrom pydantic_ai_guardrails import InputBlocked, RateLimit
@dataclassclass Deps: user_id: str
agent = Agent( 'openai:gpt-4o', deps_type=Deps, capabilities=[RateLimit(max_requests=10, window_seconds=60, key=lambda ctx: ctx.deps.user_id)],)
try: agent.run_sync('Hello', deps=Deps(user_id='u_123'))except InputBlocked as e: print(e.reason) # rate limit exceeded: 10/10 per 60sIsolated counters
Section titled “Isolated counters”from pydantic_ai_guardrails import RateLimit, RateLimitStore
store = RateLimitStore()RateLimit(max_requests=5, window_seconds=1, store=store)RateLimitStore is in-memory and per-process. For limits across several workers, subclass it and implement check_and_increment(key, max_requests, window_seconds) -> tuple[bool, int] against shared storage such as Redis.
Failure behaviour
Section titled “Failure behaviour”on_fail='raise': raisesInputBlocked.on_fail='warn': logs and continues. The request is not counted when it is over the limit.