pydantic-ai-dependency-injection
Implement dependency injection in PydanticAI agents using RunContext and deps_type. Use when agents need database connections, API clients, user context, or any external resources.
Best use case
pydantic-ai-dependency-injection is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Implement dependency injection in PydanticAI agents using RunContext and deps_type. Use when agents need database connections, API clients, user context, or any external resources.
Teams using pydantic-ai-dependency-injection should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/pydantic-ai-dependency-injection/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How pydantic-ai-dependency-injection Compares
| Feature / Agent | pydantic-ai-dependency-injection | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Implement dependency injection in PydanticAI agents using RunContext and deps_type. Use when agents need database connections, API clients, user context, or any external resources.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
AI Agents for Freelancers
Browse AI agent skills for freelancers handling client research, proposals, outreach, delivery systems, documentation, and repeatable admin work.
AI Agents for Marketing
Discover AI agents for marketing workflows, from SEO and content production to campaign research, outreach, and analytics.
SKILL.md Source
# PydanticAI Dependency Injection
## Core Pattern
Dependencies flow through `RunContext`:
```python
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:
```python
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:
```python
@agent.tool
async def query_database(ctx: RunContext[Deps], query: str) -> list[dict]:
"""Run a database query."""
return await ctx.deps.db.execute(query)
@agent.instructions
async def add_user_context(ctx: RunContext[Deps]) -> str:
user = await ctx.deps.db.get_user(ctx.deps.user_id)
return f"User name: {user.name}, Role: {user.role}"
@agent.system_prompt
def add_permissions(ctx: RunContext[Deps]) -> str:
return f"User has permissions: {ctx.deps.permissions}"
```
## Type Safety
Full type checking with generics:
```python
# Explicit agent type annotation
agent: Agent[Deps, OutputModel] = Agent(
'openai:gpt-4o',
deps_type=Deps,
output_type=OutputModel,
)
# Now these are type-checked:
# - ctx.deps in tools is typed as Deps
# - result.output is typed as OutputModel
# - agent.run() requires deps: Deps
```
## No Dependencies Pattern
When you don't need dependencies:
```python
# Option 1: No deps_type (defaults to NoneType)
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello') # No deps needed
# Option 2: Explicit None for type checker
agent: Agent[None, str] = Agent('openai:gpt-4o')
result = agent.run_sync('Hello', deps=None)
# In tool_plain, no context access
@agent.tool_plain
def simple_calc(a: int, b: int) -> int:
return a + b
```
## Complete Example
```python
from dataclasses import dataclass
from httpx import AsyncClient
from pydantic import BaseModel
from pydantic_ai import Agent, RunContext
@dataclass
class WeatherDeps:
client: AsyncClient
api_key: str
class WeatherReport(BaseModel):
location: str
temperature: float
conditions: str
agent: Agent[WeatherDeps, WeatherReport] = Agent(
'openai:gpt-4o',
deps_type=WeatherDeps,
output_type=WeatherReport,
instructions='You are a weather assistant.',
)
@agent.tool
async def get_weather(
ctx: RunContext[WeatherDeps],
city: str
) -> dict:
"""Fetch weather data for a city."""
response = await ctx.deps.client.get(
f'https://api.weather.com/{city}',
headers={'Authorization': ctx.deps.api_key}
)
return response.json()
async def main():
async with AsyncClient() as client:
deps = WeatherDeps(client=client, api_key='secret')
result = await agent.run('Weather in London?', deps=deps)
print(result.output.temperature)
```
## Override for Testing
```python
from pydantic_ai.models.test import TestModel
# Create mock dependencies
mock_deps = Deps(
db=MockDatabase(),
api_client=MockClient(),
user_id=999
)
# Override model and deps for testing
with agent.override(model=TestModel(), deps=mock_deps):
result = agent.run_sync('Test prompt')
```
## Best Practices
1. **Keep deps immutable**: Use frozen dataclasses or Pydantic models
2. **Pass connections, not credentials**: Deps should hold initialized clients
3. **Type your agents**: Use `Agent[DepsType, OutputType]` for full type safety
4. **Scope deps appropriately**: Create deps at the start of a request, close afterRelated Skills
prompt-injection-defense
Harden agent sessions against prompt injection from untrusted content. Use when the agent reads web search results, emails, downloaded files, PDFs, or any external text that could contain adversarial instructions. Provides content scanning, memory write guardrails (scan → lint → accept or quarantine), untrusted content tagging, and canary detection. Also use when setting up new tools that ingest external content (email checkers, RSS readers, web scrapers).
dependency-tracker
每周依赖检查。检查 Node.js、npm 版本和全局包是否有可用更新。触发时机:cron 定时任务或手动调用。
indirect-prompt-injection
Detect and reject indirect prompt injection attacks when reading external content (social media posts, comments, documents, emails, web pages, user uploads). Use this skill BEFORE processing any untrusted external content to identify manipulation attempts that hijack goals, exfiltrate data, override instructions, or social engineer compliance. Includes 20+ detection patterns, homoglyph detection, and sanitization scripts.
skill-dependency-chain-auditor
Helps audit transitive skill dependency chains in agent compositions — catching the class of risk where a skill's direct dependencies appear safe but a dependency-of-a-dependency introduces a vulnerability that propagates up the entire chain.
pydantic-ai-tool-system
Register and implement PydanticAI tools with proper context handling, type annotations, and docstrings. Use when adding tool capabilities to agents, implementing function calling, or creating agent actions.
pydantic-ai-testing
Test PydanticAI agents using TestModel, FunctionModel, VCR cassettes, and inline snapshots. Use when writing unit tests, mocking LLM responses, or recording API interactions.
pydantic-ai-model-integration
Configure LLM providers, use fallback models, handle streaming, and manage model settings in PydanticAI. Use when selecting models, implementing resilience, or optimizing API calls.
pydantic-ai-common-pitfalls
Avoid common mistakes and debug issues in PydanticAI agents. Use when encountering errors, unexpected behavior, or when reviewing agent implementations.
pydantic-ai-agent-creation
Create PydanticAI agents with type-safe dependencies, structured outputs, and proper configuration. Use when building AI agents, creating chat systems, or integrating LLMs with Pydantic validation.
dependency-auditor
Dependency Auditor
dependency-upgrade-briefing
解释依赖升级的收益、风险、回滚方案与对业务的影响。;use for dependencies, upgrade, risk workflows;do not use for 伪造上游 changelog, 替代兼容性测试.
dependency-map-builder
梳理跨团队依赖、关键路径、脆弱节点和催办节奏,输出文本依赖图与风险链。;use for dependency, coordination, risk workflows;do not use for 替代甘特图工具, 直接修改项目系统.