Skip to content

pydantic_ai.native_tools

AbstractNativeTool

Bases: ABC

A native tool that can be used by an agent.

This class is abstract and cannot be instantiated directly.

The native tools are passed to the model as part of the ModelRequestParameters.

Attributes

kind

Native tool identifier, this should be available on all native tools as a discriminator.

Type: str Default: 'unknown_native_tool'

optional

Whether this instance is a best-effort upgrade rather than a hard requirement.

When True, the instance is silently dropped from the request on a model that doesn’t support it natively, instead of raising when no local fallback is provided. Use for native tools where a fallback path exists (e.g. a local function tool that takes over when the native one isn’t available). When False (the default), the request errors on models that can’t honor the native tool — the user explicitly asked for it, so fail loudly rather than silently substituting different behavior.

Type: bool Default: False

unique_id

A unique identifier for the native tool.

If multiple instances of the same native tool can be passed to the model, subclasses should override this property to allow them to be distinguished.

Type: str

label

Human-readable label for UI display.

Subclasses should override this to provide a meaningful label.

Type: str

restricting_settings

The names of the settings set on this instance that narrow what the tool may do.

These are settings such as domain filters and usage limits, which are usually there for compliance or cost reasons. A model that can’t apply one of them treats this instance as unsupported, so the request uses the local fallback when one is provided, leaves the tool out when it is optional, and raises UserError otherwise. Settings that only tune results, such as a search context size, are not included.

Models report which of these they can’t apply via Model.unsupported_native_tool_settings.

Type: frozenset[str]

AnthropicWebSearchToolSettings

Bases: TypedDict

Anthropic-specific settings for WebSearchTool.

Attributes

response_inclusion

Whether results consumed by completed code execution calls remain in the response.

Anthropic defaults to 'full'. This has no effect when the model calls the tool directly, which is the default on models without dynamic filtering and on requests whose citations route the tool to direct calls: direct results, and results from code execution calls that paused before completing, are returned in full.

Type: Literal[‘full’, ‘excluded’]

OpenRouterWebSearchToolSettings

Bases: TypedDict

OpenRouter-specific settings for WebSearchTool.

Attributes

engine

The search engine OpenRouter should use.

Other strings are forwarded as they are, so an engine OpenRouter adds later works without a new release.

Type: Literal[‘auto’, ‘native’, ‘exa’, ‘firecrawl’, ‘parallel’, ‘perplexity’] | str

mode

The search mode, which depends on the engine.

Exa and Parallel each accept their own set of values, and other engines ignore this option. OpenRouter decides whether a value fits the engine, so it isn’t checked here.

Type: Literal[‘instant’, ‘fast’, ‘auto’, ‘deep-lite’, ‘deep’, ‘deep-reasoning’, ‘turbo’, ‘basic’, ‘advanced’] | str

max_results

The maximum results returned by each search call.

Type: int

max_total_results

The maximum results returned across all search calls in one request.

Type: int

max_characters

The maximum content characters returned for each result.

Type: int

WebSearchProviderSettings

Bases: TypedDict

Provider-specific web search settings, keyed by the model class that reads them.

WebSearchTool

Bases: AbstractNativeTool

A native tool that allows your agent to search the web for information.

The parameters that PydanticAI passes depend on the model, as some parameters may not be supported by certain models. The restricting settings allowed_domains, blocked_domains, max_uses, and external_web_access=False are the exception: on a model that can’t apply one that is set, the tool is treated as unsupported, so the local fallback runs if one is provided, the tool is left out if it is optional, and UserError is raised otherwise. OpenRouter uses its Beta web-search server tool, which lets the model decide whether to search and how often. It accepts the portable settings below, though their effect depends on OpenRouter’s selected search engine and downstream provider.

Supported by:

  • Anthropic
  • OpenAI Responses
  • Groq
  • Google
  • xAI
  • OpenRouter

Attributes

search_context_size

The search_context_size parameter controls how much context is retrieved from the web to help the tool formulate a response.

