页面简介
Pydantic AI upgrade guide and changelog: the breaking changes in each release, how to install V2, and the recommended path to migrate your code from V1.
正文摘录
Upgrade Guide In September 2025, Pydantic AI reached V1 and committed to API stability: no changes that break your code until V2. V2 is now available, collecting the breaking and behavior changes that stability guarantee didn’t allow. This guide is the canonical place to learn what’s in V2, how to install it, and how to upgrade; for the guarantees behind these version numbers, see the Version Policy. Deprecations Functionality deprecated in a V2 release keeps working until V3, and using it raises a PydanticAIDeprecationWarning naming its replacement. Resolving these as they appear is the smooth path to the next major, the same way resolving V1’s warnings was the smooth path to this one. Deprecated in V2, to be removed in V3 Calling a RunUsage, as in V1’s result.usage(), returns that same usage and warns. usage became a property in V2, and the call used to raise TypeError: 'RunUsage' object is not callable, which code that wraps usage accounting in except Exception turned into silently zero usage. Drop the parentheses: result.usage. RetryPromptPart is deprecated in favor of the two parts it conflated: a retry that answers a tool call is that call’s own ToolReturnPart with outcome='retried', and one that answers no tool call is a RetryFeedbackPart. The old part reached the model as bare user text in the second case, which the model couldn’t tell from something a person wrote (#6404, #7799). Pydantic AI no longer emits it, and constructing one warns. What keeps working: a 'retry-prompt' part in a serialized history loads as whichever of the two it always meant, and an instance your own code holds, including one handed back through DeferredToolResults, is translated the same way before it reaches a model. The direct helpers send it in that new shape too. Calling Model.request() or Model.count_tokens() yourself skips that translation but still works: a tool-bound one goes out as that call’s retried result, and a tool-less one as the user text it always rendered as. sanitize_messages keeps client-returned retry feedback: it translates a tool-less one into the RetryFeedbackPart it always meant, keeps a 'validation_error' or 'model_retry' part as sent (it reaches the model fenced, in the user voice), and demotes a 'no_output' part, the one cause rendered in the system voice, to that same fenced, attributed user text, since a client can forge it; pass strip_system_prompts=False to keep a 'no_output' part as sent. What you need to change: isinstance(part, RetryPromptPart) no longer matches, in new runs or in loaded histories, so code that finds tool errors that way silently finds none (v2.60.0). Use is_retry(part) instead, which matches both parts above (on a release that predates it, check isinstance(part, RetryFeedbackPart) or (isinstance(part, ToolReturnPart) and part.outcome == 'retried')), as in Finding tool errors in history. Each records why the retry happened, and which attempt it is against which limit, in a RetryInfo on its retry field, which tool spans also carry as pydantic_ai.tool.retry.* attributes. ToolRetryError.tool_retry holds one of those two parts, so read tool_name off it only after checking for a ToolReturnPart. What the model now sees: a tool retry carries the serialized validation errors or the ModelRetry message, with no N validation errors: header and no Fix the errors and try again. suffix. One that answers no call arrives in the voice its cause calls for: validation errors and a ModelRetry message in the user voice, inside a <pyai:validation_errors> or <pyai:retry_feedback> fence behind one line saying the application, not the user, is speaking, and the framework’s fixed request for usable output in the system voice. v2.68.0 renamed those fences from <validation_errors> and <retry_feedback> (#11813), so code that matches them in stored or logged prompts has to match the new names, and made such feedback count as something the framing announcement explains: by default, a conversation that didn’t have the announcement yet gets it from its first fenced retry on, as a system message on models with a mid-conversation system role and at the start of the system prompt, when there is one, on the rest. On providers without a native tool error channel, a retried tool call’s validation errors go in the {"error": ...} wrapper as a JSON array rather than as a string holding one, and Anthropic and Bedrock get them as one text block. Client-returned retry feedback is kept by sanitize_messages and the UI adapters rather than stripped, and a 'no_output' part among it goes out as fenced user text rather than in the system voice. Retries in a history stored before upgrading are rendered the new way too, since rendering happens when each request goes out, so a conversation’s first request after upgrading misses the provider’s prompt cache from its first retry onward, once. A decision model judges a retried tool call as that call’s tool_return, where it had a retry entry. On ag-ui-protocol below 0.1.11, AGUIAdapter.dump_messages now also warns on a run that retried its own output. See Retries. Vercel AI dumps keep a request’s part order: VercelAIAdapter.dump_messages now writes a ModelRequest as one UIMessage per run of same-role parts, in the order they were authored, instead of putting every system part first. This applies with no retries at all: a request holding an enqueued SystemPromptPart after its UserPromptPart now dumps as a user message followed by a system message, and positional message ids shift with it. The request’s metadata rides on its last user message, or its last message when it has none. Reading pydantic_ai.models.anthropic.DEPRECATED_ANTHROPIC_MODELS returns the same model ids and warns. Pydantic AI no longer uses it: AnthropicModelName is a curated list, and the Anthropic SDK no longer lists the retired ids it excluded. Keep your own list of retired model ids, from Anthropic’s model deprecations page. The json_mode_schema_prompt argument and attribute of MistralModel warn. The prompt was never sent, so nothing changes when you stop passing it. Set the instructions for prompted output with PromptedOutput(template=...) or the model profile’s prompted_output_template. Reading pydantic_ai.models.mistral.SIMPLE_JSON_TYPE_MAPPING or VALID_JSON_TYPE_MAPPING returns the same mapping and warns. Pydantic AI no longer uses them: define your own mapping if you need one. Catching up across V2 minor releases If you’re upgrading across several V2 minor releases at once, these are the changes since v2.0.0 that can make existing code behave differently. Each one is listed under the release that shipped it, newest first, with a link to its pull request. They come from the “Compatibility Notes” section of each release’s notes on GitHub Releases, which also lists the bug fixes and features of each release. Release notes have had a Compatibility Notes section since v2.33.0, so for v2.1.0 through v2.32.2, read each release’s notes on GitHub Releases. Later releases not listed below have no compatibility notes. v2.75.0 Keep workspace files below 'operator' authority out of the instructions in RepoContext, Skills and Memory, and add lowest_authority_under. Text from a workspace file below 'operator' authority no longer reaches the instructions: RepoContext names the working directory’s file for the model to read with its file tools and sends an ancestor’s file as framed data, Skills offers such skills through list_skills and load_skill tools instead of load_capability, and Memory attributes such a snapshot to its MEMORY.md. Files at 'operator', the default, are unchanged. Durable runs now record extra realpath workspace calls at run start, so let in-flight runs finish, or use Temporal worker versioning or a new DBOS app version, before upgrading. RepoContext(autoload_instructions=False) with nested instruction files misses the prompt cache once on the first request after upgrading (#11837) Raise empty and unreadable model responses as ModelEmptyResponseError and ModelInvalidResponseError, so FallbackModel and ModelFallback fall back on them. With their default fallback_on, FallbackModel and ModelFallback now fall back on an empty stream, an OpenAI Chat completion without choices, and an OpenAI Chat body that isn’t JSON or doesn’t match the schema, where the run used to raise UnexpectedModelBehavior. Both new errors subclass ModelAPIError and UnexpectedModelBehavior, so except UnexpectedModelBehavior still catches them, but an except ModelAPIError placed before it now takes them; an empty Mistral or OpenAI choices raises one instead of AssertionError or IndexError. To keep raising instead of falling back, pass a fallback_on that leaves them out, such as lambda e: isinstance(e, ModelAPIError) and not isinstance(e, UnexpectedModelBehavior) (#12108) Resolve Pax /permissions approvals through a token-taking HandleDeferredToolCalls handler with harness approval_ask. pydantic_ai_pax.runtime.permissions.approval_handler still returns an ApprovalHandler, but its handler now takes a resume token: it runs after every two-parameter deferred tool call handler wherever it is listed, and in a durable run on any engine but AWS Lambda it raises UserError instead of asking. Pax itself behaves as before. To run a handler of your own after it, make that handler take a token too; under a durable engine other than Lambda, bind ApprovalHandler(lambda ctx, requests: ask_permissions(requests, approve)) instead (#13195) Share one instructions string across a conversation’s requests instead of keeping a copy per request. ModelMessagesTypeAdapter is now built with an AfterValidator, and in a history it loads, requests with equal instructions hold the same string object. Its type, JSON schema, serialization and validated values are unchanged. Compare instructions with ==, not is (#13308) Send Coder’s no-unrequested-sub-agents line only to models that need it, and let instructions branch on the model serving each request. Coder with SubAgents