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

pydantic-ai-tool-system — скилл для Claude Code: установка и обзор

Скилл pydantic-ai-tool-system помогает агенту корректно объявлять инструменты PydanticAI с нужными декораторами, докстрингами и типами контекста.

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

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

Что делает pydantic-ai-tool-system

Скилл содержит правила написания инструментов для фреймворка PydanticAI. Он следит за разделением двух декораторов: @agent.tool требует RunContext первым аргументом, а @agent.tool_plain запрещает передавать контекст вовсе. Без соблюдения этой сигнатуры вызов упадёт с ошибкой ещё на этапе сборки.

В инструкциях расписано оформление докстрингов в стилях Google и Sphinx, так как модель читает описания аргументов именно оттуда. Также показаны примеры работы с ToolReturn, фильтрации инструментов через prepare_tools, объединения наборов через FunctionToolset и CombinedToolset, а также извлечения токенов и зависимостей из ctx.

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

  • настроить вызов функций через декораторы PydanticAI
  • проверить сигнатуры и типы аргументов у plain-инструментов
  • оформить docstring для передачи схемы параметров в LLM
  • динамически фильтровать доступные тулы через prepare_tools

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

  • Напиши инструмент для PydanticAI, который принимает ID пользователя и обращается к базе через RunContext
  • Сделай plain-тул для расчёта суммы чисел с Google-style докстрингом
  • Покажи, как объединить две группы функций через CombinedToolset

Как установить pydantic-ai-tool-system

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill pydantic-ai-tool-system -a claude-code

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

~/.claude/skills/pydantic-ai-tool-system/SKILL.md

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

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

Вопросы о pydantic-ai-tool-system

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

Выполните команду npx skills add existential-birds/beagle --skill pydantic-ai-tool-system -a claude-code в терминале.

Чем @agent.tool отличается от @agent.tool_plain?

Декоратор @agent.tool строго требует объект RunContext первым параметром, тогда как @agent.tool_plain не должен содержать контекст в сигнатуре.

Зачем нужны подробные докстринги у функций-инструментов?

Языковая модель использует текст докстринга и описания параметров (Google или Sphinx) для понимания того, когда и с какими аргументами вызывать инструмент.

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

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

# PydanticAI Tool System

## Tool Registration

Two decorators based on whether you need context:

```python
from pydantic_ai import Agent, RunContext

agent = Agent('openai:gpt-4o')

# @agent.tool - First param MUST be RunContext
@agent.tool
async def get_user_data(ctx: RunContext[MyDeps], user_id: int) -> str:
    """Get user data from database.

    Args:
        ctx: The run context with dependencies.
        user_id: The user's ID.
    """
    return await ctx.deps.db.get_user(user_id)

# @agent.tool_plain - NO context parameter allowed
@agent.tool_plain
def calculate_total(prices: list[float]) -> float:
    """Calculate total price.

    Args:
        prices: List of prices to sum.
    """
    return sum(prices)
```

## Critical Rules

1. **@agent.tool**: First parameter MUST be `RunContext[DepsType]`
2. **@agent.tool_plain**: MUST NOT have `RunContext` parameter
3. **Docstrings**: Required for LLM to understand tool purpose
4. **Google-style docstrings**: Used for parameter descriptions

### Gates (verify in the file, not from memory)

1. **Decorator matches signature** — If the first parameter is `RunContext[...]`, the decorator must be `@agent.tool` (not `@agent.tool_plain`). **Pass:** the same `def` line’s decorator stack includes `@agent.tool`, and the first parameter is typed `RunContext[...]`.
2. **Plain tools** — With `@agent.tool_plain`, the parameter list must not include `RunContext`. **Pass:** a quick scan of the signature shows no `RunContext`.
3. **Docstring for the model** — Non-empty docstring; if the tool has parameters, describe them (Google `Args:` or Sphinx `:param` when using `docstring_format='sphinx'`). **Pass:** each parameter in the signature is mentioned in the docstring body.

## Docstring Formats

Google style (default):
```python
@agent.tool_plain
async def search(query: str, limit: int = 10) -> list[str]:
    """Search for items.

    Args:
        query: The search query.
        limit: Maximum results to return.
    """
```

Sphinx style:
```python
@agent.tool_plain(docstring_format='sphinx')
async def search(query: str) -> list[str]:
    """Search for items.

    :param query: The search query.
    """
```

## Tool Return Types

Tools can return various types:

```python
# String (direct)
@agent.tool_plain
def get_info() -> str:
    return "Some information"

# Pydantic model (serialized to JSON)
@agent.tool_plain
def get_user() -> User:
    return User(name="John", age=30)

# Dict (serialized to JSON)
@agent.tool_plain
def get_data() -> dict[str, Any]:
    return {"key": "value"}

# ToolReturn for custom content types
from pydantic_ai import ToolReturn, ImageUrl

@agent.tool_plain
def get_image() -> ToolReturn:
    return ToolReturn(content=[ImageUrl(url="https://...")])
```

## Accessing Context

RunContext provides:

```python
@agent.tool
async def my_tool(ctx: RunContext[MyDeps]) -> str:
    # Dependencies
    db = ctx.deps.db
    api = ctx.deps.api_client

    # Model info
    model_name = ctx.model.model_name

    # Usage tracking
    tokens_used = ctx.usage.total_tokens

    # Retry info
    attempt = ctx.retry  # Current retry attempt (0-based)
    max_retries = ctx.max_retries

    # Message history
    messages = ctx.messages

    return "result"
```