Supported by:

  • OpenAI Responses
  • OpenRouter

Type: Literal[‘low’, ‘medium’, ‘high’] Default: 'medium'

user_location

The user_location parameter allows you to localize search results based on a user’s location.

Supported by:

Type: WebSearchUserLocation | None Default: None

blocked_domains

If provided, these domains will never appear in results.

With Anthropic, you can only use one of blocked_domains or allowed_domains, not both.

Supported by:

Type: list[str] | None Default: None

allowed_domains

If provided, only these domains will be included in results.

With Anthropic, you can only use one of blocked_domains or allowed_domains, not both.

Supported by:

Type: list[str] | None Default: None

max_uses

If provided, the tool will stop searching the web after the given number of uses.

For OpenRouter, this limit is enforced with a non-native search engine or Anthropic’s native search. Other native providers ignore it.

Supported by:

  • Anthropic
  • OpenRouter

Type: int | None Default: None

external_web_access

Whether the hosted web search tool may fetch live web content.

If False, the tool uses only cached or indexed results. If None, the parameter is omitted and the provider default is used. OpenAI currently defaults to True.

Supported by:

OpenAI’s legacy web_search_preview tool ignores this parameter.

Type: bool | None Default: None

provider_settings

Provider-specific web search settings, keyed by the model class that reads them.

Type: WebSearchProviderSettings | None Default: None

kind

The kind of tool.

Type: str Default: 'web_search'

restricting_settings

allowed_domains, blocked_domains and max_uses when set, and external_web_access when False.

Type: frozenset[str]

WebSearchUserLocation

Bases: TypedDict

Allows you to localize search results based on a user’s location.

Supported by:

  • Anthropic
  • OpenAI Responses
  • xAI
  • OpenRouter

Attributes

city

The city where the user is located.

Type: str

country

The country where the user is located.

For OpenAI and xAI, this must be a 2-letter ISO 3166-1 alpha-2 country code (e.g., ‘US’, ‘GB’).

Type: str

region

The region or state where the user is located.

Type: str

timezone

The timezone of the user’s location.

Type: str

XSearchTool

Bases: AbstractNativeTool

A native tool that allows your agent to search X/Twitter for posts and content.

See https://docs.x.ai/developers/tools/x-search for more details.

When used via the XSearch capability with a fallback_subagent_model set, this tool also works with non-xAI models by delegating to a subagent running the specified xAI model.

Supported by:

  • xAI

Attributes

allowed_x_handles

If provided, only posts from these X handles will be included (max 20).

Supported by:

Type: list[str] | None Default: None

excluded_x_handles

If provided, posts from these X handles will be excluded (max 20).

Supported by:

Type: list[str] | None Default: None

from_date

If provided, only posts created on or after this datetime will be included.

Naive datetimes are interpreted as UTC by the xAI API.

Supported by:

Type: datetime | None Default: None

to_date

If provided, only posts created on or before this datetime will be included.

Naive datetimes are interpreted as UTC by the xAI API.

Supported by:

Type: datetime | None Default: None

enable_image_understanding

Enable image analysis from X posts.

Supported by:

Type: bool Default: False

enable_video_understanding

Enable video analysis from X content.

Supported by:

Type: bool Default: False

include_output

Include raw X search results in the response as NativeToolReturnPart.

Without this, the model uses the search results internally but only returns its text summary. Enabling it gives programmatic access to searched posts, sources, and metadata.

Can also be set via XaiModelSettings.xai_include_x_search_output.

Supported by:

Type: bool Default: False

kind

The kind of tool.

Type: str Default: 'x_search'

CodeExecutionTool

Bases: AbstractNativeTool

A native tool that allows your agent to execute code.

Supported by:

  • Anthropic
  • OpenAI Responses
  • Google
  • Bedrock (Nova2.0)
  • xAI

Attributes

files

Uploaded files to make available in the code execution environment.

Only files matching the model provider are used; files from other providers are ignored.

Supported by:

  • Anthropic
  • OpenAI Responses

Type: list[UploadedFile] | None Default: None

