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

pydantic-ai-agent-creation — скилл для Claude Code

Скилл pydantic-ai-agent-creation помогает создавать типобезопасных агентов на PydanticAI: со структурированным выводом, зависимостями и настройками модели. Нужен при сборке AI-агентов и чат-систем.

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

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

Что делает pydantic-ai-agent-creation

Скилл подсказывает, как объявлять Agent с моделью в формате provider:model-name, задавать output_type через модели Pydantic и подключать зависимости через deps_type. В примерах есть провайдеры OpenAI, Anthropic и Google, а также настройки temperature, max_tokens, retries, name и end_strategy.

Отдельно разобраны асинхронный run, синхронный run_sync и потоковый run_stream. Для инструкций доступны статический текст, динамический декоратор @agent.instructions и system_prompt; для внешних сервисов показан типизированный объект зависимостей.

Перед использованием в рабочем коде скилл предлагает проверить обычный вызов, соответствие структурированного ответа схеме и передачу deps. При заданном deps_type вызов без deps= не пройдёт проверку типов.

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

  • создать агента PydanticAI с типизированными зависимостями
  • получить ответ модели в виде Pydantic-схемы
  • настроить повторы после ошибок валидации
  • выбрать синхронный, асинхронный или потоковый запуск
  • проверить агента перед подключением к рабочему коду

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

  • Создай агента PydanticAI с output_type=CityInfo и проверь структурированный ответ.
  • Настрой агент с deps_type=MyDeps, передай зависимости через deps= и добавь динамические инструкции.
  • Покажи асинхронный запуск через await agent.run(...) и потоковый вывод через run_stream.

Как установить pydantic-ai-agent-creation

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill pydantic-ai-agent-creation -a claude-code

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

~/.claude/skills/pydantic-ai-agent-creation/SKILL.md

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

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

Вопросы о pydantic-ai-agent-creation

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

Выполните npx skills add existential-birds/beagle --skill pydantic-ai-agent-creation -a claude-code, затем проверьте файл ~/.claude/skills/pydantic-ai-agent-creation/SKILL.md.

Что делает pydantic-ai-agent-creation?

Скилл объясняет создание агентов PydanticAI с типизированными зависимостями, проверяемым выводом, настройками провайдера и несколькими способами запуска.

Как проверить агента со структурированным выводом?

Задайте output_type, запросите ответ по схеме и убедитесь, что result.output стал экземпляром модели Pydantic. Повторные ошибки валидации требуют уточнить инструкции или увеличить retries.

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

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

# Creating PydanticAI Agents

## Quick Start

```python
from pydantic_ai import Agent

# Minimal agent (text output)
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')
print(result.output)  # str
```

## Model Selection

Model strings follow `provider:model-name` format:

```python
# OpenAI
agent = Agent('openai:gpt-4o')
agent = Agent('openai:gpt-4o-mini')

# Anthropic
agent = Agent('anthropic:claude-sonnet-4-5')
agent = Agent('anthropic:claude-haiku-4-5')

# Google
agent = Agent('google-gla:gemini-2.0-flash')
agent = Agent('google-vertex:gemini-2.0-flash')

# Others: groq:, mistral:, cohere:, bedrock:, etc.
```

## Structured Outputs

Use Pydantic models for validated, typed responses:

```python
from pydantic import BaseModel
from pydantic_ai import Agent

class CityInfo(BaseModel):
    city: str
    country: str
    population: int

agent = Agent('openai:gpt-4o', output_type=CityInfo)
result = agent.run_sync('Tell me about Paris')
print(result.output.city)  # "Paris"
print(result.output.population)  # int, validated
```

## Agent Configuration

```python
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings

agent = Agent(
    'openai:gpt-4o',
    output_type=MyOutput,           # Structured output type
    deps_type=MyDeps,               # Dependency injection type
    instructions='You are helpful.',  # Static instructions
    retries=2,                      # Retry attempts for validation
    name='my-agent',                # For logging/tracing
    model_settings=ModelSettings(   # Provider settings
        temperature=0.7,
        max_tokens=1000
    ),
    end_strategy='early',           # How to handle tool calls with results
)
```

## Running Agents

Three execution methods:

```python
# Async (preferred)
result = await agent.run('prompt', deps=my_deps)

# Sync (convenience)
result = agent.run_sync('prompt', deps=my_deps)

# Streaming
async with agent.run_stream('prompt') as response:
    async for chunk in response.stream_output():
        print(chunk, end='')
```

## Instructions vs System Prompts

```python
# Instructions: Concatenated, for agent behavior
agent = Agent(
    'openai:gpt-4o',
    instructions='You are a helpful assistant. Be concise.'
)

# Dynamic instructions via decorator
@agent.instructions
def add_context(ctx: RunContext[MyDeps]) -> str:
    return f"User ID: {ctx.deps.user_id}"

# System prompts: Static, for model context
agent = Agent(
    'openai:gpt-4o',
    system_prompt=['You are an expert.', 'Always cite sources.']
)
```

## Common Patterns

### Parameterized Agent (Type-Safe)