## Tool Prepare Functions

Dynamically modify tools per-request:

```python
from pydantic_ai.tools import ToolDefinition

async def prepare_tools(
    ctx: RunContext[MyDeps],
    tool_defs: list[ToolDefinition]
) -> list[ToolDefinition]:
    """Filter or modify tools based on context."""
    if ctx.deps.user_role != 'admin':
        # Hide admin tools from non-admins
        return [t for t in tool_defs if not t.name.startswith('admin_')]
    return tool_defs

agent = Agent('openai:gpt-4o', prepare_tools=prepare_tools)
```

## Toolsets

Group and compose tools:

```python
from pydantic_ai import FunctionToolset, CombinedToolset

# Create a toolset
db_tools = FunctionToolset()

@db_tools.tool
def query_users(name: str) -> list[dict]:
    """Query users by name."""
    ...

@db_tools.tool
def update_user(id: int, data: dict) -> bool:
    """Update user data."""
    ...

# Use in agent
agent = Agent('openai:gpt-4o', toolsets=[db_tools])

# Combine toolsets
all_tools = CombinedToolset([db_tools, api_tools])
```

## Common Mistakes

### Wrong: Context in tool_plain
```python
@agent.tool_plain
async def bad_tool(ctx: RunContext[MyDeps]) -> str:  # ERROR!
    ...
```

### Wrong: Missing context in tool
```python
@agent.tool
def bad_tool(user_id: int) -> str:  # ERROR!
    ...
```

### Wrong: Context not first parameter
```python
@agent.tool
def bad_tool(user_id: int, ctx: RunContext[MyDeps]) -> str:  # ERROR!
    ...
```

## Async vs Sync

Both work, but async is preferred for I/O:

```python
# Async (preferred for I/O operations)
@agent.tool
async def fetch_data(ctx: RunContext[Deps]) -> str:
    return await ctx.deps.client.get('/data')

# Sync (fine for CPU-bound operations)
@agent.tool_plain
def compute(x: int, y: int) -> int:
    return x * y
```

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

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
building-pydantic-ai-agents pydantic Скилл building-pydantic-ai-agents учит помощника проектировать приложения на Pydantic AI с инструментами и валидацией ответов. Пригодится при сборке типизированных агентных систем. CX Codex +1 6 600установок migrating-openai-agents-sdk-to-pydantic-ai pydantic Скилл migrating-openai-agents-sdk-to-pydantic-ai для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode, который переводит Python-приложения с OpenAI Agents SDK на Pydantic AI. CX Codex +1 474установок qianwen-text QianWen-AI Скилл qianwen-text для Claude Code общается с моделями Qwen, пишет текст и код, вызывает функции. Запускается по явному упоминанию имени или просьбе использовать Qwen. CX Codex +1 6 200установок openai-api-development Mindrally Скилл openai-api-development для разработки на OpenAI API: подсказывает, как писать вызовы GPT, function calling, эмбеддинги и Assistants API на Python. CX Codex +1 906установок qwencloud-text QwenCloud Скилл qwencloud-text для Claude Code отправляет запросы к Qwen и сторонним моделям через QwenCloud. Он включается для генерации текста, кода и вызова функций. CX Codex +1 1 800установок agent-protocol borghei Скилл agent-protocol для Claude Code проектирует схемы инструментов и форматы обмена данными между агентами. Помогает связывать сервисы через MCP, Google A2A и OpenAI Function Calling. CX Codex +1 104установок

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

Весь набор →
react-router-code-review Скилл react-router-code-review для Claude Code проверяет код роутинга в React Router v6.4 и новее: лоадеры, экшены, границы ошибок и навигацию. CX Codex +1 202установок swift-testing-code-review Скилл swift-testing-code-review проверяет тесты Swift Testing: макросы, параметризованные и асинхронные сценарии, организацию наборов. Нужен при ревью .swift-файлов. CX Codex +1 196установок docs-style Скилл docs-style задаёт правила редполитики для технической документации: выбор формата по Diataxis, активный залог и структура для людей и нейросетей. CX Codex +1 180установок deepagents-architecture Скилл deepagents-architecture помогает выбрать архитектуру для приложений на Deep Agents, спланировать субагентов, настроить цепочки middleware и схему хранения данных. CX Codex +1 162установок langgraph-implementation Скилл langgraph-implementation помогает собирать состояния графов LangGraph, задавать узлы и переходы, добавлять сохранение и паузы для участия человека. CX Codex +1 161установок postgres-code-review Скилл postgres-code-review проверяет SQL, схемы и код работы с PostgreSQL: ищет проблемы с индексами, JSONB, соединениями и транзакциями. Подключайте его при ревью изменений в базе. CX Codex +1 158установок explanation-docs Скилл explanation-docs для Claude Code помогает писать документы о том, как и почему устроена система. Документирует архитектурные решения и материалы для онбординга. CX Codex +1 152установок llm-artifacts-detection Скилл llm-artifacts-detection находит типичный мусор после ИИ-кодеров: лишние слои абстракций, тесты стандартных библиотек, мёртвый код и очевидные комментарии. CX Codex +1 151установок

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

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