DependencyInjectionError
pydantic_ai.errors.DependencyInjectionError
Stack trace
pydantic_ai.errors.DependencyInjectionError: Missing required dependency 'SomeDependency' for injection in Pydantic AI model
File "/app/main.py", line 42, in <module>
model = MyPydanticAIModel()
File "/usr/local/lib/python3.10/site-packages/pydantic_ai/__init__.py", line 120, in __init__
raise DependencyInjectionError(f"Missing required dependency '{dep}' for injection")
Why it happens
Pydantic AI uses dependency injection to provide runtime dependencies to Pydantic models. This error occurs when a required dependency is not registered or passed to the model, causing the injection mechanism to fail during instantiation.
Detection
Catch DependencyInjectionError exceptions during model creation and log the missing dependency name to identify configuration issues before runtime failures.
Causes & fixes
Required dependency not registered in the dependency container or context
Register the missing dependency in the Pydantic AI dependency container or pass it explicitly when creating the model instance.
Incorrect or missing type annotations on model fields expected for injection
Ensure all injectable fields have correct type annotations and are marked for injection according to Pydantic AI documentation.
Using an outdated or incompatible version of pydantic-ai that lacks proper injection support
Upgrade to a compatible pydantic-ai version that supports the required injection features.
Code: broken vs fixed
from pydantic_ai import PydanticAIModel
class MyModel(PydanticAIModel):
some_dep: SomeDependency # dependency injection expected
model = MyModel() # Raises DependencyInjectionError here import os
from pydantic_ai import PydanticAIModel, DependencyContainer
# Register dependency explicitly
container = DependencyContainer()
container.register(SomeDependency, SomeDependency())
class MyModel(PydanticAIModel):
some_dep: SomeDependency
model = MyModel(_dependencies=container) # Fixed: dependencies injected
print("Model instantiated successfully with dependencies") Workaround
Wrap model instantiation in try/except DependencyInjectionError, then manually instantiate missing dependencies and pass them as keyword arguments to the model constructor.
Prevention
Use a centralized dependency container and enforce strict registration of all injectable dependencies before model creation to avoid injection errors.