Index of every page on this site: llms.txt
All skills
pydantic avatar

/building-pydantic-ai-agents

@b2d64a3
by pydanticpydantic/pydantic-ai21k stars
3,221
Run it yourself

Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns. Use when the user mentions Pydantic AI, imports pydantic_ai, or asks to build an AI agent, add tools/capabilities, attach a workspace, defer capability loading, stream output, define agents from YAML, or test agent behavior.

Use this Skill: https://skilld.dev/gh/pydantic/pydantic-ai/building-pydantic-ai-agents

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesTOOLS-CORE.md

≈2.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Tools Core

Read this file when the user wants to add function tools, organize toolsets, connect MCP servers, or use explicit common search tools.

Add Tools to an Agent

Use @agent.tool_plain for pure functions and @agent.tool for tools that need RunContext.

import random

from pydantic_ai import Agent, RunContext

agent = Agent('google:gemini-3-flash-preview', name='dice_tools_agent', deps_type=str)


@agent.tool_plain
def roll_dice() -> str:
    return str(random.randint(1, 6))


@agent.tool
def get_player_name(ctx: RunContext[str]) -> str:
    return ctx.deps

Use Tool(fn) when tools are defined outside the agent file or shared between agents.

Choosing a Tool Registration Method

Default choices:

  • @agent.tool when the tool needs deps, usage, retry count, or message history
  • @agent.tool_plain when the tool is a plain function
  • Tool(...) in tools=[...] when the tool should be reusable across agents
  • FunctionToolset when multiple related tools should be managed as a group

Describe Enum Options to the Model

An Enum parameter or field reaches the model as a bare list of values. Mix in UseEnumMemberDocstrings to send the docstring written under each member as that option's description; the enum then renders as anyOf of described consts. This is the enum counterpart to model_config = ConfigDict(use_attribute_docstrings=True) on a Pydantic model — an Enum has no config to carry a flag, and any assigned class attribute becomes a member, so a base class is the marker.

from enum import StrEnum

from pydantic_ai import Agent, UseEnumMemberDocstrings

agent = Agent('openai:gpt-5.2', name='ticket_agent')


class Urgency(UseEnumMemberDocstrings, StrEnum):
    """How urgent the ticket is."""

    low = 'low'
    """Can wait a week."""
    high = 'high'
    """Needs attention today."""


@agent.tool_plain
def set_urgency(urgency: Urgency) -> str:
    """Set the urgency of the ticket."""
    return f'Urgency set to {urgency.value}.'

Without the mix-in the docstrings are ignored and the schema is unchanged. Literals have nowhere to write a docstring; use a described Enum when the model needs to know what each option means.

A bool has two answers and nowhere to describe them; Annotated[bool, BoolCriteria(true='...', false='...')] sends what each one means the same way, and the value stays a plain bool.

Organize or Restrict Which Tools an Agent Can Use

Use toolsets when the user has multiple related tools or wants cross-cutting behavior applied to a group.

Examples:

  • FunctionToolset for a bundle of Python tools
  • MCP servers, which are themselves toolsets
  • wrapper toolsets for approval, deferred loading, or other cross-cutting behavior

Access Usage Stats, Message History, or Retry Count in Tools

Route this to @agent.tool with RunContext.

Useful RunContext fields include:

  • ctx.deps
  • ctx.usage
  • ctx.messages
  • ctx.retry
  • ctx.realtime — whether the run is a realtime session
  • ctx.realtime_session — the live RealtimeSession in tools and on_event hooks (None in classic runs, setup hooks, and throughout wrap_run, whose context copy predates the connection)

Inside a realtime tool, await ctx.realtime_session.close() hangs up cleanly: the calling tool does not resume, and its call is recorded as interrupted. Use ctx.cancel() instead when the session context should raise RunCancelled; that route also records the call as interrupted.

Use MCP Servers

For URL-based MCP servers, use the MCP capability — it runs the MCP server locally by default and lets you opt into the model provider's native MCP support with native=True. See the MCP capability docs.

from pydantic_ai import Agent
from pydantic_ai.capabilities import MCP

agent = Agent(
    'openai:gpt-5.2',
    name='mcp_agent',
    capabilities=[
        MCP('https://mcp.example.com/api'),               # Streamable HTTP, local-only by default
        MCP('https://mcp.example.com/other', native=True),  # opt into native with local fallback
    ],
)

