К основному содержанию
скилл CX Codex

pydantic-ai-dependency-injection — скилл для Claude Code

Скилл pydantic-ai-dependency-injection показывает, как передавать базы данных, API-клиенты и контекст пользователя в PydanticAI через RunContext и deps_type.

Apache-2.0 141 установок ★ 89 обновлён 2026-09-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add existential-birds/beagle --skill pydantic-ai-dependency-injection -a claude-code
Открыть на GitHub

Что делает pydantic-ai-dependency-injection

Скилл разбирает внедрение зависимостей в агенты PydanticAI. Зависимости описываются через dataclass или Pydantic-модель, передаются в Agent через deps_type, а инструменты, инструкции и системные промпты получают их из RunContext[Deps].

Внутри есть примеры типизации Agent[Deps, OutputModel], запуска с deps=, агента без зависимостей и полного сценария с AsyncClient. Для тестов показан TestModel вместе с agent.override и моками. Каждый путь agent.run или run_sync, который использует зависимости, должен передавать объект с полями и типами из deps_type.

Какие задачи решает

  • передать соединение с базой данных в инструмент агента
  • добавить API-клиент в контекст запуска
  • получить user context в инструкции агента
  • проверить агента с моками через agent.override
  • типизировать зависимости и результат агента

Примеры запросов агенту

  • Настрой внедрение зависимостей в агенте PydanticAI через RunContext и deps_type.
  • Покажи, как передать базу данных, API-клиент и user_id в инструмент агента.
  • Добавь тест агента с TestModel, моками зависимостей и agent.override.

Как установить pydantic-ai-dependency-injection

1Через Skills CLI (Vercel)

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

2Вручную: положить файлы

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

Папка скилла целиком; для одного проекта — .claude/skills/pydantic-ai-dependency-injection/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о pydantic-ai-dependency-injection

Как установить pydantic-ai-dependency-injection в Claude Code?

Выполните npx skills add existential-birds/beagle --skill pydantic-ai-dependency-injection -a claude-code. Скилл будет доступен в ~/.claude/skills/pydantic-ai-dependency-injection/SKILL.md.

Что делает pydantic-ai-dependency-injection?

Он объясняет, как передавать внешние ресурсы в PydanticAI через deps_type, RunContext и параметр deps. Примеры охватывают инструменты, инструкции, системные промпты и статическую типизацию.

Как тестировать зависимости агента?

Создайте зависимости с моками и передайте их вместе с TestModel в agent.override. Поля и типы тестовых зависимостей должны совпадать с рабочим Deps для используемых инструментов.

Исходный текст

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

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
spring-boot-dependency-injection giuseppe-trisciuoglio Скилл spring-boot-dependency-injection внедряет паттерны внедрения зависимостей через конструктор в Spring Boot. Он помогает избавиться от field injection и настроить выбор бинов через @Primary и @Qualifier. CX Codex +1 4 000установок dependency-injection-patterns Aaronontheweb Скилл dependency-injection-patterns для Claude Code группирует регистрации зависимостей ASP.NET Core в методы расширения Add*. Он включается при организации DI и подготовке конфигурации для тестов. CX Codex +1 715установок golang-dependency-injection samber Скилл golang-dependency-injection помогает организовать внедрение зависимостей в Go-проектах: от ручных конструкторов до библиотек wire, dig, fx и do. CX Codex +1 41 700установок dependency-injection codewithmukesh Скилл внедряет паттерны dependency injection для .NET 10: выбор времён жизни сервисов, keyed services, декораторы через Scrutor и защиту от captive dependency. CX Codex +1 4 000установок migrating-deep-agents-to-pydantic-ai-harness pydantic Скилл migrating-deep-agents-to-pydantic-ai-harness для Claude Code переносит Python-приложения LangChain Deep Agents на Pydantic AI и Pydantic AI Harness. Работает с контрактами middleware, памяти, субагентов и sandbox. CX Codex +1 234установок dotnet-csharp-dependency-injection wshaddix Скилл dotnet-csharp-dependency-injection помогает настраивать внедрение зависимостей в .NET через MS DI: времена жизни, ключи, декораторы и фоновые сервисы. CX Codex +1 125установок

Из того же набора68

Весь набор →
pydantic-ai-testing Скилл pydantic-ai-testing помогает писать тесты для агентов PydanticAI: подменять ответы модели, проверять вызовы инструментов и воспроизводить записанные API-запросы. CX Codex +1 146установок adr-decision-extraction Скилл adr-decision-extraction извлекает архитектурные решения из чатов и расшифровок, чтобы подготовить материал для ADR. Он распознаёт выбор технологий, компромиссы и явные метки. CX Codex +1 144установок deepagents-implementation Скилл deepagents-implementation для Claude Code даёт рецепты сборки агентов на Deep Agents: фабрика create_deep_agent, файловые бэкенды, субагенты и стриминг LangGraph. CX Codex +1 142установок llm-judge Скилл llm-judge сравнивает две и более реализации одной задачи по файлу спецификации: собирает факты, ставит оценки по пяти измерениям и выдаёт отчёт с победителем. CX Codex +1 141установок watchos-code-review Скилл watchos-code-review для Claude Code проверяет watchOS-код на ошибки жизненного цикла, осложнений, WatchConnectivity и ограничения производительности. CX Codex +1 137установок swiftdata-code-review Скилл swiftdata-code-review проверяет код SwiftData на ошибки в моделях, предикатах, миграциях и конкурентности. Запускается при ревью файлов со связками @Model и @Query. CX Codex +1 136установок howto-docs Скилл howto-docs помогает писать пошаговые how-to-гайды под конкретную задачу: с предусловиями, шагами, проверкой результата и разбором типичных проблем. CX Codex +1 135установок deepagents-code-review Скилл deepagents-code-review проверяет код на create_deep_agent: ловит забытый checkpointer, относительные пути и бэкенды без хранилища. CX Codex +1 134установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой