页面简介
Advanced Pydantic AI function tools: return images and files, custom schemas, strict mode, dynamic tools, tool choice, retries, parallel calls and tool search.
正文摘录
Advanced Tool Features This page covers advanced features for function tools in Pydantic AI. For basic tool usage, see the Function Tools documentation. Tool Output Tools can return anything that Pydantic can serialize to JSON, as well as audio, video, image or document content depending on the types of multi-modal input the model supports: function_tool_output.pyfrom datetime import datetime from pydantic import BaseModel from pydantic_ai import Agent, DocumentUrl, ImageUrl from pydantic_ai.models.openai import OpenAIResponsesModel class User(BaseModel): name: str age: int agent = Agent(model=OpenAIResponsesModel('gpt-6.1-sol')) @agent.tool_plain def get_current_time() -> datetime: return datetime.now() @agent.tool_plain def get_user() -> User: return User(name='John', age=30) @agent.tool_plain def get_company_logo() -> ImageUrl: return ImageUrl(url='https://iili.io/3Hs4FMg.png') @agent.tool_plain def get_document() -> DocumentUrl: return DocumentUrl(url='https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf') result = agent.run_sync('What time is it?') print(result.output) #> The current time is 10:45 PM on April 17, 2025. result = agent.run_sync('What is the user name?') print(result.output) #> The user's name is John. result = agent.run_sync('What is the company name in the logo?') print(result.output) #> The company name in the logo is "Pydantic." result = agent.run_sync('What is the main content of the document?') print(result.output) #> The document contains just the text "Dummy PDF file." (This example is complete, it can be run “as is”) Some models (e.g. Gemini) natively support semi-structured return values, while some expect text (OpenAI) but seem to be just as good at extracting meaning from the data. If a Python object is returned and the model expects a string, the value will be serialized to JSON. A value whose JSON form is a string, such as a datetime, UUID or Decimal, is sent as that string without JSON quotes, which is also what it reloads as after you store and load the message history, so the model sees the same text either way. Where a returned file is sent Whether a file can travel inside the tool result depends on the model and the file’s media type: Inside the tool result, where the API and the media type both allow it: Anthropic and OpenAI Responses for images and documents, Gemini 3 for the types listed in its GoogleModelProfile’s google_supported_mime_types_in_tool_returns, and Bedrock for the media kinds a model family supports. On the user channel — the same channel the person talking to your agent uploads on — for everything else: OpenAI Chat Completions, Groq, Mistral, xAI, Hugging Face and Gemini 2.5 and earlier accept only text in a tool result, and Gemini 3 and Bedrock fall back here for a media type they can’t carry (audio and video on Gemini 3, or a kind outside a Bedrock family’s set). As a note in its place, where the model can’t read that kind of file at all, or that media type, as its profile’s file-input flags say. For example: an image in a format outside JPEG, PNG, GIF and WebP on Claude and OpenAI models, such as HEIC, a GIF on xAI, audio other than WAV and MP3 on OpenAI Chat Completions, documents other than text on Chat Completions providers without file input, such as Azure and vLLM, audio and video on Anthropic, OpenAI Responses, Mistral and xAI, video on OpenAI Chat Completions, audio on OpenAI’s models without audio in their name, images on Codestral, Voxtral and GLM-5.3 (but not GLM-5.3 Flash) on Mistral, audio on Bedrock and video on Bedrock outside Nova, anything but images on Groq and Hugging Face, and any file on Cohere, as well as documents other than PDF and plain text on Anthropic, and other than PDF and text formats on Mistral. To keep the model from reading a tool’s output as something the user attached, a file taking the user channel is framed with the call it came from: <pyai:tool_result tool_name="get_photo" tool_call_id="call_9cQx" file_id="d9a13f"> [the image] </pyai:tool_result> The tool result itself carries See file d9a13f. in place of the file, and each file gets its own tags, so the model can match every file to the call that produced it even when several tools return media in the same step. A failed Gemini tool return is the one exception: its result is Gemini’s native error string, which takes no file references, so there the tags alone carry the attribution. Realtime sessions frame tool-produced files the same way. This mirrors how a mid-conversation SystemPromptPart is framed as <system>...</system> for a model whose API has no place to put one. The framing is applied while the request is built and is never stored: the file stays on the ToolReturnPart in your message history, so the same history replayed against a model that takes files natively puts them in the tool result with no framing at all. Because it is ordinary prompt text, the framing tells the model where content came from rather than proving it — see the trust boundary. A file the model can’t read would fail the request if it were sent, which is out of proportion for something the model asked a tool for, so it is replaced in the tool result by a note naming it, and the run goes on: File d9a13f (audio/mpeg, 48,213 bytes) was not sent: this model cannot read audio files. The model can then tell the user, or try another tool. Like the framing, the note is only in the request: the file stays on the ToolReturnPart in your message history, and each model a FallbackModel tries decides for itself, so one that can read the file is sent it. With the File Understanding capability, the file is described in text by a model that can read it instead. A file in a user prompt, or in ToolReturn.content, is sent as it is, and a model that can’t take it still fails the request: you or your user chose to send it. Advanced Tool Returns For scenarios where you need more control over both the tool’s return value and the content sent to the model, you can use ToolReturn. This is particularly useful when you want to: Separate the structured return value from additional content sent to the model Explicitly send content as a separate user message (rather than in the tool result) Include additional metadata that shouldn’t be sent to the LLM Reveal deferred tools by name for the next model request Here’s an example of a computer automation tool that captures screenshots and provides visual feedback: advanced_tool_return.pyfrom pydantic_ai import Agent, BinaryContent, ToolReturn from pydantic_ai.models.test import TestModel agent = Agent(TestModel()) @agent.tool_plain def click_and_capture(x: int, y: int) -> ToolReturn: """Click at coordinates and show before/after screenshots.""" before_screenshot = BinaryContent(data=b'\x89PNG', media_type='image/png') # perform_click(x, y) after_screenshot = BinaryContent(data=b'\x89PNG', media_type='image/png') return ToolReturn( return_value=f'Successfully clicked at ({x}, {y})', content=[ 'Before:', before_screenshot, 'After:', after_screenshot, ], metadata={ 'coordinates': {'x': x, 'y': y}, 'action_type': 'click_and_capture', }, ) # The model receives the rich visual content for analysis # while your application can access the structured return_value and metadata result = agent.run_sync('Click on the submit button and tell me what happened') print(result.output) #> {"click_and_capture":"Successfully clicked at (0, 0)"} return_value: The actual return value used in the tool response. This is what gets serialized and sent back to the model as the tool’s result. Can include multimodal content directly (see Tool Output above). tools: Names of tools marked with defer_loading=True that this call made available. Pydantic AI records them in a ToolAvailabilityDeltaPart immediately after this call’s ToolReturnPart, in the same ModelRequest. The names remain revealed when history is resumed, while the current tool definitions still come from the agent. content: Content sent as a separate user message after the tool result. Use this when you explicitly want content to appear outside the tool result, or when combining structured return values with rich content. It is sent as you wrote it — this is you adding user content deliberately, so it is not framed the way a file the model API couldn’t take is (see Where a returned file is sent). metadata: Optional metadata that your application can access but is not sent to the LLM. Useful for logging, debugging, or additional processing. Some other AI frameworks call this feature ‘artifacts’. This separation allows you to provide rich context to the model while maintaining clean, structured return values for your application logic. For multimodal content that should be sent natively in the tool result (when supported by the model), return it directly from the tool function or include it in return_value (see Tool Output above). Custom Tool Schema If you have a function that lacks appropriate documentation (i.e. poorly named, no type information, poor docstring, use of *args or **kwargs and suchlike) then you can still turn it into a tool that can be effectively used by the agent with the Tool.from_schema function. With this you provide the name, description, JSON schema, and whether the function takes a RunContext for the function directly: from pydantic_ai import Agent, Tool from pydantic_ai.models.test import TestModel def foobar(**kwargs) -> str: return kwargs['a'] + kwargs['b'] tool = Tool.from_schema( function=foobar, name='sum', description='Sum two numbers.', json_schema={ 'additionalProperties': False, 'properties': { 'a': {'description': 'the first number', 'type': 'integer'}, 'b': {'description': 'the second number', 'type': 'integer'}, }, 'required': ['a', 'b'], 'type': 'object', }, takes_ctx=False, ) test_model = TestModel() agent = Agent(test_model, tools=[tool]) result = agent.run_sync('testing...') print(result.output) #> {"sum":0} Pydantic AI does not validate tool arguments here; it passes them as keywo