The capability's first positional arg is the URL. To pass any other MCPToolset input — a fastmcp.client.transports.*Transport, pre-built fastmcp.Client, in-process FastMCP server, or local script path — use the local= keyword:

from fastmcp.client.transports import StdioTransport

from pydantic_ai import Agent
from pydantic_ai.capabilities import MCP

agent = Agent(
    'openai:gpt-5.2',
    name='mcp_stdio_agent',
    capabilities=[MCP(local=StdioTransport(command='python', args=['mcp_server.py']))],
)

To keep an MCP server's tool names from colliding with other tools, pass tool_prefix: MCP(url, tool_prefix='docs') exposes search as docs_search, and MCP(url, id='docs', tool_prefix=True) uses the explicit id= as the prefix (True without id= raises UserError; the URL-derived id is never used). allowed_tools still names the server's own tools, and the id doesn't change. The prefix applies to local tools only; native MCP tools are named by the provider. Prefixing by default is planned for v3.

When each user has their own credentials for the MCP server (a multi-user or multi-tenant app), pass a function of the run context as the credentials instead of a fixed value: MCP(url, authorization_token=lambda ctx: ctx.deps.mcp_token) on the capability, or MCPToolset(url, auth=lambda ctx: ctx.deps.mcp_token) (and likewise headers=). It's called at the start of each run, and each run connects in an MCP session of its own with what it returned. Don't share one toolset between users with a fixed httpx.Auth that reads the user from a ContextVar: one session is opened as one user, and on FastMCP 3 overlapping runs send their requests with the first run's token. A toolset with function credentials never connects outside an agent run, so async with toolset: is a no-op and direct calls like list_tools() raise UserError; use await toolset.for_run(ctx) to get a connectable copy. See per-user authentication.

When you need to manage the toolset lifecycle yourself, share an MCP server across multiple agents, or use FastMCP-specific configuration that doesn't fit the capability shape, use MCPToolset directly and pass it via toolsets=[...]. Its tool_error_behavior controls how a tool error from the server surfaces: 'retry' (default) raises ModelRetry, 'failed' raises ToolFailed (recorded as outcome='failed'), and 'error' raises the raw fastmcp ToolError. For SEP-1686 tools with optional task support, set prefer_tasks=False to use normal calls; required tasks still use task-augmented execution.

An agent inside an MCP server can use MCPSamplingModel(ctx.session) to request inference from the connected client. It accepts prior function tool calls, results, and retries via message_history using the MCP 2025-11-25 sampling format. This preserves completed tool exchanges; it does not enable new tool calls or multimodal tool results. It sends its request in the middle of the tool call, so the client must connect with FastMCP 3 or a FastMCP 4 Client(..., mode='legacy'); on FastMCP 4's default (2026-07-28) protocol the request fails with NoBackChannelError. See MCP sampling and how the server asks.

Search with DuckDuckGo, Tavily, or Exa

Use common tools when the user wants explicit search tools rather than provider-adaptive capabilities.

from pydantic_ai import Agent
from pydantic_ai.common_tools.duckduckgo import duckduckgo_search_tool

agent = Agent(
    'openai:gpt-5.2',
    name='duckduckgo_search_agent',
    tools=[duckduckgo_search_tool()],
    instructions='Search DuckDuckGo for the given query and return the results.',
)

Good default split:

  • use WebSearch() capability when the user wants model-agnostic search with native fallback
  • use duckduckgo_search_tool() / Tavily / Exa when the user explicitly wants those engines as tools

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts1mo3 checks · Risk SAFE
  • Gen Agent Trust Hub1mo

    The skill provides comprehensive guidance for building AI agents using the Pydantic AI framework. It correctly identifies security considerations for powerful features like code execution, file system access, and credential management, providing appropriate warnings and best practices for their safe use.

  • Socket1mo

    No alerts

  • Snyk1mo

    Risk: LOW · No issues

Signed by skilld at b2d64a3. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 3 days ago
compatibility
Requires Python 3.11+
metadata
{
  "version": "1.1.2",
  "author": "pydantic"
}

README badge

README badge for pydantic/pydantic-ai/building-pydantic-ai-agents