Skip to main content
skill CX Codex

pydantic-ai-dependency-injection — Claude Code skill: DI

pydantic-ai-dependency-injection — a skill for wiring databases, API clients, and user context into PydanticAI agents with RunContext and deps_type.

Apache-2.0 141 installs ★ 89 updated 2026-09-15

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add existential-birds/beagle --skill pydantic-ai-dependency-injection -a claude-code
Open on GitHub

What pydantic-ai-dependency-injection does

This skill explains dependency injection for PydanticAI agents. Define dependencies with a dataclass or Pydantic model, declare them through deps_type, then read them in tools, instructions, and system prompts via RunContext[Deps].

The examples cover typed Agent[Deps, OutputModel] declarations, runs with deps=, agents with no dependencies, and an async weather client. Testing uses TestModel, mocked dependency objects, and agent.override. Any agent.run or run_sync path that reaches a dependency-based tool must receive a value whose fields and types match deps_type.

What it helps with

  • pass a database connection into an agent tool
  • provide an API client through the run context
  • add user context to agent instructions
  • test tools with mocked dependencies
  • type-check agent dependencies and output

Example prompts for the agent

  • Set up dependency injection in a PydanticAI agent with RunContext and deps_type.
  • Show how to pass a database, an API client, and user_id to an agent tool.
  • Test this agent with TestModel, mocked dependencies, and agent.override.

How to install pydantic-ai-dependency-injection

1Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill pydantic-ai-dependency-injection -a claude-code

2Manually: put the files in place

~/.claude/skills/pydantic-ai-dependency-injection/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/pydantic-ai-dependency-injection/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about pydantic-ai-dependency-injection

How do I install pydantic-ai-dependency-injection in Claude Code?

Run npx skills add existential-birds/beagle --skill pydantic-ai-dependency-injection -a claude-code. The skill is then available at ~/.claude/skills/pydantic-ai-dependency-injection/SKILL.md.

What does pydantic-ai-dependency-injection do?

It shows how PydanticAI agents receive external resources through deps_type, RunContext, and the deps argument. The examples cover tools, instructions, system prompts, and static typing.

How are dependency-based agents tested?

Build a dependency object with mocks, then pass it with TestModel to agent.override. The test object needs the same fields and types as the production Deps for the tools being exercised.

Source text

SKILL.md · Apache-2.0
---
name: pydantic-ai-dependency-injection
description: 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.
---

# 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')
```

## Gates

Run these in order before treating the agent as correct; each step has an objective pass condition.

1. **Deps cover every access** — Collect every `ctx.deps.<attr>` (and nested uses) from tools, `@agent.instructions`, and `@agent.system_prompt`. **Pass:** each `<attr>` exists on `deps_type` (and static checking passes if you use mypy/pyright on `Agent[DepsType, …]`).
2. **Every run that needs deps gets them** — **Pass:** each `agent.run` / `run_sync` path that executes those tools passes `deps=` whose type matches `deps_type` (no `None` unless the agent truly has no deps).
3. **Tests pin deps shape** — **Pass:** tests that use `agent.override` pass a `deps=` value with the same fields/types as production `Deps` (not a partial mock unless tools under test never touch missing fields).

## 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 after

© existential-birds · Apache-2.0 · existential-birds/beagle

Similar skills

All skills for Agent setup: memory, context, orchestration →

From the same set68

The whole set →
pydantic-ai-testing pydantic-ai-testing is a Claude Code skill for testing PydanticAI agents with mocked model responses, recorded API interactions, and inline snapshots. CX Codex +1 146installs adr-decision-extraction The adr-decision-extraction skill pulls architectural decisions from chats and session transcripts before ADR writing. It identifies technology choices, trade-offs, and explicit decision tags. CX Codex +1 144installs deepagents-implementation deepagents-implementation is a Claude Code skill with recipes for building agents on Deep Agents: create_deep_agent, file backends, subagents and LangGraph streaming. CX Codex +1 142installs llm-judge llm-judge ranks two or more implementations of the same task against a spec file: facts first, then scores across five dimensions, then a report naming the winner. CX Codex +1 141installs watchos-code-review The watchos-code-review skill reviews watchOS code for lifecycle, complications, WatchConnectivity, and resource limits. Use it when checking WatchKit or SwiftUI app code. CX Codex +1 137installs swiftdata-code-review swiftdata-code-review reviews SwiftData code for model relationships, query predicates, actor concurrency, and schema migrations. Works on .swift files. CX Codex +1 136installs howto-docs The howto-docs skill shapes task-focused how-to guides with prerequisites, actionable steps, result checks, and troubleshooting for readers who already know the product. CX Codex +1 135installs deepagents-code-review deepagents-code-review reviews Deep Agents code and flags what breaks agents at runtime: interrupt_on with no checkpointer, backends with no store. CX Codex +1 134installs

Project sponsors

Companies that keep this analytics open