kind

The kind of tool.

Type: str Default: 'code_execution'

AnthropicWebFetchToolSettings

Bases: TypedDict

Anthropic-specific settings for WebFetchTool.

Attributes

enable_citations

Whether fetched content is cited. Maps to citations={'enabled': True}.

The citations model setting also enables them.

Type: bool

max_content_tokens

Maximum length, in tokens, of the fetched content that Anthropic adds to the context.

Type: int

use_cache

Whether Anthropic may return cached web content.

Anthropic defaults to True; False fetches the page fresh, which adds latency.

Type: bool

response_inclusion

Whether results consumed by completed code execution calls remain in the response.

Anthropic defaults to 'full'. This has no effect when the model calls the tool directly, which is the default on models without dynamic filtering and on requests whose citations route the tool to direct calls: direct results, and results from code execution calls that paused before completing, are returned in full.

Type: Literal[‘full’, ‘excluded’]

WebFetchProviderSettings

Bases: TypedDict

Provider-specific web fetch settings, keyed by the model class that reads them.

WebFetchTool

Bases: AbstractNativeTool

Allows your agent to access contents from URLs.

The parameters that PydanticAI passes depend on the model, as some parameters may not be supported by certain models. The restricting settings allowed_domains, blocked_domains, and max_uses are the exception: on a model that can’t apply one that is set, the tool is treated as unsupported, so the local fallback runs if one is provided, the tool is left out if it is optional, and UserError is raised otherwise.

Supported by:

  • Anthropic
  • Google

Attributes

max_uses

If provided, the tool will stop fetching URLs after the given number of uses.

Supported by:

  • Anthropic

Type: int | None Default: None

allowed_domains

If provided, only these domains will be fetched.

With Anthropic, you can only use one of blocked_domains or allowed_domains, not both.

Supported by:

Type: list[str] | None Default: None

blocked_domains

If provided, these domains will never be fetched.

With Anthropic, you can only use one of blocked_domains or allowed_domains, not both.

Supported by:

Type: list[str] | None Default: None

enable_citations

If True, enables citations for fetched content.

Deprecated: set provider_settings.anthropic.enable_citations instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

The citations model setting also enables them.

Supported by:

  • Anthropic

Type: Annotated[bool, _moved_to_provider_settings(anthropic, enable_citations)] Default: False

max_content_tokens

Maximum content length in tokens for fetched content.

Deprecated: set provider_settings.anthropic.max_content_tokens instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • Anthropic

Type: Annotated[int | None, _moved_to_provider_settings(anthropic, max_content_tokens)] Default: None

provider_settings

Provider-specific web fetch settings, keyed by the model class that reads them.

Type: WebFetchProviderSettings | None Default: None

kind

The kind of tool.

Type: str Default: 'web_fetch'

restricting_settings

allowed_domains, blocked_domains and max_uses when set.

Type: frozenset[str]

OpenAIImageGenerationToolSettings

Bases: TypedDict

OpenAI-specific settings for ImageGenerationTool.

Attributes

action

Whether to generate a new image, edit an input image, or let OpenAI choose. Defaults to 'auto'.

Type: Literal[‘generate’, ‘edit’, ‘auto’]

background

The image background. 'transparent' requires PNG or WebP output. Defaults to 'auto'.

Type: Literal[‘transparent’, ‘opaque’, ‘auto’]

input_fidelity

How closely edits should preserve features from input images. Defaults to 'low'.

Type: Literal[‘high’, ‘low’]

moderation

The OpenAI image moderation level. Defaults to 'auto'.

Type: Literal[‘auto’, ‘low’]

model

The OpenAI image generation model. By default, OpenAI selects the model.

Type: ImageGenerationModelName

partial_images

The number of partial images to stream, from 0 to 3. Defaults to 0.

Type: int

quality

The OpenAI image quality level. Defaults to 'auto'. gpt-image-2 and earlier models reject xhigh and max.

Type: ImageQuality

ImageGenerationProviderSettings

Bases: TypedDict

