Most frameworks make it hard to swap out components like the retriever or the model provider for testing. Does Pydantic AI and its dependency injection system make it easier to mock these services? I want to ensure our RAG pipeline is fully unit-testable before we push to production. We are currently using a mix of OpenAI and local models and need flexibility.
3 answers
This is actually where Pydantic AI shines brightest compared to something like LangChain. The deps argument in the agent allows you to define a specific type for your dependencies. When you're running in production, you pass in your real database connection or API client. For unit tests, you just pass in a mock object that matches the type. Since everything is strictly typed, your IDE will even tell you if your mock is missing a method. This approach allowed us to reach 90% test coverage on our AI agents, something we found nearly impossible with other libraries.
Does this dependency injection pattern in Pydantic AI work well when you have nested agents that all need different services?
It makes the transition from local dev to cloud environments so much smoother. No more messy environment variables everywhere.
Exactly, Ruth. Using Pydantic AI means your code stays clean and your tests stay reliable, which is vital for any serious data science project.
Yes, you can pass the main context down to sub-agents or define specific dependencies for each. It’s very flexible because it’s just standard Python object-oriented programming.