Exceptions¶
Custom exceptions for middleware control flow and error reporting. All exceptions
inherit from MiddlewareError, making it easy to catch any middleware-related error
with a single except clause.
The blocking exceptions (InputBlocked, ToolBlocked, OutputBlocked) are the
primary way middleware communicates that a request should be rejected. Raise them from
any hook to stop processing immediately.
MiddlewareError¶
pydantic_ai_middleware.MiddlewareError
¶
Base exception for all middleware errors.
MiddlewareConfigError¶
pydantic_ai_middleware.exceptions.MiddlewareConfigError
¶
Bases: MiddlewareError
Raised when middleware configuration is invalid.
Raised when middleware configuration is invalid (unknown type names, bad predicate specs, malformed config files).
InputBlocked¶
pydantic_ai_middleware.InputBlocked
¶
Bases: MiddlewareError
Raised when input is blocked by middleware.
Source code in src/pydantic_ai_middleware/exceptions.py
Raised to block input processing.
from pydantic_ai_middleware import InputBlocked
raise InputBlocked("Content not allowed")
raise InputBlocked() # Uses default message
ToolBlocked¶
pydantic_ai_middleware.ToolBlocked
¶
Bases: MiddlewareError
Raised when a tool call is blocked by middleware.
Source code in src/pydantic_ai_middleware/exceptions.py
Raised to block a tool call.
from pydantic_ai_middleware import ToolBlocked
raise ToolBlocked("dangerous_tool", "Not authorized")
raise ToolBlocked("tool_name") # Uses default reason
OutputBlocked¶
pydantic_ai_middleware.OutputBlocked
¶
Bases: MiddlewareError
Raised when output is blocked by middleware.
Source code in src/pydantic_ai_middleware/exceptions.py
Raised to block output.
from pydantic_ai_middleware import OutputBlocked
raise OutputBlocked("Contains sensitive information")
raise OutputBlocked() # Uses default message
BudgetExceededError¶
pydantic_ai_middleware.exceptions.BudgetExceededError
¶
Bases: MiddlewareError
Raised when accumulated cost exceeds the configured budget limit.
Source code in src/pydantic_ai_middleware/exceptions.py
__init__(cost, budget)
¶
Initialize the exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost
|
float
|
The current accumulated cost in USD. |
required |
budget
|
float
|
The configured budget limit in USD. |
required |
Source code in src/pydantic_ai_middleware/exceptions.py
| Python | |
|---|---|
Raised when accumulated cost exceeds the configured budget limit. Used by
CostTrackingMiddleware.
from pydantic_ai_middleware.exceptions import BudgetExceededError
# Raised automatically by CostTrackingMiddleware
# You can also catch it:
try:
result = await agent.run("prompt")
except BudgetExceededError as e:
print(f"Over budget: ${e.cost:.4f} >= ${e.budget:.4f}")
ParallelExecutionFailed¶
pydantic_ai_middleware.exceptions.ParallelExecutionFailed
¶
Bases: MiddlewareError
Raised when parallel middleware execution fails.
Contains information about which middleware failed and which succeeded, allowing for detailed error handling and debugging.
Source code in src/pydantic_ai_middleware/exceptions.py
__init__(errors, results=None, message='Parallel middleware execution failed')
¶
Initialize the exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errors
|
list[Exception]
|
List of exceptions from failed middleware. |
required |
results
|
list[Any] | None
|
Optional list of successful results (for partial failures). |
None
|
message
|
str
|
Human-readable error message. |
'Parallel middleware execution failed'
|
Source code in src/pydantic_ai_middleware/exceptions.py
Raised when parallel middleware execution fails. Contains the list of errors and any successful results.
GuardrailTimeout¶
pydantic_ai_middleware.exceptions.GuardrailTimeout
¶
Bases: MiddlewareError
Raised when an async guardrail times out.
This can occur when a guardrail takes longer than the configured timeout while running concurrently with the agent.
Source code in src/pydantic_ai_middleware/exceptions.py
__init__(guardrail_name, timeout)
¶
Initialize the exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guardrail_name
|
str
|
Name/identifier of the guardrail that timed out. |
required |
timeout
|
float
|
The timeout value in seconds that was exceeded. |
required |
Source code in src/pydantic_ai_middleware/exceptions.py
Raised when an async guardrail exceeds its configured timeout.
MiddlewareTimeout¶
pydantic_ai_middleware.exceptions.MiddlewareTimeout
¶
Bases: MiddlewareError
Raised when a middleware hook exceeds its configured timeout.
Source code in src/pydantic_ai_middleware/exceptions.py
__init__(middleware_name, timeout, hook_name='')
¶
Initialize the exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
middleware_name
|
str
|
Name/class of the middleware that timed out. |
required |
timeout
|
float
|
The timeout value in seconds that was exceeded. |
required |
hook_name
|
str
|
The specific hook that timed out. |
''
|
Source code in src/pydantic_ai_middleware/exceptions.py
Raised when a middleware hook exceeds its per-middleware timeout.
AggregationFailed¶
pydantic_ai_middleware.exceptions.AggregationFailed
¶
Bases: MiddlewareError
Raised when parallel results cannot be aggregated.
This occurs when the aggregation strategy cannot produce a valid result from the parallel middleware outputs.
Source code in src/pydantic_ai_middleware/exceptions.py
__init__(strategy, reason, errors=None)
¶
Initialize the exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
AggregationStrategy
|
The aggregation strategy that failed. |
required |
reason
|
str
|
Explanation of why aggregation failed. |
required |
errors
|
list[Exception] | None
|
Optional list of underlying errors. |
None
|
Source code in src/pydantic_ai_middleware/exceptions.py
Raised when parallel results cannot be aggregated according to the chosen strategy.