Provider-specific image generation settings, keyed by the model class that reads them.

ImageGenerationTool

Bases: AbstractNativeTool

A native tool that allows your agent to generate images.

Supported by:

  • OpenAI Responses
  • Google

Attributes

action

Whether to generate a new image or edit an existing image.

Deprecated: set provider_settings.openai.action instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. Default: ‘auto’.

Type: Annotated[Literal[‘generate’, ‘edit’, ‘auto’], _moved_to_provider_settings(openai, action)] Default: 'auto'

background

Background type for the generated image.

Deprecated: set provider_settings.openai.background instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. ‘transparent’ is only supported for ‘png’ and ‘webp’ output formats.

Type: Annotated[Literal[‘transparent’, ‘opaque’, ‘auto’], _moved_to_provider_settings(openai, background)] Default: 'auto'

input_fidelity

Control how much effort the model will exert to match the style and features, especially facial features, of input images.

Deprecated: set provider_settings.openai.input_fidelity instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. Default: ‘low’.

Type: Annotated[Literal[‘high’, ‘low’] | None, _moved_to_provider_settings(openai, input_fidelity)] Default: None

moderation

Moderation level for the generated image.

Deprecated: set provider_settings.openai.moderation instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses

Type: Annotated[Literal[‘auto’, ‘low’], _moved_to_provider_settings(openai, moderation)] Default: 'auto'

model

The image generation model to use.

Deprecated: set provider_settings.openai.model instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. Defaults to the provider’s image generation model selection. Known image generation models include gpt-image-2.6-flare, gpt-image-2.6-sunburst, gpt-image-2, gpt-image-1.5, and gpt-image-1-mini.

This selects the underlying image generation model used by the tool; it does not change the agent’s conversational model.

Type: Annotated[ImageGenerationModelName | None, _moved_to_provider_settings(openai, model)] Default: None

output_compression

Compression level for the output image.

Supported by:

  • OpenAI Responses. Only supported for ‘jpeg’ and ‘webp’ output formats. Default: 100.
  • Google (Vertex AI only). Only supported for ‘jpeg’ output format. Default: 75. Setting this will default output_format to ‘jpeg’ if not specified.

Type: int | None Default: None

output_format

The output format of the generated image.

Supported by:

  • OpenAI Responses. Default: ‘png’.
  • Google (Vertex AI only). Default: ‘png’, or ‘jpeg’ if output_compression is set.

Type: Literal[‘png’, ‘webp’, ‘jpeg’] | None Default: None

partial_images

Number of partial images to generate in streaming mode.

Deprecated: set provider_settings.openai.partial_images instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. Supports 0 to 3.

Type: Annotated[int, _moved_to_provider_settings(openai, partial_images)] Default: 0

quality

The quality of the generated image.

Deprecated: set provider_settings.openai.quality instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • OpenAI Responses. gpt-image-2 and earlier models reject xhigh and max.

Type: Annotated[ImageQuality, _moved_to_provider_settings(openai, quality)] Default: 'auto'

size

The size of the generated image.

  • OpenAI Responses: ‘auto’ (default: model selects the size based on the prompt), ‘1024x1024’, ‘1024x1536’, ‘1536x1024’
  • Google (Gemini 3 Pro Image and later): ‘512’ (Gemini 3.1 Flash Image only), ‘1K’ (default), ‘2K’, ‘4K’

Type: ImageSize | None Default: None

aspect_ratio

The aspect ratio to use for generated images.

Supported by:

  • Google image-generation models (Gemini)
  • OpenAI Responses (maps ‘1:1’, ‘2:3’, and ‘3:2’ to supported sizes)

Type: ImageAspectRatio | None Default: None

provider_settings

Provider-specific image generation settings, keyed by the model class that reads them.

Type: ImageGenerationProviderSettings | None Default: None

kind

The kind of tool.

Type: str Default: 'image_generation'

MemoryTool

Bases: AbstractNativeTool

A native tool that allows your agent to use memory.

