
Pydantic Ai Dependency Injection
This shows you how to thread external resources like database connections, API clients, and user context into PydanticAI agents through the RunContext pattern. You define a deps_type dataclass, access it via ctx.deps in your tools and system prompts, then pass the actual dependencies at runtime when you call agent.run(). The type safety is real: Agent[DepsType, OutputType] gives you full static checking across tools, instructions, and run calls. Most useful when your agent needs to hit external services or maintain per-request state like user sessions. The gates section is smart about verifying every ctx.deps access maps to an actual field and your tests don't mock away half the dependencies your tools actually touch.
- skills.sh installs
- 141
- GitHub stars
- 87
- last updated
- Aug 21, 2026
Install
$ npx -y skills add existential-birds/beagle --skill pydantic-ai-dependency-injection --agent claude-codeInstalls into .claude/skills of the current project.
Files
PydanticAI Dependency Injection
Core Pattern
Dependencies flow through RunContext:
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
@dataclass
class Deps:
db: DatabaseConn
api_client: HttpClient
user_id: int
agent = Agent(
'openai:gpt-4o',
deps_type=Deps, # Type for static analysis
)
@agent.tool
async def get_user_balance(ctx: RunContext[Deps]) -> float:
"""Get the current user's account balance."""
return await ctx.deps.db.get_balance(ctx.deps.user_id)
# At runtime, provide deps
result = await agent.run(
'What is my balance?',
deps=Deps(db=db_conn, api_client=client, user_id=123)
)
Defining Dependencies
Use dataclasses or Pydantic models:
from dataclasses import dataclass
from pydantic import BaseModel
# Dataclass (recommended for simplicity)
@dataclass
class Deps:
db: DatabaseConnection
cache: CacheClient
user_context: UserContext
# Pydantic model (if you need validation)
class Deps(BaseModel):
api_key: str
endpoint: str
timeout: int = 30
Accessing Dependencies
In tools and instructions:
Sponsors
Details
- Repository
- github.com/existential-birds/beagle
- Categories
- Backend & APIs, AI & Agent Building, Python, Databases
- First seen
- Jun 3, 2026
More from existential-birds/beagle
All 40- Deepagents Implementation140
- Deepagents Code Review132
- Github Projects120
- Pydantic Ai Model Integration120
- React Flow1.3K
- Python Code Review928
- Langgraph Code Review887
- Tailwind V4817
- React Flow Advanced643
- React Router V7577
- React Flow Architecture536
- Vitest Testing471
- Docling431
- Fastapi Code Review387
- React Flow Implementation374
- Shadcn Ui356
- React Flow Code Review324
- Langgraph Architecture282
- Swiftui Code Review273
- Tutorial Docs271
- Bubbletea Code Review265
- Zustand State258
- Adr Writing250
- Dagre React Flow247