翻篇收录说明
翻篇网页快照

Native Tools | Pydantic Docs

https://pydantic.dev/docs/ai/tools-toolsets/native-tools/

最近抓取:2026-12-03 06:42:44(北京时间)

最近内容变化:2026-12-03 06:42:44(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Use provider-executed native tools (formerly builtin tools) in Pydantic AI: web search, code execution, web fetch, image generation, file search, MCP and more.

正文摘录

Native Tools Native tools are provided and executed by LLM providers, while common tools are custom implementations executed by Pydantic AI. Pydantic AI supports the following native tools: WebSearchTool: Allows agents to search the web XSearchTool: Allows agents to search X/Twitter (xAI only) CodeExecutionTool: Enables agents to execute code in a secure environment ImageGenerationTool: Enables agents to generate images WebFetchTool: Enables agents to fetch web pages MemoryTool: Enables agents to use memory ComputerTool: Sends the agent’s computer tool to the model as the provider’s own computer use tool MCPServerTool: Enables agents to use remote MCP servers with communication handled by the model provider FileSearchTool: Enables agents to search through uploaded files using vector search (RAG) AdvisorTool: Lets a faster executor model consult a stronger advisor model mid-generation (Anthropic, OpenRouter) These tools are passed to the agent’s capabilities list, wrapped in NativeTool, and are executed by the model provider’s infrastructure. The calls and results show up in the model’s response as NativeToolCallPart and NativeToolReturnPart. Text the model writes before a native tool call is treated as commentary rather than output, unless no text follows the last native tool call: some providers, like Google GenerateContent with Gemini 2.5, report the searches that grounded a response after its text. Provider-independent options are fields on the native tool. When a provider has extra options, pass them to the tool’s provider_settings field under the key for the model class. The outer dictionary and each provider’s entry are TypedDicts, so type checkers and IDEs can validate and complete both levels. Each model reads only the options it knows from its own entry; like model settings, anything else is ignored rather than rejected. The key follows the model class you use, not who makes the underlying model: Claude through OpenRouterModel reads the openrouter entry, not anthropic, and OpenAIChatModel pointed at OpenRouter’s API reads neither. The provider’s API judges whether a value is one it accepts. Settings that restrict what a tool may do, such as allowed_domains, stay top-level fields, because a model that can’t apply them must not run the tool without them. To keep the local fallback of a provider-adaptive capability, pass the configured tool to its native= argument, for example WebSearch(native=WebSearchTool(provider_settings={'openrouter': {'engine': 'exa'}})). Some single-provider options used to be top-level fields, such as ImageGenerationTool.quality. Those fields still work but are deprecated: set the option in provider_settings instead, and read it from there too. The old field holds only a value set on it directly, so ImageGenerationTool(provider_settings={'openai': {'quality': 'high'}}).quality is still the default 'auto'. Setting the same option to different values in both places raises a UserError. See the Anthropic web tool settings, OpenRouter web search settings, and OpenRouter advisor settings. Google tool combinations Gemini 3 models support combining native tools with function tools, including output tools, and NativeOutput. Earlier Gemini models cannot use these combinations; use PromptedOutput for structured output alongside native tools. Dynamic Configuration Sometimes you need to configure a native tool dynamically based on the run context (e.g., user dependencies), or conditionally omit it. You can achieve this by wrapping a function with NativeTool in capabilities. The function takes RunContext as an argument and returns an AbstractNativeTool or None. This is particularly useful for tools like WebSearchTool where you might want to set the user’s location based on the current request, or disable the tool if the user provides no location. dynamic_native_tool.pyfrom pydantic_ai import Agent, RunContext, WebSearchTool from pydantic_ai.capabilities import NativeTool 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-6.1-sol', capabilities=[NativeTool(prepared_web_search)], deps_type=dict, ) # Run with location result = agent.run_sync( 'What is the weather like?', deps={'location': 'London'}, ) print(result.output) #> It's currently raining in London. # Run without location (tool will be omitted) result = agent.run_sync( 'What is the capital of France?', deps={'location': None}, ) print(result.output) #> The capital of France is Paris. The function is called for each model request, with the model about to receive it as ctx.model, so it can decide by that model’s provider or profile. When the ModelFallback capability moves a request to another model, the function is called again with that model as ctx.model, so each model gets the tool it would get on its own. Web Search Tool The WebSearchTool allows your agent to search the web, making it ideal for queries that require up-to-date data. Provider Support ProviderSupportedNotesOpenAI Responses✅Full feature support. To include the sources of each search on the NativeToolReturnPart that’s available via ModelResponse.native_tool_calls, enable the OpenAIResponsesModelSettings.openai_include_web_search_sources model setting. To include the text the model read and send it back on later requests, which otherwise can’t see it, enable OpenAIResponsesModelSettings.openai_include_web_search_results: one search and one opened page add about 24,000 characters to the input of each later request.Anthropic✅Full feature supportDeepSeek✅With DeepSeekChatModel or DeepSeekResponsesModel and deepseek-flash. No parameter support, so a restricting parameter makes the tool unsupported. See DeepSeek native web tools.Google GenerateContent✅No parameter support, so a restricting parameter makes the tool unsupported. The search sources are the NativeToolReturnPart’s content, except on Gemini 3 with the Gemini API, where they’re under the sources key of the last web search return’s content, as Gemini doesn’t say which search found which source. Gemini 2.5 and Google Cloud report their searches after the text they ground, so the call and return come after the text. See Google tool combinations.Google Interactions✅No parameter support, so a restricting parameter makes the tool unsupported. Each search is its own call and return, in the order the model ran it: the call’s args hold its queries, the return’s content holds Google’s search_suggestions, and the sources are citations on the text.xAI✅Supports blocked_domains, allowed_domains, and user_location parameters.Groq✅Limited parameter support. To use web search capabilities with Groq, you need to use the compound models.OpenRouter✅Uses OpenRouter’s Beta web-search server tool. The model can make 0–N searches. Recorded requests verify only that OpenRouter accepts the parameter names; the per-engine effects below are per OpenRouter’s docs: native search ignores search_context_size; user_location is native-only; native OpenAI ignores blocked_domains; and max_uses works with non-native or Anthropic native search. Search sources surface in provider_details['annotations'], but only when a non-native engine ran the search.OpenAI Chat Completions❌Not supportedBedrock❌Not supportedMistral❌Not supportedCohere❌Not supportedHuggingFace❌Not supported Usage web_search_anthropic.pyfrom pydantic_ai import Agent, WebSearchTool from pydantic_ai.capabilities import NativeTool agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[NativeTool(WebSearchTool())]) result = agent.run_sync('Give me a sentence with the biggest news in AI this week.') print(result.output) #> Scientists have developed a universal AI detector that can identify deepfake videos. (This example is complete, it can be run “as is”) With Anthropic, the number of searches is reported as web_search_requests in RequestUsage.details and included in RunUsage.cost. With DeepSeek, RequestUsage.details holds the non-zero tool_search, tool_fetch and tool_image_search counts. DeepSeek doesn’t bill these calls, so web_searches stays unset. With Google GenerateContent, the number of Google Search grounding queries is reported as web_search_requests in RequestUsage.details, and the billed count as web_searches on RequestUsage: one per unique query on Gemini 3, and one per grounded request that returned a web source on Gemini 2.5 and older. The billed count is included in RunUsage.cost, without deducting Google’s free grounding allowance. With Google Interactions, Google’s grounding tool counts are reported in RequestUsage.details as <tool>_count, such as google_search_count, and the billed count as web_searches on RequestUsage: the google_search_count on Gemini 3, and one per grounded request on Gemini 2.5 and older, whether or not a web source came back. The billed count is included in RunUsage.cost. With OpenAI, you must use their Responses API to access the web search tool. The number of searches is reported as web_search_requests in RequestUsage.details and included in RunUsage.cost. Pages the model opens or searches within don’t count as searches. web_search_openai.pyfrom pydantic_ai import Agent, WebSearchTool from pydantic_ai.capabilities import NativeTool agent = Agent('openai-responses:gpt-6.1-sol', capabilities=[NativeTool(WebSearchTool())]) result = agent.run_sync('Give me a sentence with the biggest news in AI this week.') print(result.output) #> Scientists have developed a universal AI detector that can identify deepfake videos. (This example is complete, it can be run “as is”) Configuration Options The WebSearchTool supports several configuration parameters: web_search_configured.pyfrom pydantic_ai import Agent, WebSearchTool, WebSearchUserLocation from pydantic_ai.capabilities import NativeTool agent = Agent( 'anthropic:claude-sonnet-5-5', capabilities=[ NativeTool( WebSearchTool( search_cont