Supported by:

  • Anthropic

Attributes

kind

The kind of tool.

Type: str Default: 'memory'

MCPServerTool

Bases: AbstractNativeTool

A native tool that allows your agent to use MCP servers.

Supported by:

  • OpenAI Responses
  • Anthropic
  • xAI

Attributes

id

A unique identifier for the MCP server.

Type: str

url

The URL of the MCP server to use.

For OpenAI Responses, it is possible to use connector_id by providing it as x-openai-connector:<connector_id>.

Type: str

authorization_token

Authorization header to use when making requests to the MCP server.

Supported by:

  • OpenAI Responses
  • Anthropic
  • xAI

Type: str | None Default: None

description

A description of the MCP server.

Supported by:

  • OpenAI Responses
  • xAI

Type: str | None Default: None

allowed_tools

A list of tools that the MCP server can use.

Supported by:

  • OpenAI Responses
  • Anthropic
  • xAI

Type: list[str] | None Default: None

headers

Optional HTTP headers to send to the MCP server.

Use for authentication or other purposes.

Supported by:

  • OpenAI Responses
  • xAI

Type: dict[str, str] | None Default: None

XaiFileSearchToolSettings

Bases: TypedDict

xAI-specific settings for FileSearchTool.

Attributes

instructions

Instructions for interpreting and ranking xAI collections search results.

Type: str

retrieval_mode

The xAI collections search retrieval strategy. xAI defaults to 'hybrid' server-side.

Type: Literal[‘hybrid’, ‘semantic’, ‘keyword’]

FileSearchProviderSettings

Bases: TypedDict

Provider-specific file search settings, keyed by the model class that reads them.

FileSearchTool

Bases: AbstractNativeTool

A native tool that allows your agent to search through uploaded files using vector search.

This tool provides a fully managed Retrieval-Augmented Generation (RAG) system that handles file storage, chunking, embedding generation, and context injection into prompts.

Supported by:

  • OpenAI Responses
  • Google (Gemini)
  • xAI (mapped to collections search)

Attributes

file_store_ids

The file store IDs to search through.

For OpenAI, these are the IDs of vector stores created via the OpenAI API. For Google, these are file search store names that have been uploaded and processed via the Gemini Files API. For xAI, these are collection IDs for the xAI collections search tool.

Type: Sequence[str]

max_num_results

The maximum number of results to return.

Supported by:

  • OpenAI Responses (mapped to max_num_results; OpenAI accepts 1 to 50)
  • xAI (mapped to collections search limit, defaults to 10 server-side)

Type: int | None Default: None

instructions

Optional instructions that guide how the collections search results are interpreted and ranked.

Deprecated: set provider_settings.xai.instructions instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • xAI

Type: Annotated[str | None, _moved_to_provider_settings(xai, instructions)] Default: None

retrieval_mode

The retrieval strategy for the search.

Deprecated: set provider_settings.xai.retrieval_mode instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • xAI (defaults to hybrid server-side)

Type: Annotated[Literal[‘hybrid’, ‘semantic’, ‘keyword’] | None, _moved_to_provider_settings(xai, retrieval_mode)] Default: None

provider_settings

Provider-specific file search settings, keyed by the model class that reads them.

Type: FileSearchProviderSettings | None Default: None

kind

The kind of tool.

Type: str Default: 'file_search'

AnthropicAdvisorToolSettings

Bases: TypedDict

Anthropic-specific settings for AdvisorTool.

Attributes

caching

The ephemeral cache TTL for the Anthropic advisor context. Maps to caching={'type': 'ephemeral', 'ttl': ...}.

Type: Literal[‘5m’, ‘1h’]

OpenRouterAdvisorToolSettings

Bases: TypedDict

OpenRouter-specific settings for AdvisorTool.

Attributes

forward_transcript

Whether OpenRouter should include the conversation transcript in the advisor request.

Type: bool

AdvisorProviderSettings

Bases: TypedDict

Provider-specific advisor settings, keyed by the model class that reads them.

AdvisorTool

