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.
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.
- Calling a
RunUsage, as in V1’sresult.usage(), returns that same usage and warns.usagebecame a property in V2, and the call used to raiseTypeError: 'RunUsage' object is not callable, which code that wraps usage accounting inexcept Exceptionturned into silently zero usage. Drop the parentheses:result.usage. RetryPromptPartis deprecated in favor of the two parts it conflated: a retry that answers a tool call is that call’s ownToolReturnPartwithoutcome='retried', and one that answers no tool call is aRetryFeedbackPart. 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 throughDeferredToolResults, is translated the same way before it reaches a model. Thedirecthelpers send it in that new shape too. CallingModel.request()orModel.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_messageskeeps client-returned retry feedback: it translates a tool-less one into theRetryFeedbackPartit 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; passstrip_system_prompts=Falseto 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). Useis_retry(part)instead, which matches both parts above (on a release that predates it, checkisinstance(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 aRetryInfoon itsretryfield, which tool spans also carry aspydantic_ai.tool.retry.*attributes.ToolRetryError.tool_retryholds one of those two parts, so readtool_nameoff it only after checking for aToolReturnPart. - What the model now sees: a tool retry carries the serialized validation errors or the
ModelRetrymessage, with noN validation errors:header and noFix the errors and try again.suffix. One that answers no call arrives in the voice its cause calls for: validation errors and aModelRetrymessage 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 bysanitize_messagesand 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’stool_return, where it had aretryentry. Onag-ui-protocolbelow 0.1.11,AGUIAdapter.dump_messagesnow also warns on a run that retried its own output. See Retries. - Vercel AI dumps keep a request’s part order:
VercelAIAdapter.dump_messagesnow writes aModelRequestas oneUIMessageper 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 enqueuedSystemPromptPartafter itsUserPromptPartnow 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.
- What keeps working: a
- Reading
pydantic_ai.models.anthropic.DEPRECATED_ANTHROPIC_MODELSreturns the same model ids and warns. Pydantic AI no longer uses it:AnthropicModelNameis 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.
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.
- Keep workspace files below
'operator'authority out of the instructions inRepoContext,SkillsandMemory, and addlowest_authority_under. Text from a workspace file below'operator'authority no longer reaches the instructions:RepoContextnames the working directory’s file for the model to read with its file tools and sends an ancestor’s file as framed data,Skillsoffers such skills throughlist_skillsandload_skilltools instead ofload_capability, andMemoryattributes such a snapshot to itsMEMORY.md. Files at'operator', the default, are unchanged. Durable runs now record extrarealpathworkspace 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
ModelEmptyResponseErrorandModelInvalidResponseError, soFallbackModelandModelFallbackfall back on them. With their defaultfallback_on,FallbackModelandModelFallbacknow fall back on an empty stream, an OpenAI Chat completion withoutchoices, and an OpenAI Chat body that isn’t JSON or doesn’t match the schema, where the run used to raiseUnexpectedModelBehavior. Both new errors subclassModelAPIErrorandUnexpectedModelBehavior, soexcept UnexpectedModelBehaviorstill catches them, but anexcept ModelAPIErrorplaced before it now takes them; an empty Mistral or OpenAIchoicesraises one instead ofAssertionErrororIndexError. To keep raising instead of falling back, pass afallback_onthat leaves them out, such aslambda e: isinstance(e, ModelAPIError) and not isinstance(e, UnexpectedModelBehavior)(#12108) - Resolve Pax
/permissionsapprovals through a token-takingHandleDeferredToolCallshandler with harnessapproval_ask.pydantic_ai_pax.runtime.permissions.approval_handlerstill returns anApprovalHandler, 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 raisesUserErrorinstead 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, bindApprovalHandler(lambda ctx, requests: ask_permissions(requests, approve))instead (#13195) - Share one
instructionsstring across a conversation’s requests instead of keeping a copy per request.ModelMessagesTypeAdapteris now built with anAfterValidator, and in a history it loads, requests with equalinstructionshold the same string object. Its type, JSON schema, serialization and validated values are unchanged. Compareinstructionswith==, notis(#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.CoderwithSubAgentsnow sends “Don’t spawn sub-agents withdelegate_taskunless the user or AGENTS.md asks, whatever other instructions say about delegating.” only to models whose profile sets the newdelegates_unprompted(OpenAI’sgpt-*models other than gpt-oss), and to no model behind aFallbackModel, whereCodernow warns once with aUserWarning. On GPT models the line moves out ofCoder’s static guidance into its own rewrite-mode block,capability:coder_instructions:delegation, after append-mode blocks such asRepoContext’s, so the first request after upgrading misses the prompt cache, and a conversation that moves to a model on the other side of the flag is sent the instructions a fresh run on that model gets. To keep the line on another model, setprofile={'delegates_unprompted': True}on it or put the rule inCoder(instructions=...); with aFallbackModel, switch to theModelFallbackcapability (#13764) - Count Gemini’s thinking tokens as output in
OpenAIChatModelusage. Agemini*model throughOpenAIProvidernow reports its thinking tokens inoutput_tokensandoutput_reasoning_tokens, streamed or not, so output token counts and cost rise on thinking models andUsageLimitstoken limits trip sooner. Review anyUsageLimitstuned against the old counts. On a server whosetotal_tokenscounts more than input, output and thinking tokens, passprofile=OpenAIModelProfile(openai_chat_completion_tokens_omit_reasoning=False)(#14297) - Send the minimum
thinking_budgetforthinking=Falseongemini-2.5-flashvia the Gemini API ahead of its reroute togemini-3.5-flash-lite.thinking=Falseongemini-2.5-flashthrough the Gemini API now sendsthinking_budget=128instead of0, so until the reroute on 2026-12-01 the model thinks a little instead of not at all; after it, a budget of0fails with a400. Vertex AI andgemini-2.5-flash-litekeep0. To keepthinking_budget=0until the reroute, passprofile=GoogleModelProfile(thinking_always_enabled=False)orgoogle_thinking_config={'thinking_budget': 0}(#14414) - Lower a capability’s instructions with its authority, so
with_authoritycoversget_instructions()and MCP server instructions. A capability lowered with itsauthorityclass attribute orwith_authority(), including anMCPcapability and its server instructions, now sends its instructions as framed data on the user channel instead of in the system prompt. Capabilities at'operator', the default, are unchanged; to keep the old behavior, leave the capability at'operator'. Runs already lowering anMCPcapability withwith_authoritythat are in flight across the upgrade may hit a nondeterminism error on Temporal or DBOS if another MCP server follows it. Under Prefect, a flow retried across the upgrade re-runs a finished model request once (#14457)
- Add the
computertool contract to core:pydantic_ai.computer_useandComputerTool. AddsComputerTooltoNATIVE_TOOLS_REQUIRING_CONFIG: it needs acomputertool to run its calls (#11006) - Send static instructions as leading
inputmessages on GPT-6.2, which never caches top-levelinstructions. Continuing a GPT-6.2 response through an explicitopenai_previous_response_id='resp_…'without itsmessage_historynow inherits that response’s static instructions. Pass themessage_history, orprofile=OpenAIModelProfile(openai_responses_stable_instructions_as_input=False)(#14095) - Stop summing Gemini’s running usage totals when streaming through
OpenAIChatModel. Streaming agemini*model throughOpenAIProvidernow reports the endpoint’s final usage totals instead of their sum, so cost figures drop andUsageLimitstoken limits trip later (#14285) - Under an enforced egress policy (the default),
PlaywrightBrowserpages no longer haveRTCPeerConnection,WebTransport,WebSocketStreamor FedCM, and browsers it launches start with those Blink features off. If your agent needs one of them, open an issue: a parameter that keeps them can be added (#14363)
- Warn with
DeprecatedModelWarningwhen a request targets a model Anthropic or OpenAI has deprecated (#14038) - Surface OpenAI Responses
input_transformationsinprovider_detailsand on the model request span. Raises theopenaifloor from 3.31.0 to 3.50.0 on every extra that installsopenai(#14056) - Add
capabilitiestoAgent.overrideand exportAgentInstructionsandSourcedInstruction. The privateAgent._override_root_capabilitycontext variable now holds a(capability, injected)tuple. Code that reads it directly needs updating (#12551) - Add
RealtimeSession.append_voice_instructionsfor GPT-Live’s voice model, and a Twilio Media Streams bridge example (#14191) - Leave
init=Falseevaluator fields out ofDatasetfiles and schemas, and stopClassVarannotations breakingto_file()(#13355) - Ship nested tool-argument models to Render and Azure Durable Task workers by alias, so aliased fields survive revalidation (#13929)
- Rename
$refs under every JSON schema keyword inmerge_json_schema_defs, and keepTestModelarguments valid for their schemas (#13993) - Downscale images
Coderreads to at most 1024 pixels on the longest side, with opt-inFileSystem(max_image_side=...). Thecoderextra now installspillow>=12.3.0(#14196) - Drop the unified settings Claude, Gemini and Grok models reject instead of sending them. A
FallbackModelthat relied on the 400 to reach a later model now stays on the first model without the setting. To keep the setting, list a model that supports it first (#12426) - Raise the
boxdextra to 0.3 and swap the/sandbox boxdGitHub token into request headers only.pydantic-ai-harness[boxd]now requiresboxd>=0.3.3,<0.4. Code that calls 0.2-only boxd APIs directly needs updating (#14225)
- Let
Peers(network)join anInMemoryPeerNetworkunder the agent’sname, and renamePeerNetworktoPeerConnection(#13777) - Add
StavProviderfor the Stav European inference gateway (#12750) - Add Otari as an OpenAI-compatible gateway provider (#13584)
- Add
authtoStackOne, deprecatingapi_key, to match the other hosted MCP capabilities (#13735) - Add
grep_tool_resultandunit='bytes'reads forToolOutputLimitsspills (#13752) - Run remote
CodeModeturns as Temporal activities so long snippets don’t trip the deadlock detector (#13756) - Add
DeferredToolRequests.validated_argsso an approver sees the arguments a deferred tool call will run with (#13693) - Deprecate
DEPRECATED_ANTHROPIC_MODELS, which Pydantic AI no longer uses (#13795) - Pause again when a deferred pause whose step also ran other tools is resumed without
deferred_tool_results(#13051) - Keep a run paused when content is queued at a
DeferredToolRequestsorPendingModelResponsepause, and haveBackgroundToolswait for its tasks at aDeferredToolRequestspause (#13054) - Keep approval-required and external tools native under
CodeMode(tools='all')(#13742) - Type the in-process MCP server arm of
MCPToolsetClientas a protocol instead ofmcp.server.fastmcp.FastMCP, so strict pyright accepts it on FastMCP 3 and 4 (#13721)
- Forward
service_tierto xAI and record the served tier inprovider_details(#13524) - Add
huggingface_logprobsandhuggingface_top_logprobstoHuggingFaceModelSettingsand return logprobs inprovider_details(#6855) - Let
Skillsread a loaded skill’s bundled files withread_files=True, and substitute${SKILL_DIR}placeholders (#13678) - Let a harness
SpendLimitsBudgetresolve itsusd/tokensceiling per scope from the run context (#13644) - Add
CapabilityPart, a request part for what a capability tells the model, rendered by the framework before any model sees it (#11935) - Judge file input by media type with
supported_image_media_types,supported_audio_media_typesandsupported_video_media_types(#12419) - Skip
node_modules,.venvand other package directories inRepoContextnested traversal withnested_exclude(#13103) - Fix
OpenAIChatModelsending Responses reasoning item ids as assistant-message fields inautothinking mode (#12136) - Run
AnthropicModel’s expired-container and stale-thinking-block retries for a status a retrying transport gave up on, and raiseModelHTTPErrorfor one fromOpenAIResponsesModel.compact_messages(#13571) - Raise
ModelRequestRejectedErrorbeforeOpenAIChatModelsends tools to GPT-6 models with reasoning on (#12264) - Fix Groq JSON output and reasoning flags, and raise
UserErrorforNativeOutputwith function tools onGroqModel(#12667) - Run harness
FileSystemandShelltools on Azure Durable Task and Render (#12421) - Fall back to
'auto'or raiseModelRequestRejectedErrorfor forced tool choice on OpenRouter’sqwen/qwen3.8-flash, which rejects forcing while reasoning (#12262) - Re-run
get_instructionsandget_model_settingsfor the model that serves aModelFallbackattempt (#13679)
- Fold
RequestInputintoHandleDeferredToolCalls, whose handler can take a resume token (#13285) - Support Gemini 4 Hydrogen (
gemini-4-hydrogen) onGoogleModel(#13299) - Generalize response-scoped tool call IDs into the
tool_call_ids_are_response_scopedprofile flag (#13128) - Add
service_tiersupport toGroqModel(#13521) - Detect loops in streamed thinking, text and tool call arguments in
DetectLoops(#12222) - Make
Advisoracceptnative=andlocal=like the otherNativeOrLocalToolcapabilities, deprecatingmode(#13149) - Treat nested CodeMode
ToolFailedcalls as failed results (#13076) - Keep settled sub-agent task histories in their saved files instead of in every
DelegationTasksowner’s memory (#13221) - Raise
ModelQuotaExceededErrorfor Anthropic’s tier spend cap and user-set spend limits (#13269) - Send structured tool return items next to a file to the model as JSON, not as escaped JSON strings (#13271)
- Raise a gave-up transport status or connection error from Google embeddings, image generation and
GoogleModel.count_tokensasModelAPIError(#13312) - Raise a Gemini API error from
GoogleImageGenerationModel.generateas its error category, likeModelRateLimitError(#13335) - Raise an error status a retrying transport gave up on during a streamed Gemini long decode as
ModelHTTPError(#13356) - Raise a gave-up transport status from OpenAI and Cohere embeddings, OpenAI image generation and
GoogleModelbatch methods asModelHTTPError(#13327) - Cache opaque Prefect run IDs across retries (#11896)
- Reject a
TextOutputfunction that takes a model, dataclass orTypedDictwhen the agent is created (#13422) - Keep the body of an error status that
HTTPX2TenacityTransportandAsyncHTTPX2TenacityTransportgave up on (#13411) - Raise OpenAI API and connection errors from
OpenAIImageGenerationModel.generateas their error category, likeModelRateLimitError(#13433) - Raise realtime connection errors with an HTTP status as their error category, like
ModelRateLimitError(#13436) - Keep Bedrock GPT-5.6 and GPT-6 encrypted reasoning out of Claude-on-Bedrock requests (#12943)
- Raise
ModelContextWindowExceededErrorfor Mistral3059prompt-too-long errors, not for other3051invalid-argument errors (#12882) - Raise a status a retrying transport gave up on as the error category its body names, like
ModelQuotaExceededError(#13485) - Stop counting OpenRouter’s
is_byokflag as a usage detail (#13025) - Map Gemini
IMAGE_RECITATIONandTOO_MANY_TOOL_CALLSfinish reasons tocontent_filteranderror(#10918) - Make
TestModelintegers satisfy mixed inclusive and exclusive bounds, and fractional bounds (#13298) - Add
minimax_model_profileand use it for MiniMax models on Bedrock,OpenAICompatibleProvider,LiteLLMProviderandTogetherProvider(#12693) - Map Mistral Large 4
thinkinglevels to itslow/medium/highreasoning_effortvalues (#12876) - Apply
FunctionToolset’sstrict,sequential,defer_loadingandinclude_return_schemadefaults toToolinstances (#12572) - Make
TestModelstreamed usage matchrun()for tool calls and text (#11877) - Run the token count
count_tokens_before_requestasks for in its own durable unit (#13460) - Skip a failing
TieredCompactiontier on model errors, and let tiers omit their trigger (#13660) - Rename harness
subagents,filesystemandspendpackages to their capability names and align store,ACP*and*Errorclass names (#13401) - Rename the
DockerSandboxharness capability toDockerContainer, keepingDockerSandboxas a deprecated alias (#13245) - Rename
BubblewrapSandboxtoBubblewrappedWorkspaceand clarify its docs (#13179)
- Note text that looks like an application frame in user and tool content instead of escaping it (#11813)
- Add
OutputTokenLimitExceeded, and fall back to the next model inModelFallbackwhen a response is cut off atmax_tokens(#12407) - Ask for approvals and answers inside the run with
RequestInput, putAskUseron the deferred pipeline, and mark deferred calls withkindandanswered_by(#12757) - Add
DelegationTasks.discover()and stop one damaged saved task from blockingDelegationTasks.opened()(#10140) - Require workspace backends to leave detached processes running, and check it in
WorkspaceBackendSuite(#13070) - Run
PromptInjectionDefendersemantic classification as durable operations so it works on Temporal (#12424) - Give sub-agent task-control events the
Eventsuffix and past-participle names, withagent_nameandparent_task_idfields, keeping the old names as deprecated aliases (#13074) - Spell out abbreviated identifiers in
pydantic_ai_harness, renamingnum_resultstomax_resultsandmax_duration_secstomax_duration_seconds(#13075) - Rename harness
CapabilityEventfields to*_count,*_name,duration_msandprevious_item, keeping the old names as deprecated aliases (#13068) - Rename harness
CapabilityEventoutliers to<Subject><PastParticiple>Eventand addSTEP_PERSISTENCE_EVENTS(#13065) - Add the
RefineOutputharness capability (#13120)
- Support
SubAgents(dynamic_agents=...)under durable execution (#12418) - Strip every default-ignorable character before
ArtifactScannerphrase matching and flag hidden variation selectors (#11475) - Load one instruction file per directory and nested files by default in
RepoContext, addwalk_up, and haveCoderbuild on them (#11691) - Cap inlined nested instructions at 32,000 characters per conversation by default with
RepoContext(nested_max_chars=...)(#11699) - Send documents of any media type
mimetypesknows, with the format taken from it (#12365) - Move provider-specific native-tool fields to
provider_settings(#7807) - Add
framing_announcementsetting and only announce the<system>voice tag once a conversation needs it (#12661) - Surface nested
RepoContextinstruction files when the model writes or edits in a directory (#11701) - Record
InputGuardrail,OutputGuardrailandToolGuardrailverdicts as durable operations (#12428) - Refuse a
CapabilityCreationrun whendirectoryis below'operator'authority (#12558) - Stop continuing an OpenAI response without a
history_digestthroughopenai_previous_response_id(#12575) - Replay Prefect tasks on flow retry when the message history holds binary content (#12188)
- Reject
CodeModetools named after Python builtins, which the sandbox called instead of the tool (#12698) - Break chat-template special tokens in content on open-model routes, and restore them in model output, with
ModelProfile.may_tokenize_special_tokens_in_content(#12556) - Use the engine’s codec and
serialization_failurefor durable capability results (#11057) - Send
FileSearchTool.max_num_resultsto OpenAI Responses (#12728) - Raise
UserErrorwhen validation requests approval for an external tool, keep single-model tool arguments through durable re-validation, and document concurrent DBOS runs and shared MCPhttp_clients (#12958) - Record a
StepPersistencetool call that ends inModelRetryorToolFailedasfailedinstead of leaving itstarted(#12638) - Raise
UserErrorfromStreamedRunResult.resultwhen arun_stream()run stops while finishing (#13087) - Run
CodeModeremote sandboxes over gRPC with pydantic-monty 1.5.0 (#12673) - Replace
httpxwithhttpx2inpydantic-ai-harness(#13026) - Curate
KnownModelNameand the provider model-name literals to the models a user would pick (#12817)
- Call Anthropic’s
20260209web tools directly on the Anthropic API when citations are requested (#12278) - Apply
FunctionToolset(requires_approval=True)toToolinstances passed to the toolset (#12378) - Re-resolve realtime session instructions before each model turn and deliver their changes as appends (#11930)
- Recognize
SummarizingCompaction(keep_user_messages=True)copies only by the marker on their text (#12316)
- Protect the
gh-awcanonical session capture from agent tools (#10606) - Add multimodal notes to
AskUserAnswer(#11664) - Count
BrowserUsemodel calls toward the host run’s usage andUsageLimits(#11860) - Name the V2 replacement when code imports a name V2 removed, like
OpenAIModelorMCPServerStdio(#12035) - Fall back to the next model in
ModelFallbackwhen a model refuses, and letContentFilterErrorinfallback_onmatch refusals (#12039) - Raise
ModelQuotaExceededErrorinstead ofModelRateLimitErrorfor Z.ai balance and plan-limit 429s (#12042) - Support the
'12h'prompt cache retention on the OpenAI Responses API for GPT-5.6 and later (#12046) - Send Google a server deadline of at least 20 minutes instead of the client’s read timeout, and warn about httpx’s 5 s default (#12057)
- Stop Temporal from retrying model errors that can’t succeed on retry by default, via
non_retryable_model_errors(#12107)
- Raise an error status a retrying transport gave up on as
ModelHTTPError, so fallback moves on (#11934) - Send stored response, item, conversation and container IDs back only to the endpoint that created them, via
Model.accepts_server_state(#11774) - Make
json-repairan optional dependency, needed only byCoderandRepairToolArguments(#11768) - Turn off strict tool schemas for
Coder’s tools by default, withCoder(strict=True)to opt in (#11743) - Surface every nested
RepoContextinstruction file between a traversed path and the working directory, without repeating the root file (#11687) - Add
output_speech_timestampsto report word timing of realtime speech, on Azure AI Voice Live (#11685) - Make the
ModelFallbackcapability constructible from agent specs (#11679) - Add a
first_event_timeoutmodel setting so a stream that never starts can fall back (#11582) - Dispatch
OnlineEvaluationevaluators once per durable run instead of on every replay (#11577) - Show the harness
Planningplan in the plan tools’ results instead of a per-request reminder copy (#11521) - Add agent artifact security scanning for
MemoryandSkillswithArtifactScanner(#11470) - Fix
AnthropicModel.count_tokensrejecting all-deferred tool requests and undercounting server tools on the Anthropic API (#11343) - Accept plain functions as evaluators in
pydantic_evals(#10292) - Remove unresolvable
RealtimeEventfrompydantic_ai.agent.__all__(#10189) - Add
RunContext.load_capabilityto load on-demand capabilities from code (#10090) - Add a
ModelFallbackcapability, a per-attemptprepare_model_requesthook, andRetryModelRequest(#9348)
- Default
CodeModetodynamic_catalog=True, so a revealed tool is appended instead of rewriting the cached prompt (#11358) - Pass the Gemini Live reconnect replay to
GoogleRealtimeConnection’sdialas a keyword-onlyreplayargument (#11515) - Give Harness
LLMRemindera defaultinterval=10instead of generating on every request (#11641) - Replay signed and encrypted history data to providers with the same
canonical_system(#11504) - Let a deferred
CombinedCapabilityload as one capability, with members keeping their global ordering (#10321) - End a GPT-Live reply that delegated at Live’s next pause instead of mid-sentence when the backend answers (#11250)
- Say what the
<system>tag means and escape it in user and tool text on models without mid-conversation system messages (#11506)
- Change thinking effort mid-conversation via OpenAI
configuration_updateand Anthropic per-messageoutput_config, recorded asModelSettingsDeltaPart(#11111) - Add
ModelRequestRejectedError,ModelAuthenticationErrorandModelNotFoundErrormodel error categories (#11081) - State loaded deferred capabilities’ instructions in the system voice, append their changes, and show them to
before_model_request(#11103) - Prefix hosted MCP capabilities’ tool names with the service by default, configurable with
tool_prefix(#10376) - Store the
SummarizingCompactionsummary as aCompactionPartinstead of a system prompt, and send provider-lessCompactionParts to every model (#10573) - Deliver realtime
SystemPromptParts on each provider’s operator channel withsession.send()(#11379) - Preserve run identity when replaying Prefect capability operations (#11196)
- Append changed MCP server instructions with
on_change='append', and give an id-less URLMCPToolsetits hostname asid(#10791) - Record Harness
Memorysnapshots in history once per changed run, so requests stay append-only (#10903) - Tell the realtime model a tool call failed on every provider, so it answers instead of going silent (#11086)
- Reserve DBOS handler step positions during tool
ctx.emit()(#11157) - Record GPT-Live speech as one
SpeechPartinstead of splitting it at each delegated tool call (#11187) - Deliver
ctx.emit()events into the realtime session event stream (#11369) - Make realtime shared settings warn, raise or ignore like standard
ModelSettings: forcedtool_choiceraises on Gemini Live,parallel_tool_calls=Falsewarns (#11066) - Keep the prompt cache when changing thinking effort mid-conversation on OpenRouter, via its
configuration_updatesystem message (#11426) - Start
GraphBuilderbroadcast branches in.to()order instead of reversed, which can break replay of durable workflows paused across the upgrade (#11408) - Cache
on_change='append'instruction blocks behind a second cache point after the static instructions (#11351) - Build Harness
SystemReminderson request-scoped system prompts and deprecatecache_ttl(#9712) - Add
CodeMode(monty_sandbox=...), which takes a remote Monty URL or a function that builds the pool, and deprecatemonty_sandbox_url(#11141)
- Warn when a provider-specific thinking setting from a broader scope overrides
thinking(#10231) - Send the least thinking a model accepts for
thinking=Falseon models that can’t turn thinking off (#11036) - Raise
NotImplementedErrorfor a file in aCohereModeltool return instead of dropping it (#11114) - Keep concurrent workspace runs attached to their own Prefect environments (#11160)
- Keep
boolandintinputs on separateLiteraldecision branches inpydantic_graph(#9091) - Deprecate
google_multi_speakeronGoogleRealtimeModel, which no Gemini Live model supports (#11064) - Accept async
authfunctions in the hosted MCP capabilities (#10835) - Run the authoring checks in
CapabilityStore.load_activeand stop overwriting unreadable manifests (#10731) - Keep the last valid authored capability on a failed re-author, share the
CapabilityStorelock per directory, and let runs cancel authoring (#10767) - Reject
BrowserUseprohibited lists browser-use would match by exact hostname, and retry when redacted schema keys collide (#10775) - Share one
LocalStackcontainer insideasync with agent:, stop service-list bypasses andaws configurewrites to~/.aws, and capaws_clioutput (#10828) - Make
InputGuardrailredact the user’s own prompt and close fail-open paths in guardrails (#10841) - Keep
CodeMode(dynamic_catalog=True)discoveries from rewriting the cached prompt (#10906)
- Raise model error categories like
ModelRateLimitErrorfrom embedding models (#10804) - Add
usage_limits,deadline,run_idandconversation_idtoModelSelectionContext(#10856) - Default
BedrockConverseModel’smaxTokensto Claude’s maximum output, streaming such requests behind the scenes (#10845) - Deprecate
RetryPromptPartin favor ofToolReturnPart(outcome='retried')andRetryFeedbackPart(#8094). Code that finds tool errors withisinstance(part, RetryPromptPart)now finds none, in new runs or loaded histories: see theRetryPromptPartdeprecation entry - Summarize harness-added user-channel content as
<harness_data>instead of user messages inSummarizingCompaction(#10833) - Give
AskUser,ConversationSearch,Macroscope,ManagedPrompt,PlaywrightBrowserandPydanticAIDocsa stable defaultid, and appendManagedPromptversion changes (#10904) - Derive the
MCPcapability’s defaultidfrom the server URL’s hostname only, and reject two servers on one host without explicit ids (#10807) - Record who wrote a memory file with an opt-in
MetadataMemoryStoreandMemory(write_metadata=...)(#10892) - Let a named
InstructionPartpassed to a run’sinstructionsopt intoon_change='append', keyedrun:<name>(#10789) - Keep
SummarizingCompaction(keep_user_messages=True)copies recognized after their request is merged (#10914) - Strip request-level
instructionsfrom untrusted history insanitize_messagesand server-managed UI adapters (#10897) - Send tool returns whose JSON form is a string, like
datetimeandUUID, to the model unquoted so restored histories match the first run (#10488) - Keep the ids of instructions a wrapper toolset passes on from the toolsets it wraps (#10909)
- Include
settingsandprofilein model equality andModelrepr(#9474) - Deprecate
OpenAIDecisionsProviderand letOpenAIDecisionsModeltakeOpenAIProvider(#10951) - Record every mid-run tool population change as a
ToolAvailabilityDeltaPart(#9405) - Send typed text to the GPT-Live backend as a user turn, so
send(text)runs the agent’s tools (#10960) - Keep tool returns shaped like media markers from breaking
StepPersistencesnapshots, and fixSqliteMediaStore,DiskMediaStore,MongoMediaStoreandS3MediaStoreedge cases (#10834) - Send settings stated by either of two merged
Advisorcapabilities (#10726) - Drop client-supplied
TextContent.metadatafrom user prompts insanitize_messages(#10943) - Raise
ModelConnectionErrorandModelTimeoutErrorfor xAI gRPC connection failures and client timeouts (#11080) - Send the agent’s
system_promptand seeded history’s system prompts to realtime sessions (#11055) - Deliver
SubAgentsbackground task output as framed<task_output>data instead of in aSystemPromptPart(#10550) - Keep
BrowserUsesecrets on allowlisted sites and out of tool results, and fix allowlist andfile://gaps (#10771) - Match
FileSystemdenied and read-only patterns case-insensitively, protect.gitfiles, and bound reads and Python regex searches (#10825) - Filter
GitHubtools onreadOnlyHintunderread_only=True, reject'oauth', and deprecate plainhttp://URLs (#10815) - Add
'max'to unifiedthinkingeffort levels (#10920)
- Remove shut-down Groq models
playai-tts,playai-tts-arabic,meta-llama/llama-guard-4-12bandmeta-llama/llama-4-maverick-17b-128e-instruct(#10306) - Distinguish omitted provider usage from reported zero and add
UsageLimitUnavailableWarning(#9491) - Add
on_change='append'to preserve dynamic instruction prefixes (#8188) - Stop recording that a realtime session ended when a tool raised, and document that it goes on (#10782)
- Record what the user heard of ElevenLabs Agents replies they barged in on, adding the
OutputItemCutlifecycle event (#10739) - Append the next hour to
LogfireMCPhistory instead of rewriting its instructions, keeping the prompt cache (#10543) - Settle a realtime reply only with the response that answers it, adding
AnswersRevised(#10668) - Add provider-neutral model error categories like
ModelRateLimitError,ModelUnavailableError,ModelServerErrorandModelContextWindowExceededError, andModelHTTPError.for_category(#9354) - Frame
BackgroundToolsresults as<tool_result>tool output instead of untagged user text (#10548) - Send
TrajectoryJudgesteering as a frameworkSystemPromptPartnote plus the judge message as escaped<judge_feedback>data, both marked withmetadata(#10545) - Check
tool_calls_limitbefore eachCodeModenested tool call (#10362) - Let
GitHubCopilotProvidersend a configurablecopilot-integration-idviaintegration_idorGITHUB_COPILOT_INTEGRATION_ID(#10784)
- Count a resumed
'suspended'response’s usage only in the run that produced it, inRunUsage,UsageLimitsandSpendLimits(#10078) - Make
RealtimeConnectionyield lifecycle events through a publicpydantic_ai.realtime.lifecyclemodule (#10353) - Let
read_filereturn images and PDFs, and describe other binary files (#9596) - Record a realtime reply the user cut off after it finished generating as interrupted, and mark interrupted speech when seeding (#10466)
- Treat a native tool as unsupported when the model can’t apply its
allowed_domains,blocked_domains,max_usesorexternal_web_accesssetting (#10451) - Add request-scoped
SystemPromptPart(scope='request')sent natively as Anthropicclear_atsystem messages (#9711) - Send Harness
WarnNearLimitswarnings as request-scoped system prompts (#10561) - Escape
RepoContext<context-file>blocks and send the nested-directory pointer as aSystemPromptPart(#10558) - Make the profile’s
supports_auto_cachedecideanthropic_cache, and use automatic caching on legacyAsyncAnthropicBedrockfor Claude Opus 4.7 and later (#10551) - Let any module define a
ToolKindwith typed tool parts, and keep unknown kinds loadable (#9710) - Emit
Planningstatus-tool events after their store reads, so DBOS recovery with anevent_stream_handlerreplays in order. Existing DBOS workflows usingPlanningwith anevent_stream_handlermay not recover after upgrading; let in-flight workflows finish first or deploy a new DBOS application version (#10343) - Align
RealtimeTurnCompleteEventwith the exchange boundary thatwait_for_reply()waits for. To react when a particular response ends, use itsPartEndEvents. Caption UIs should keep user parts open until theirPartEndEvent, which can arrive after the reply completes (#10517)
- Attach namespaced
originandtool_call_idmetadata toBackgroundToolscompletions (#10196) - Take GPT-Live realtime history, usage, and reply waits from the session core (#10083)
- Honour
disable-model-invocationanduser-invocableinSkills, and skip stray skill library paths (#10378) - Take Gemini Live realtime history, usage, and reply waits from the session core (#10082)
- Run
BrowserUseon the host model by default and make browser-use telemetry opt-in (#9506)
- Require Python 3.11 or newer in every package; Python 3.10 installs resolve to 2.54.0 and earlier (#9526)
- Record the tool requests of
ExaSearch,YouSearch,LocalStackand other harness capabilities under durable execution (#9705) - Bound retained realtime audio like retained images with
retain_audio_max_seconds(#9702) - Prefix
LogfireMCPtool names withlogfire_(#9868) - Serialize
FileUrl.media_typeasnullfor extensionless URLs instead of raising (#8405) - Take realtime history, usage, and reply waits from the session core on OpenAI, Azure OpenAI, and xAI (#9612)
- Keep default
run_idandconversation_idstable when a durable run is re-executed (#9701) - Record each failed
FallbackModelattempt with its model, timing, error and usage, and count rejected responses inRunUsage(#8745)
- Handle draft-7 list-form
itemsinJsonSchemaTransformer,TestModeland Mistral streamed output, and makeTestModelaccept boolean subschemas and capprefixItemsatmaxItems(#9560) - Fix
ImageGenerationunderFallbackModelanddataclasses.replace, and compareEmbedderby identity (#9477) - Refuse a second durable execution engine on an agent before either binds (#9391)
- Make
wrap_*hooks enclose complete stage lifecycles (#7053) - Re-raise model errors from Temporal model activities with their original type in workflow code (#9580)
- End the run when a
BackgroundToolstool raises an unexpected exception, as a sequential tool does (#9434) - Drop the
SubAgentsagent_foldersdefault-change warning: since v2.52.0 (#9023) theagentsfolder is not loaded by default, so passagent_folders='agents'to keep loading it (#9424)
- Add
oneOfschema support toTestModel’s generated data (#8783) - Deprecate
pydantic_ai_harness.step_persistence.naming(#9499)
- Run harness capabilities in any workspace:
Coder,FileSystem,Shelland the rest work throughctx.workspace, locally or in a sandbox (#8866) - Replace
ModalSandbox’s own tools with a Modal workspace, soCoder,ShellandFileSystemrun in the sandbox;ModalSandboxBackendreplacesModalSandboxSession(#8867) - Raise
AnthropicModel’s defaultmax_tokensfrom 4096 to 16384 on Claude Sonnet 4.5 and later (#9025) - Keep the prompt as a
DecisionModel’s judgedtextafter a retry (#8967) - Stop
SubAgentsloading agent files by default, and deprecateinherit_tools(#9023) - Default
AnthropicModel’smax_tokensto the model’s maximum output, streaming such requests behind the scenes (#9298)
- Match dated
gemini-3.8-liveids, rejectgoogle_affective_dialogon Gemini 3.1 Flash Live and 3.8 Live at connect, and raiseRealtimeErrorfor Gemini Live close codes (#8761) - Raise a
UserErrorfor a realtimetool_choicethat forces a tool call on OpenAI, Azure OpenAI, and xAI (#8755)
- Ask a
DecisionModelwhich route to take by name, with one label per route (#8733) - Make
ModelSelectionContext.messagesend with the request being routed, and addModelSelectionContext.prompt(#8737) - Replace the decision model’s tool-call lean with an opt-in
decision_route_threshold(#8739)
- Name a
Noneoutput routeNonerather thanNoneType(#8590) - Raise when
UserPromptPart.contentis not astror a sequence, instead of silently sending adict’s keys (#8595)
- Make
RunContext.enqueue()safe from worker threads (#7758) - Require a JSON
Content-Typeon UI adapter requests (#8396) - Dispatch a capability
@durable_operationcalled from a per-request hook, instead of silently running it inline (#8395)
- Reject invalid
DeferredToolResults.approvalsvalues (#8081)
- Add
--mcp-configsupport and tool-call streaming toclai(#1374)
- Deprecate
RunContext.capability_loadedandavailable_capability_idsin favor ofcapability_activeandactive_capability_ids(#7454) - Make inclusive integer
maximumreachable inTestModel(#7697)
- Use
httpx2for Anthropic clients, requiringanthropic>=1.0.0. Anhttp_clientyou pass toAnthropicProvidermust now be anhttpx2.AsyncClient(#7657)
Here’s a filtered list of the breaking changes for each version to help you upgrade Pydantic AI.
- See #11111 - A model request whose
thinkingeffort level differs from the one in effect, like a run’s first request withthinking='low', emits aModelSettingsDeltaEvent, which a durabilityevent_stream_handler=receives in an event-handler activity or step of its own. This can break replay of durable workflows paused across the upgrade: see Temporal and DBOS for who is affected and how to upgrade.
Nothing was removed, but code that reads message history behaves differently, and some durable workflows record a different sequence of activities or steps:
- See #8094 - Pydantic AI no longer records a
RetryPromptPart. A tool retry is that call’sToolReturnPartwithoutcome='retried', and a retry that answers no tool call is aRetryFeedbackPart. A stored'retry-prompt'part loads as one of those too, soisinstance(part, RetryPromptPart)matches nothing, and code that counts tool errors that way reports none without an error or warning. Replace that check withis_retry(part), which matches both new parts, or on a release that predates it, withisinstance(part, RetryFeedbackPart) or (isinstance(part, ToolReturnPart) and part.outcome == 'retried'); Finding tool errors in history shows it in use, and how to also find tool calls that failed. The retry text sent to the model changed too, and changed again in v2.68.0: see “What the model now sees” in the deprecation entry, which lists the other changes. - See #9405 - A tool that joins the agent’s tools mid-run emits a
ToolAvailabilityDeltaEvent, which a durabilityevent_stream_handler=receives in an event-handler activity or step of its own. This can break replay of durable workflows paused across the upgrade: see Temporal and DBOS for who is affected and how to upgrade.
The stable V2.0 release. There are no new breaking or behavior changes since the betas; the full breaking-change list and recommended upgrade path are in the v2.0.0b1 entry below. Install it with:
uv add pydantic-ai
The seventh V2 beta, forked from v1.107.0. There are no new V2 breaking or behavior changes since v2.0.0b6 below — everything in that entry applies unchanged — but this beta picks up the latest V1 release on top, which adds Claude Fable 5 / Mythos 5 model support and OpenRouter prompt caching (CachePoint), plus known_model_names() and Anthropic fixes; see the v1.107.0 release notes for the full list.
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b7"
uv add "pydantic-ai==2.0.0b7"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.107.0.
The sixth V2 beta, forked from v1.106.0. There are no new V2 breaking or behavior changes since v2.0.0b5 below — everything in that entry applies unchanged — but this beta picks up the latest V1 release on top, which adds api_host/timeout configuration and base seed mapping for the xAI provider, plus streaming and data-URI handling fixes; see the v1.106.0 release notes for the full list.
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b6"
uv add "pydantic-ai==2.0.0b6"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.106.0.
The fifth V2 beta, forked from v1.105.0. There are no new V2 breaking or behavior changes since v2.0.0b4 below — everything in that entry (including the prepare-callbacks change) still applies — but this beta picks up the latest V1 release on top, which adds on-demand (deferred-loading) capabilities and Grok 4.3 reasoning_effort support, plus GoogleModelSettings.google_cached_content and Temporal gateway/ fixes; see the v1.105.0 release notes for the full list.
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b5"
uv add "pydantic-ai==2.0.0b5"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.105.0.
The fourth V2 beta, forked from v1.104.0. One new V2 behavior change since v2.0.0b3:
- Prepare callbacks (
prepare_tools=/PrepareToolscapability) that returnNonenow raiseTypeErrorinstead of silently stripping all tools. V1.103.0 announces this change viaPydanticAIDeprecationWarning(see #5188); V2 turns the warning into a hard error (see #5668). Return an empty list ([]) when you mean “no tools for this turn.”
This beta also picks up two V1 releases on top — v1.103.0 and v1.104.0 — together adding Claude Opus 4.8 support, McpServer.list_prompts / get_prompt, message-timestamp roundtripping through VercelAIAdapter’s UIMessage.metadata, OpenRouter eager input streaming, and several Bedrock and UI fixes. See those release notes for the full list.
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b4"
uv add "pydantic-ai==2.0.0b4"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.104.0.
The third V2 beta, forked from v1.102.0. There are no new V2 breaking changes since v2.0.0b1 below — everything in that entry applies unchanged — but this beta picks up the latest V1 release on top, which is a bug-fix release; see the v1.102.0 release notes for the full list.
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b3"
uv add "pydantic-ai==2.0.0b3"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.102.0.
The second V2 beta, forked from v1.101.0. There are no new V2 breaking changes since v2.0.0b1 below — everything in that entry applies unchanged — but this beta picks up the latest V1 release on top, which adds the pending message queue (ctx.enqueue / agent_run.enqueue).
Install it the same way, pinning the exact pre-release version:
pip install "pydantic-ai==2.0.0b2"
uv add "pydantic-ai==2.0.0b2"
For the full breaking-change list and the recommended upgrade path, see the v2.0.0b1 entry below; the only difference is that the latest V1 to upgrade through first is now v1.101.0.
The first V2 beta, forked from v1.100.0, which deprecates most of what V2 removes. V2 leans into a harness-first design with capabilities as a core primitive: a single, composable unit that bundles an agent’s tools, hooks, instructions, and model settings, reaching every layer of the agent through one concept. Many of V2’s changes move configuration that used to be spread across Agent arguments onto that primitive, alongside the behavior changes that V1’s stability guarantee didn’t allow. Pydantic AI stays a small core: some capabilities ship with it, more come from the first-party Pydantic AI Harness, and others are third-party or your own.
The breaking changes below are split into two groups:
- Changes not covered by deprecation warnings — removals and behavior changes that couldn’t be announced via a V1 deprecation warning. Review these even if you’re already on the latest V1 with no warnings.
- Changes covered by deprecation warnings — if you upgraded to the latest V1 and resolved every deprecation warning, you’ve already made these. They’re listed with full before → after for reference.
Recommended upgrade path. To make the jump as smooth as possible:
- Upgrade to the latest V1 release. Most of what V2 removes is deprecated as of v1.100.0 (the release this beta is forked from), so any V1 at or above that version surfaces those warnings.
- Resolve every deprecation warning. The changes covered by deprecation warnings were announced in V1 via warnings that name the new API and, where possible, include a migration snippet. Run your test suite (or app) with warnings visible and address each one — by hand or by pointing a coding agent at them — to migrate across the bulk of V2 ahead of time.
- Upgrade to V2 and make the changes not covered by deprecation warnings — primarily default-behavior changes and a handful of removals with no V1 deprecation.
You can also upgrade straight to V2 and work through the list below directly — it’s organized so a coding agent can apply the code changes mechanically. Resolving deprecation warnings on the latest V1 first is still the smoother path, since it spreads the work out and leaves you only the behavior changes to reason about consciously at the end.
Message history serialized with V1 (via ModelMessagesTypeAdapter) continues to deserialize in V2.
These removals and behavior changes could not be announced via a V1 deprecation warning, so review them even if you’ve resolved every deprecation warning on the latest V1.
Code changes:
- Generic type parameter defaults changed from
Nonetoobject: an un-parameterizedAgent(...)now infersAgent[object, str]instead ofAgent[None, str], and thepydantic_graphStateT/RunEndT/DepsTdefaults changed to match. Update explicitAgent[None, ...],RunContext[None], andTool[None]annotations that don’t actually requireNonedependencies to useobject. This is a type-checking-only change; runtime behavior is unchanged. See #5307. - The
pydantic_graph.persistencepackage and thepydantic_graph.mermaidmodule are removed, with no V2 equivalent for standalone Mermaid generation (render diagrams withGraph.render()). The builder API deliberately does not snapshot graph state, so there is nopydantic_graphreplacement for the persistence package; to save, resume, and fork agent run state, Pydantic AI Harness ships theStepPersistencecapability. The move of theGraphBuilderAPI out ofpydantic_graph.betato the top-levelpydantic_graphwas deprecation-announced; see below. See #5470. ModelProfileand its subclasses are nowTypedDicts instead of dataclasses. Passingprofile=OpenAIModelProfile(field=value)into a model still works unchanged; the migration only matters if you read or mutate profile fields, or call.update()/.from_profile(). SeeModelProfileis now aTypedDictbelow. (#5481)
Default behavior changes — same API, different runtime behavior (roughly ordered by how many users they affect):
- A bare
uv add pydantic-ai/pip install pydantic-ainow installs a slimmer set of extras (frontier providers plus minimal integrations); providers likebedrock,groq, andmistralare no longer included by default, so you’ll need to add the extras you use. See Slimmer default extras below. (#5467) - The default
end_strategychanged from'early'to'graceful': when a model calls function tools in the same response as a successful output tool, those function tools now run (and their side effects happen) instead of being skipped, and tool calls run in the order the model emitted them. See Parallel tool-call execution order below. (#5339) - The default instrumentation format is now version 5, and agent run spans report token usage under
gen_ai.aggregated_usage.*. See Instrumentation defaults below. (#5523) capture_run_messages()now also captures the partialModelRequest/ModelResponsefrom an interrupted run, marked withstate='interrupted'(a newModelRequest.statefield is added). Code that asserts on exact captured-message counts on error paths may need updating. See #5364.- Output tool calls and returns now emit dedicated
OutputToolCallEvent/OutputToolResultEventinstead ofFunctionToolCallEvent/FunctionToolResultEvent. Separately, native tool calls and returns no longer emit dedicated events at all — theBuiltinToolCallEvent/BuiltinToolResultEventclasses are removed and they surface only via the standardPartStartEvent/PartDeltaEvent. See #5332 and #5476.
ModelProfile is now a TypedDict
See the Model Profile guide for an overview of what a model profile is and how to configure one.
ModelProfile and all its subclasses (OpenAIModelProfile, AnthropicModelProfile, GoogleModelProfile, BedrockModelProfile, etc.) are now TypedDict(total=False) instead of @dataclass. This unifies the mental model with ModelSettings (also a TypedDict) and enables direct dict-spread for cross-class merging.
ModelProfile.update() and ModelProfile.from_profile() are removed; use the module-level merge_profile (later argument wins per key).
Migration recipes:
| v1 (dataclass) | v2 (TypedDict) |
|---|---|
OpenAIModelProfile(field=value) | Same syntax; returns a partial dict instead of a fully-defaulted instance. |
profile.field (attribute read) | profile.get('field', <default>) — non-trivial defaults are exported from pydantic_ai.profiles (e.g. DEFAULT_THINKING_TAGS, DEFAULT_PROMPTED_OUTPUT_TEMPLATE); the fully-merged base is DEFAULT_PROFILE. |
profile.field = value (attribute write) | profile['field'] = value |
dataclasses.replace(profile, field=value) | {**profile, 'field': value} or merge_profile(profile, ModelProfile(field=value)) |
profile.update(other) | merge_profile(profile, other) |
OpenAIModelProfile.from_profile(p) | Just p — no upcasting needed |
Model(name, profile=full_profile) (full replace) | Now merges on top of the provider’s default profile — usually what you want. For a hard replace use Model(name, profile=lambda _default: full_profile). |
Model(name, profile=fn) where fn: Callable[[str], ModelProfile | None] | Removed — the user-passed callable is now Callable[[ModelProfile], ModelProfile], receiving the resolved default and returning the final profile. The (model_name: str) -> ModelProfile | None shape is still accepted internally by Provider.model_profile. |
isinstance(profile, OpenAIModelProfile) | Not supported by TypedDict at runtime — raises TypeError. Use isinstance(profile, dict) or check key presence ('openai_chat_supports_web_search' in profile). Pyright still narrows correctly via the TypedDict subclass annotation. |
Model.profile is now the single source of truth for the resolved profile. It is composed by merge_profile in this order (later wins):
DEFAULT_PROFILE— base defaults for every documented key.Provider.model_profile(model_name)— provider/model-specific resolution.- The user’s
profile=argument — either a partial dict (merged on top) or aCallable[[ModelProfile], ModelProfile](full control: receives the resolved default, returns the final profile).
In v1, ModelProfile.update() silently filtered out fields not declared on the target class. In v2, dict-spread preserves every key.
This means e.g. a Bedrock-hosted Anthropic model’s resolved profile now carries the upstream anthropic_* fields alongside the bedrock_* fields, where v1 dropped them. No in-tree model class reads cross-class fields, so behavior is unchanged in the standard providers; but custom model classes that do profile.get('anthropic_supports_adaptive_thinking', False) on a non-Anthropic route will now see the value the upstream Anthropic profile set, where v1 always returned the default.
See the Model Profile guide for how to configure a profile, and PR #5481 for the full ModelProfile redesign.
The default end_strategy changed from 'early' to 'graceful'. This only affects responses where a model calls function tools in the same response as an output tool (the call that ends the run). When that output tool succeeds, the function tools requested alongside it now run by default instead of being skipped, so their side effects happen and their results reach the model if the run continues; and a function tool’s ModelRetry now suppresses the output result so the model can correct itself on the next round. The case where every output tool fails is unchanged: function tools run and the run continues either way. Most agents don’t need any change. If you relied on the run ending the instant an output tool succeeds — skipping any function tools requested in the same response — set end_strategy='early' explicitly.
The sequential=True flag on a tool is now a per-tool barrier rather than a batch-wide serial switch: a sequential tool runs alone, but other tools in the same response still run in parallel around it. The barrier now also applies to output tools via ToolOutput(sequential=True), not just function tools. To run all of a run’s tools serially, wrap the run in agent.parallel_tool_call_execution_mode('sequential') or set parallel_tool_calls=False on the model settings.
See Parallel Output Tool Calls for the full behavior of all three strategies, and #5339.
A bare uv add pydantic-ai / pip install pydantic-ai now installs pydantic-ai-slim[openai,anthropic,google,cli,mcp,evals,web,retries,logfire] — frontier providers plus minimal integrations. Providers and integrations that were previously bundled are no longer installed by default; add the ones you use explicitly, e.g. uv add 'pydantic-ai[bedrock,groq]': bedrock, groq, mistral, cohere, xai, huggingface, temporal, ag-ui, ui, and spec. See the installation guide for the full list of extras.
Some pydantic-ai-slim extras were also removed outright (not just dropped from the default bundle): the outlines-* extras (the Outlines integration is removed), vertexai (Vertex AI is now served by the google extra), fastmcp (the FastMCP back-compat shim is removed), and a2a (A2A now lives in the upstream fasta2a package). See #5467.
The default instrumentation format is now version 5 (versions 2–4 still work but emit a deprecation warning; version 1 and its event_mode=/logger_provider= arguments are removed). In version 5, deferred tool calls (CallDeferred/ApprovalRequired) are no longer recorded as span errors.
Separately, InstrumentationSettings’s use_aggregated_usage_attribute_names now defaults to True: agent run spans report token usage under gen_ai.aggregated_usage.* while model request spans keep gen_ai.usage.*, which avoids double-counting in backends that sum parent and child usage. Dashboards and alerts that read token usage from run spans must be updated, or set use_aggregated_usage_attribute_names=False to keep the V1 attribute names.
See #5523.
These changes were announced in the latest V1 releases via deprecation warnings that name the replacement API. If you upgraded to the latest V1 and resolved every warning, you’ve already made them. The V1 → V2 migration map carries the full before → after for every symbol; this section records the behavior that changes with them and the PRs each one landed in.
Behavior changes that flip silently if the V1 deprecation warning was not addressed — even though these were announced, an unaddressed warning means the behavior changes without raising an error, so confirm you’ve handled them:
- The bare
openai:model prefix now uses the OpenAI Responses API (OpenAIResponsesModel) instead of the Chat Completions API (OpenAIChatModel). Useopenai-chat:to keep Chat Completions, oropenai-responses:to opt into the new default explicitly. Announced via #5334; flipped in #5469. - Provider-adaptive
WebSearchandWebFetchcapabilities are now native-only and raise on models that don’t support them, andMCP(url=...)runs the server locally by default. Restore the V1 fallbacks withWebSearch(local='duckduckgo'),WebFetch(local=True), andMCP(url=..., native=True). Announced via #5331; changed in #5333.
API removals and renames — look each old name up in the migration map; the PRs that announced and landed each group are:
| Group | PRs |
|---|---|
Providers: Grok → xAI (grok: prefix → xai:) | #5460 |
Providers: Google GLA/Vertex → GoogleProvider/GoogleCloudProvider, GeminiModel → GoogleModel | #5336, #5543, #5479 |
Models: OpenAIModel → OpenAIChatModel, system_prompt_role and sampling-settings move into the profile | #5468 |
Models: StreamedResponse.usage() becomes a property (affects custom Model subclasses) | #5546 |
Models: bare provider-prefix-less names (Agent('gpt-5')) now raise UserError | #5464 |
Native tools: builtin_tools → native_tools throughout | #5338, #5396 |
Native tools: UrlContextTool → WebFetchTool | #5458 |
MCP: per-transport server classes → MCPToolset | #5325, #5337 |
Agent config → capabilities: instrument= | #5434 |
Agent config → capabilities: event_stream_handler=, prepare_tools= | #5335, #5475 |
Agent config → capabilities: history_processors= | #5425 |
Agent config: mcp_servers= → toolsets=, sequential_tool_calls() → parallel_tool_call_execution_mode() | #5466 |
Tools: DeferredToolCalls → DeferredToolRequests, DeferredToolset → ExternalToolset | #5459 |
Tools: FunctionToolset.tool() now requires a RunContext first parameter | #5462 |
Tools: pydantic_ai.ext.aci removed (wrap with Tool.from_schema) | #5510, #5467 |
Usage and response-field renames (request_tokens → input_tokens, vendor_details → provider_details, …) | #5476 |
Events: dedicated OutputToolCallEvent/OutputToolResultEvent, FunctionToolResultEvent.result → .part | #5332 |
Streaming: StreamedRunResult accessor renames, stream_responses() → stream_response() | #5296, #5463 |
Streaming: Agent.run_stream_events() is an async context manager only | #5440 |
Results: result.usage()/result.timestamp()/stream.get() become properties | #5263 |
Integrations: Agent.to_a2a() and the bundled fasta2a move upstream | #5426, #5502 |
Integrations: Agent.to_ag_ui()/AGUIApp → AGUIAdapter, cached_async_http_client → create_async_http_client() | #5345, #5464 |
Graph: pydantic_graph.beta imports move to top-level pydantic_graph | #5306, #5470 |
Instrumentation: version=1 and its event_mode=/logger_provider= arguments removed | #5523 |
Pydantic Evals: keyword-only arguments, required Dataset(name=...), Evaluator.name → get_serialization_name() | #5547, #5548 |
Pydantic Evals: evaluation_name/evaluator_version class attributes → get_default_evaluation_name()/get_evaluator_version() | #5554, #5556 |
Four of these carry a caveat the name mapping alone doesn’t convey:
- MCP:
Agent.set_mcp_sampling_model()is not removed — it still sets the sampling model on every registeredMCPToolset, whileMCPToolset(sampling_model=...)sets it on one toolset at construction. - Instrumentation:
version=2/3/4still work but now emit a deprecation warning, and the default isversion=5— see Instrumentation defaults above for the behavior changes that ship with it. Agent(instrument=...): only the constructor arguments are removed. TheAgent.instrumentproperty,Agent.instrument_all(), andInstrumentedModelare unchanged.- Outlines: the integration is removed outright. If you’d like to keep using Outlines with Pydantic AI, please file an issue at dottxt-ai/outlines. See #5444.
The following breaking change was accidentally left out of v1.0.0:
- See #2808 - Remove
Pythonevaluator frompydantic_evalsfor security reasons
- See #2725 - Drop support for Python 3.9
- See #2738 - Make many dataclasses require keyword arguments
- See #2715 - Remove
casesandaveragesattributes frompydantic_evalsspans - See #2798 - Change
ModelRequest.partsandModelResponse.partstypes fromlisttoSequence - See #2726 - Default
InstrumentationSettingsversion to 2 - See #2717 - Remove errors when passing
AsyncRetryingorRetryingobject toAsyncTenacityTransportorTenacityTransportinstead ofRetryConfig
Before V1, minor versions were used to introduce breaking changes:
v0.8.0 (2025-08-26)
See #2689 - AgentStreamEvent was expanded to be a union of ModelResponseStreamEvent and HandleResponseEvent, simplifying the event_stream_handler function signature. Existing code accepting AgentStreamEvent | HandleResponseEvent will continue to work.
v0.7.6 (2025-08-26)
The following breaking change was inadvertently released in a patch version rather than a minor version:
See #2670 - TenacityTransport and AsyncTenacityTransport now require the use of pydantic_ai.retries.RetryConfig (which is just a TypedDict containing the kwargs to tenacity.retry) instead of tenacity.Retrying or tenacity.AsyncRetrying.
v0.7.0 (2025-08-12)
See #2458 - pydantic_ai.models.StreamedResponse now yields a FinalResultEvent along with the existing PartStartEvent and PartDeltaEvent. If you’re using pydantic_ai.direct.model_request_stream or pydantic_ai.direct.model_request_stream_sync, you may need to update your code to account for this.
See #2458 - pydantic_ai.models.Model.request_stream now receives a run_context argument. If you’ve implemented a custom Model subclass, you will need to account for this.
See #2458 - pydantic_ai.models.StreamedResponse now requires a model_request_parameters field and constructor argument. If you’ve implemented a custom Model subclass and implemented request_stream, you will need to account for this.
v0.6.0 (2025-08-06)
This release was meant to clean some old deprecated code, so we can get a step closer to V1.
See #2440 - The next method was removed from the Graph class. Use async with graph.iter(...) as run: run.next() instead.
See #2441 - The result_type, result_tool_name and result_tool_description arguments were removed from the Agent class. Use output_type instead.
See #2441 - The result_retries argument was also removed from the Agent class. Use output_retries instead.
See #2443 - The data property was removed from the FinalResult class. Use output instead.
See #2445 - The get_data and validate_structured_result methods were removed from the
StreamedRunResult class. Use get_output and validate_response_output instead.
See #2446 - The format_as_xml function was moved to the pydantic_ai.format_as_xml module.
Import it via from pydantic_ai import format_as_xml instead.
See #2451 - Removed deprecated Agent.result_validator method, Agent.last_run_messages property, AgentRunResult.data property, and result_tool_return_content parameters from result classes.
v0.5.0 (2025-08-04)
See #2388 - The source field of an EvaluationResult is now of type EvaluatorSpec rather than the actual source Evaluator instance, to help with serialization/deserialization.
See #2163 - The EvaluationReport.print and EvaluationReport.console_table methods now require most arguments be passed by keyword.
v0.4.0 (2025-07-08)
See #1799 - Pydantic Evals EvaluationReport and ReportCase are now generic dataclasses instead of Pydantic models. If you were serializing them using model_dump(), you will now need to use the EvaluationReportAdapter and ReportCaseAdapter type adapters instead.
See #1507 - The ToolDefinition description argument is now optional and the order of positional arguments has changed from name, description, parameters_json_schema, ... to name, parameters_json_schema, description, ... to account for this.
v0.3.0 (2025-06-18)
See #1142 — Adds support for thinking parts.
We now convert the thinking blocks ("<think>..."</think>") in provider specific text parts to
Pydantic AI ThinkingParts. Also, as part of this release, we made the choice to not send back the
ThinkingParts to the provider - the idea is to save costs on behalf of the user. In the future, we
intend to add a setting to customize this behavior.
v0.2.0 (2025-05-12)
See #1647 — usage makes sense as part of ModelResponse, and could be really useful in “messages” (really a sequence of requests and response). In this PR:
- Adds
usagetoModelResponse(field has a default factory ofUsage()so it’ll work to load data that doesn’t have usage) - changes the return type of
Model.requestto justModelResponseinstead oftuple[ModelResponse, Usage]
v0.1.0 (2025-04-15)
See #1248 — the attribute/parameter name result was renamed to output in many places. Hopefully all changes keep a deprecated attribute or parameter with the old name, so you should get many deprecation warnings.
See #1484 — format_as_xml was moved and made available to import from the package root, e.g. from pydantic_ai import format_as_xml.
For the full changelog, see GitHub Releases.