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.

referencesNATIVE-TOOLS.md

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

Native Tools

Read this file when the user wants provider-native tools such as web search, web fetch, code execution, memory, or file search.

Prefer provider-adaptive capabilities like WebSearch(), WebFetch(), MCP(), or ImageGeneration() when the user wants a provider-agnostic solution. Use native tools directly when they explicitly want provider-native behavior or provider-specific configuration.

Give My Agent Web Search or Code Execution

Native tools are wrapped in [NativeTool][pydantic_ai.capabilities.NativeTool] and passed via capabilities=[...].

from pydantic_ai import Agent
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.native_tools import WebSearchTool

agent = Agent('openai-responses:gpt-5.2', name='web_search_agent', capabilities=[NativeTool(WebSearchTool())])
result = agent.run_sync('Give me a sentence with the biggest news in AI this week.')
print(result.output)

For OpenAI web search, use the Responses API model prefix (openai-responses:), not openai:. Set external_web_access=False on WebSearch or WebSearchTool to restrict OpenAI Responses web search to cached or indexed content.

Restricting settings (allowed_domains, blocked_domains, max_uses, and external_web_access=False on web search; the first three on web fetch) are not dropped silently. On a model whose native tool can't apply one that is set (Gemini applies none), the tool counts as unsupported: a local fallback runs in its place if one is configured, an optional=True tool is left out, and UserError is raised otherwise.

Native Tool Defaults

Reach for these when the provider supports them:

  • WebSearchTool
  • WebFetchTool
  • CodeExecutionTool
  • ImageGenerationTool
  • MemoryTool
  • MCPServerTool
  • FileSearchTool
  • AdvisorTool (Anthropic, OpenRouter; lets a faster executor model consult a stronger advisor model mid-generation)

Provider-Specific Settings

Put settings shared by providers directly on the native tool. For provider-only options, pass the provider's typed settings dictionary in provider_settings, keyed by the model class that reads it: OpenRouterModel reads openrouter, even for Claude, and OpenAIChatModel with an OpenRouter provider doesn't read it. Like model settings, unknown keys are ignored, so use the typed dictionaries to catch typos:

from pydantic_ai import Agent
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.native_tools import OpenRouterWebSearchToolSettings, WebSearchTool

agent = Agent(
    'openrouter:openai/gpt-5.2',
    capabilities=[
        NativeTool(
            WebSearchTool(
                provider_settings={
                    'openrouter': OpenRouterWebSearchToolSettings(engine='exa')
                }
            )
        )
    ],
)

The outer TypedDict lists the known keys. Each key maps to its own tool-specific TypedDict, so autocomplete and type checking apply at both levels. A model adapter reads only the options it knows from its own entry, so settings for several models can coexist on one tool.

Anthropic has response_inclusion on WebSearchTool and WebFetchTool (AnthropicWebSearchToolSettings, AnthropicWebFetchToolSettings) and use_cache on WebFetchTool. use_cache selects the 20260318 web fetch version; response_inclusion selects the 20260318 versions only when code execution may call the tool, since it has no effect on direct calls.

Some provider-only options used to be top-level fields and now live in provider_settings. The top-level fields still work but emit a deprecation warning, so write new code with provider_settings, and read the value back from there too:

  • WebFetchTool: enable_citations and max_content_tokens under anthropic (AnthropicWebFetchToolSettings)
  • ImageGenerationTool: action, background, input_fidelity, moderation, model, partial_images and quality under openai (OpenAIImageGenerationToolSettings)
  • FileSearchTool: instructions and retrieval_mode under xai (XaiFileSearchToolSettings)
  • AdvisorTool: caching under anthropic (AnthropicAdvisorToolSettings)

For example, write ImageGenerationTool(provider_settings={'openai': {'quality': 'high'}}), not ImageGenerationTool(quality='high'). The capabilities' own arguments, such as ImageGeneration(quality='high'), are not deprecated.

Dynamic Native Tool Configuration

Prepare native tools from RunContext when configuration depends on the current user or request. Wrap the prepare function in NativeTool(...).

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import NativeTool
from pydantic_ai.native_tools import WebSearchTool


async def prepared_web_search(ctx: RunContext[dict]) -> WebSearchTool | None:
    if not ctx.deps.get('location'):
        return None
    return WebSearchTool(user_location={'city': ctx.deps['location']})


agent = Agent(
    'openai-responses:gpt-5.2',
    name='dynamic_web_search_agent',
    capabilities=[NativeTool(prepared_web_search)],
    deps_type=dict,
)

Returning None omits the tool for that step. XSearch and ImageGeneration are the exception when fallback_subagent_model is set: they route unsupported models to a subagent rather than a local tool, and their native= factory is resolved a second time when that subagent runs. Once fallback_subagent_model is set, returning None no longer omits anything — the subagent tool stays offered and calling it raises UserError. Return a configured tool instance, or drop fallback_subagent_model.

When to Use Native Tools vs Provider-Adaptive Capabilities

Use provider-adaptive capabilities — WebSearch(), WebFetch(), MCP(), ImageGeneration() — when:

  • the code should work across providers
  • you want local fallback when native support is missing
  • the user has not committed to a provider yet
from pydantic_ai import Agent
from pydantic_ai.capabilities import WebSearch

agent = Agent('anthropic:claude-sonnet-4-6', name='adaptive_web_search_agent', capabilities=[WebSearch()])

Use native tools (NativeTool(WebSearchTool(...))) when:

  • the user explicitly wants provider-native behavior
  • provider-specific configuration matters (e.g. WebSearchTool(user_location=...))
  • the user already picked a provider that supports the tool

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