Bases: AbstractNativeTool

A native tool that lets a faster executor model consult a stronger advisor model mid-generation.

The first-class fields describe behavior shared by the supported systems; system-specific options live in provider_settings. See the per-field docstrings for which provider supports each option.

Supported by:

  • Anthropic
  • OpenRouter

Attributes

model

The advisor model to consult, i.e. the model field of the provider’s advisor tool definition.

The executor/advisor pairing is validated by the provider’s API, not here. The accepted namespace depends on the executing provider: Anthropic model IDs (e.g. claude-opus-4-8) on Anthropic, OpenRouter catalog slugs (e.g. anthropic/claude-opus-4.8) on OpenRouter.

Supported by:

  • Anthropic
  • OpenRouter

Type: AdvisorModelName

max_uses

If provided, the advisor can be consulted at most this many times per request. Maps to max_uses.

This is a per-request cap, not a per-run budget: a run that spans multiple requests resets the count each request. Enforce a conversation-wide ceiling yourself if you need one.

Supported by:

  • Anthropic

OpenRouter caps advisor consultations per request with a fixed gateway limit and ignores max_uses.

Type: int | None Default: None

max_tokens

If provided, caps the advisor’s output tokens (minimum 1024). Maps to max_tokens on Anthropic and max_completion_tokens on OpenRouter.

When set, the Anthropic advisor result carries a stop_reason.

Supported by:

  • Anthropic
  • OpenRouter

Type: int | None Default: None

caching

If provided, caches the advisor context ephemerally with the given TTL. Maps to caching={'type': 'ephemeral', 'ttl': ...}.

Deprecated: set provider_settings.anthropic.caching instead, and read it from there too. This field holds only a value set on it directly, not one set in provider_settings.

Supported by:

  • Anthropic

OpenRouter’s advisor tool has no equivalent knob and ignores caching.

Type: Annotated[Literal[‘5m’, ‘1h’] | None, _moved_to_provider_settings(anthropic, caching)] Default: None

provider_settings

Provider-specific advisor settings, keyed by the model class that reads them.

Type: AdvisorProviderSettings | None Default: None

kind

The kind of tool.

Type: str Default: 'advisor'

NATIVE_TOOL_TYPES

Registry of all native tool types, keyed by their kind string.

This dict is populated automatically via __init_subclass__ when tool classes are defined.

Type: dict[str, type[AbstractNativeTool]] Default: {}

ImageAspectRatio

Supported aspect ratios for image generation tools.

The direct image API takes the wider ImageGenerationAspectRatio, of which these ten are a subset.

Default: Literal['21:9', '16:9', '4:3', '3:2', '1:1', '9:16', '3:4', '2:3', '5:4', '4:5']

ImageSize

Supported sizes for image generation tools.

Default: Literal['auto', '1024x1024', '1024x1536', '1536x1024', '512', '1K', '2K', '4K']

ImageQuality

Supported quality settings for OpenAI image generation.

Default: Literal['low', 'medium', 'high', 'xhigh', 'max', 'auto']

ImageGenerationModelName

Known OpenAI image generation model names, or another OpenAI image model ID.

Default: Literal['gpt-image-2.6-flare', 'gpt-image-2.6-sunburst', 'gpt-image-2', 'gpt-image-1.5', 'gpt-image-1-mini'] | str

AdvisorModelName

Known Anthropic advisor model names, or any other model ID string.

The literals list the latest models Anthropic accepts as the advisor — the stronger model an executor consults mid-generation. The executor/advisor pairing is validated by the API, not here. The literals are Anthropic model IDs; on OpenRouter, pass a catalog slug string instead (e.g. anthropic/claude-opus-4.8 or the ~anthropic/claude-opus-latest alias). See Anthropic’s model compatibility list.

Default: Literal['claude-fable-5-2', 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-opus-4-8', 'claude-sonnet-4-6'] | str

SUPPORTED_NATIVE_TOOLS

Set of all native tool types.

Default: frozenset(NATIVE_TOOL_TYPES.values())