```python
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext

@dataclass
class Deps:
    api_key: str
    user_id: int

agent: Agent[Deps, str] = Agent(
    'openai:gpt-4o',
    deps_type=Deps,
)

# deps is now required and type-checked
result = agent.run_sync('Hello', deps=Deps(api_key='...', user_id=123))
```

### No Dependencies (Satisfy Type Checker)

```python
# Option 1: Explicit type annotation
agent: Agent[None, str] = Agent('openai:gpt-4o')

# Option 2: Pass deps=None
result = agent.run_sync('Hello', deps=None)
```

## Verification gates

Run these in order before depending on an agent in production code:

1. **Smoke run** — Execute `agent.run_sync('Reply with OK.')` (or `await agent.run(...)` in async code). **Pass:** the call completes without raising and `result.output` is present.
2. **Structured output** — If you set `output_type`, prompt for a response that should satisfy the schema. **Pass:** `result.output` is an instance of your Pydantic model; repeated validation failures mean tightening instructions or `retries`, not adding features yet.
3. **Dependencies** — If you set `deps_type`, call `run` / `run_sync` with `deps=` of that type. **Pass:** the invocation type-checks and completes (or fails only for model/API reasons, not a missing or wrong `deps` value).

## Decision Framework

| Scenario | Configuration |
|----------|--------------|
| Simple text responses | `Agent(model)` |
| Structured data extraction | `Agent(model, output_type=MyModel)` |
| Need external services | Add `deps_type=MyDeps` |
| Validation retries needed | Increase `retries=3` |
| Debugging/monitoring | Set `instrument=True` |

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

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

Все скиллы по теме «ИИ и ML» →
migrating-agno-to-pydantic-ai pydantic Скилл migrating-agno-to-pydantic-ai для Claude Code переносит Python-приложения с Agno на Pydantic AI, трассируя реальный путь запроса и сохраняя HTTP-границы и инфраструктуру. CX Codex +1 463установок building-pydantic-ai-agents pydantic Скилл building-pydantic-ai-agents учит помощника проектировать приложения на Pydantic AI с инструментами и валидацией ответов. Пригодится при сборке типизированных агентных систем. CX Codex +1 6 600установок agentic-development alinaqi Скилл agentic-development для Claude Code: сборка автономных ИИ-агентов на Pydantic AI (Python) и Claude Agent SDK (Node.js). Покрывает многошаговые задачи с инструментами. CX Codex +1 416установок pydantic jiatastic Скилл объясняет агенту, как описывать данные моделями Pydantic: типизированные поля, валидаторы, сериализация и выгрузка JSON-схемы. CX Codex +1 194установок pydantic-models-py Microsoft Скилл pydantic-models-py для Claude Code задаёт структуру моделей Pydantic v2 по шаблону из пяти вариантов: Base, Create, Update, Response и InDB. Генерирует схемы запросов и ответов API с наследованием, чтобы не дублировать поля. CX Codex +1 5установок clickhouse-pydantic-config terrylica Скилл clickhouse-pydantic-config для Claude Code собирает файл подключений DBeaver для ClickHouse из Pydantic-модели и переменных окружения. Локальная и облачная базы открываются в клиенте без ручного ввода. CX Codex +1 130установок

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

Весь набор →
pytest-code-review Скилл pytest-code-review проверяет тесты pytest на корректность асинхронных вызовов, скоуп фикстур, параметризацию и пути для моков. Помогает находить утечки и ошибки патчинга до запуска CI. CX Codex +1 239установок sqlalchemy-code-review Скилл sqlalchemy-code-review проверяет SQLAlchemy-код на ошибки в сессиях, связях, запросах и миграциях. Нужен при ревью проектов на SQLAlchemy 2.0 и Alembic. CX Codex +1 228установок pydantic-ai-common-pitfalls Скилл pydantic-ai-common-pitfalls разбирает типичные ошибки в агентах на PydanticAI и подсказывает, что править: декораторы инструментов, зависимости, схемы вывода, стриминг. CX Codex +1 221установок agent-architecture-analysis Скилл agent-architecture-analysis проверяет кодовую базу ИИ-агента по методике 12-Factor Agents и выдаёт отчёт с оценкой каждого фактора и ссылками на файлы. CX Codex +1 220установок ai-elements Скилл ai-elements для Claude Code, Codex, Cursor, Copilot, Gemini CLI и OpenCode: помогает собирать интерфейсы чата, очереди задач, отображение инструментов и подтверждений. CX Codex +1 211установок go-code-review Скилл go-code-review проверяет Go-код на идиоматичность, обработку ошибок и гонки: сначала читает go.mod, потом разбирает функции целиком. CX Codex +1 206установок shadcn-code-review Скилл shadcn-code-review проверяет React-компоненты на базе shadcn/ui, Radix и Tailwind CSS на доступность, работу с CVA и шаблоны asChild. Помогает находить ошибки в кастомной вёрстке. CX Codex +1 206установок react-router-code-review Скилл react-router-code-review для Claude Code проверяет код роутинга в React Router v6.4 и новее: лоадеры, экшены, границы ошибок и навигацию. CX Codex +1 202установок

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

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