Registry / llm-agents / pydantic-ai-middleware

pydantic-ai-middleware

JSON →
library0.2.4pypypiunverified

`pydantic-ai-middleware` was a library providing a simple middleware layer for Pydantic-AI agents, allowing for `before_run`/`after_run` hooks and other lifecycle management without imposing strict guardrails. The last version of this package was `0.2.4`. As of version `0.3.0`, the package was renamed to `pydantic-ai-shields`, and its core middleware functionality was integrated directly into `pydantic-ai` v1.71+.

pip install pydantic-ai-middleware==0.2.4
INSTALL
IMPORT
SIG · PYDANTIC-AI-MIDDLE
P
pydantic-ai-middleware
llm-agentspythonv0.2.4
Install
4.8s avg
Import
2104ms
Disk
44MB
Pass rate
8/ 10
Env Coverage8 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.2.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✓ —
✓ 5.8s
py 3.11
✓ —
✓ 4.9s
py 3.12
✓ —
✓ 4.4s
py 3.13
✓ —
✓ 4.3s
py 3.9
✕ build_error
✕ build_error
44MB installed
● package 44MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MiddlewareAgent
from pydantic_ai_middleware import MiddlewareAgent
from pydantic_ai_middleware import MiddlewareAgent

This quickstart demonstrates how to wrap a `pydantic-ai` agent with custom middleware using `MiddlewareAgent` and `AgentMiddleware` from `pydantic-ai-middleware` v0.2.4. It defines a simple middleware to log before and after agent execution.

import os from pydantic_ai import PydanticAI from pydantic_ai.agents import Agent from pydantic_ai_middleware.agent import MiddlewareAgent from pydantic_ai_middleware.middleware import AgentMiddleware import asyncio class MyCustomMiddleware(AgentMiddleware): async def before_run(self, agent: Agent, input_data: str, **kwargs): print(f"Middleware: Before run with input: {input_data}") return input_data async def after_run(self, agent: Agent, output_data: str, **kwargs): print(f"Middleware: After run with output: {output_data}") return output_data class MyAgent(Agent): def run(self, topic: str) -> str: """Generate a short story about the given topic.""" return f"A story about {topic}..." ai = PydanticAI( api_key=os.environ.get("OPENAI_API_KEY", "sk-DUMMY"), # Use a dummy key if not set model="gpt-3.5-turbo", ) my_agent = MyAgent(ai=ai) middleware_agent = MiddlewareAgent( wrapped_agent=my_agent, middleware=[MyCustomMiddleware()] ) async def main(): print("\n--- Running Middleware Agent ---") result = await middleware_agent.run("a brave knight") print(f"Agent final result: {result}") print("--------------------------------") if __name__ == "__main__": asyncio.run(main())
Debug
Known issues
breakingThe `pydantic-ai-middleware` package has been renamed to `pydantic-ai-shields` as of version `0.3.0`. The core middleware functionality (`MiddlewareAgent`, `AgentMiddleware`) has been removed from this package and integrated directly into `pydantic-ai` v1.71+.
fix
For new projects, use `pydantic-ai-shields` for guardrails or `pydantic-ai` v1.71+ for native agent middleware. For existing projects, downgrade to `pydantic-ai-middleware<0.3.0` or migrate to the new `pydantic-ai` native middleware.
affects: >=0.3.0
deprecatedThe `pydantic-ai` dependency was replaced with `pydantic-ai-slim` in version `0.2.2` to reduce dependency bloat. While `pydantic-ai` still works with older versions of `pydantic-ai-middleware`, using `pydantic-ai-slim` is recommended.
fix
Ensure `pydantic-ai-slim` is installed instead of `pydantic-ai`. Imports for `pydantic_ai.*` remain compatible.
affects: 0.2.2+
gotchaInstances of `MiddlewareAgent` will fail to initialize with `AttributeError: Can't instantiate abstract class MiddlewareAgent with abstract method description` when used with `pydantic-ai` versions that introduced `description` as an abstract property on `AbstractAgent` (e.g., `pydantic-ai-slim` >= 1.73.0).
fix
Upgrade `pydantic-ai-middleware` to version `0.2.4` or higher. If unable to upgrade, you may need to downgrade `pydantic-ai-slim` to a version that predates the `description` abstract property.
affects: 0.2.0 - 0.2.3
gotchaWhen using `MiddlewareAgent.iter()` or `run_stream()`, `after_run` and `on_error` lifecycle hooks were not invoked in `AgentMiddleware`, making post-processing or error handling impossible for streaming operations.
fix
Upgrade `pydantic-ai-middleware` to version `0.2.3` or higher to ensure all middleware hooks are correctly triggered during streaming operations.
affects: 0.2.0 - 0.2.2
Upgrade
Version history
0.2.4latest on PyPI · released Mar 19, 2026
Audit
Dependencies
pydantic-ai-slimrequiredCore dependency for Pydantic-AI agent functionalities. Replaced `pydantic-ai` in v0.2.2.
genai-pricesoptionalRequired for `CostTrackingMiddleware` to calculate USD costs.
Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources
pydantic-ai-middleware — pip install pydantic-ai-middleware · libregistry