PydanticAI
v2.36.0 open-sourceHow Python does AI: agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.
async def mic_chunks():
async for chunk in microphone_stream():
yield chunk
async with agent.realtime('openai:gpt-realtime-2.1').session() as session:
await session.send_audio(mic_chunks())
agent.to_web(allowed_hosts=['mydevbox.internal'])
from pydantic_ai import Agent
agent = Agent(model='openrouter:web_search')
result = agent.run_sync('What are the latest CVEs in OpenSSL?')
print(result.data)
agent.to_web(allowed_hosts=['myagent.internal.example.com'])
clai --model openrouter:web_search 'What are the latest CVEs in OpenSSL?'
import asyncio
from pydantic_ai import Agent
agent = Agent(instructions='You are a helpful voice assistant.')
@agent.tool_plain
def order_status(order_id: str) -> str:
"""Look up the status of an order."""
return f'Order {order_id}: shipped, arriving Thursday.'
async with agent.realtime('openai:gpt-realtime-2.1').session() as session:
async for part in session.stream_transcripts():
print(f'{part.speaker}: {part.transcript}')
async with agent.run_stream_events(user_prompt) as events:
async for event in events:
if should_stop(event):
events.cancel()
break
from pydantic_ai.models.openai import OpenAIResponsesModel
from pydantic_ai.providers.deepseek import DeepSeekProvider
model = OpenAIResponsesModel('deepseek-chat', provider=DeepSeekProvider())
agent = Agent(model=model)
import asyncio
from pydantic_ai import Agent
agent = Agent('openai:gpt-4o')
async def main():
async with agent.run_stream('Summarize the entire history of computing') as run:
asyncio.get_event_loop().call_later(5, run.cancel)
async for chunk in run.stream_text():
print(chunk, end='', flush=True)
asyncio.run(main())
from pydantic_ai import Agent, RunContext
agent = Agent('openai:gpt-4o')
@agent.tool
def safety_check(ctx: RunContext[None], text: str) -> str:
if 'forbidden' in text:
ctx.cancel()
return 'Aborted.'
return 'OK'
result = agent.run_sync('Please say something forbidden')
print(result.output)
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits
agent = Agent('openai:gpt-4o')
result = await agent.run(
'Summarize this document...',
usage_limits=UsageLimits(request_limit=10, cost_limit=0.05),
)
print(result.usage().cost)
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent('bedrock:anthropic.claude-3-5-sonnet-20241022-v2:0')
result = await agent.run(
'Explain zero-trust networking.',
model_settings=ModelSettings(extra_headers={'x-amzn-bedrock-workload-name': 'sec-review'}),
)
print(result.output)
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits
agent = Agent('openai:gpt-5.6-sol')
result = agent.run_sync(
'Summarize the latest earnings report.',
usage_limits=UsageLimits(cost_limit=0.05),
)
print(result.usage().cost)
from pydantic_ai.mcp import MCPToolset
toolset = MCPToolset(
server_url='http://localhost:3000',
prefer_tasks=False # skip optional MCP tasks rather than blocking
)
from pydantic_ai import Agent, RunContext
agent = Agent('openai:gpt-4o')
@agent.tool
async def summarize(ctx: RunContext[None], text: str) -> str:
if ctx.is_tool_available('fetch_document'):
return f'(fetch available) Summary of: {text}'
return f'Summary of: {text}'
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits
agent = Agent('openai:gpt-4o')
result = agent.run_sync(
'Summarize this document.',
usage_limits=UsageLimits(per_request_input_tokens_limit=4000),
)
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits
agent = Agent('openai:gpt-5.6-sol')
result = agent.run_sync(
'Summarize this document.',
usage_limits=UsageLimits(per_request_input_tokens_limit=4000),
)
from pydantic_ai import Agent
agent = Agent('anthropic:claude-opus-5')
result = agent.run_sync('Summarize the OWASP Top 10 for 2025.')
print(result.output)
from pydantic_ai import Agent
agent = Agent('anthropic:claude-opus-5')
result = agent.run_sync('Summarize the latest threat intelligence report.')
print(result.output)
import asyncio
from pydantic_ai.exceptions import ModelHTTPError
try:
result = await agent.run('summarize this')
except ModelHTTPError as e:
wait = e.retry_after # seconds until the provider allows retry
if wait:
await asyncio.sleep(wait)
# inspect raw response headers if needed
print(e.headers)
from pydantic_ai.providers.bedrock_mantle import BedrockMantleProvider
provider = BedrockMantleProvider()
from pydantic_ai import ToolFailed
@agent.tool
async def lookup_user(ctx, user_id: str) -> str:
if not user_id.startswith('u_'):
raise ToolFailed('user_id must start with u_; got: ' + user_id)
return fetch_user(user_id)
result = await agent.run(
'Summarize the threat landscape',
model_settings={
'mistral_prompt_cache_key': 'threat-landscape-v1',
'parallel_tool_calls': True,
},
)
result = await agent.run(
'Analyze this incident report',
run_id='incident-2025-07-14-001',
)
from pydantic_ai import Agent
from pydantic_ai.exceptions import ToolFailed
agent = Agent('openai:gpt-4o')
@agent.tool_plain
def fetch_record(record_id: str) -> str:
if record_id == 'missing':
raise ToolFailed('Record not found; try a different ID.')
return f'Record {record_id}: active'
result = await agent.run('Summarise this document', run_id='run-2025-07-abc123')
result = await agent.run('Fetch and summarize the report', tool_retry_budget=2)
result = await agent.run('Draft a message', model_settings={'openai_moderation': True})
print(result.all_messages()[-1].provider_details)
from pydantic_ai.settings import InstrumentationSettings
settings = InstrumentationSettings(include_model_request_parameters=False)
async with agent.run_stream(prompt) as stream:
async for event in stream.stream_events():
if isinstance(event, DeferredToolCallEvent):
print('Tool deferred:', event)
elif isinstance(event, DeferredToolResultEvent):
print('Deferred result received:', event)
elif isinstance(event, EnqueuedMessagesEvent):
print('Enqueued messages delivered:', event)
from pydantic_ai import HistoryProcessor
from pydantic_ai import Agent, RunContext
agent = Agent('openai:gpt-4o')
@agent.tool
async def my_tool(ctx: RunContext[None]) -> str:
limits = ctx.usage_limits
if limits and limits.response_tokens_limit and limits.response_tokens_limit < 500:
return 'Skipping — too close to token limit'
return 'Proceeding with full response'
/usage
agent.to_cli(model='openai:gpt-4o')
model = 'azure-responses:gpt-4o'
await dataset.evaluate(
task=my_task,
lifecycle=lambda: MyEvalLifecycle(),
)
from pydantic_ai import known_model_names
for name in known_model_names():
print(name)
from pydantic_ai.providers.xai import XaiProvider
provider = XaiProvider(
api_host="https://my-xai-proxy.example.com",
timeout=30,
)
from pydantic_ai.providers.xai import XaiProvider
from pydantic_ai import Agent
agent = Agent(
model="xai:grok-3",
model_settings={"seed": 42},
provider=XaiProvider(),
)
from pydantic_ai.models.openrouter import OpenRouterModel
model = OpenRouterModel(
'anthropic/claude-3-5-sonnet',
anthropic_eager_input_streaming=True,
)
agent_run.enqueue("Please also summarize in bullet points.")
from pydantic_ai.models.openai import OpenAIResponsesModel
model = OpenAIResponsesModel('gpt-4o')
token_count = await model.count_tokens(messages, model_settings=None)
evaluator = OnlineEvaluator(run_on_errors=True)
agent = Agent(
'openai:gpt-4o',
capabilities=[NativeTool(...), Instrumentation(...)]
)
settings = OpenAIResponsesModelSettings(openai_conversation_id='<your-conversation-id>')
result = await agent.run('Follow-up question', model_settings=settings)
with agent.override(builtin_tools=[]):
result = await agent.run('What time is it?')
from pydantic_ai import Agent
agent = Agent(
'anthropic:claude-opus-4-6',
model_settings={'service_tier': 'priority'},
)
result = agent.run_sync('Summarize this document.')
print(result.output)
agent = Agent(model=model, end_strategy='graceful')
agent = Agent(model=model, output_type=str | None)
from pydantic_ai.capabilities import OpenAICompaction
agent = Agent(
'openai:gpt-4o',
capabilities=[OpenAICompaction()],
)
from pydantic_ai.capabilities import CapabilityOrdering
ordering = CapabilityOrdering(my_outer_capability, wraps=my_inner_capability)
from pydantic_ai.http import create_async_http_client
async with create_async_http_client() as client:
agent = MyAgent(http_client=client)
result = await agent.run('Hello')
from pydantic_ai.tools import ToolDefinition
def my_tool(x: int) -> str:
return str(x)
td = ToolDefinition(
name='my_tool',
description='Converts int to str',
parameters_json_schema={},
return_schema=..., # new field
function_signature=..., # new field
)
print(td.return_schema)
print(td.function_signature)
from pydantic_ai import Agent
from pydantic_ai.tools import Tool
def my_tool_fn(ctx, query: str) -> str:
return f'result for {query}'
tool = Tool(my_tool_fn, defer_loading=True)
agent = Agent('openai:gpt-4o', tools=[tool])
import asyncio
from pydantic_ai import Agent
agent = Agent('anthropic:claude-sonnet-4-5')
async def main():
async with agent.using_thread_executor():
result = await agent.run('Summarize this document.')
print(result.output)
asyncio.run(main())
@agent.tool
async def my_tool(ctx: RunContext[MyDeps]) -> str:
current_agent = ctx.agent # newly available in v1.76.0
return f"Running as: {current_agent.name}"
from pydantic_ai.messages import TextContent
prompt = TextContent(text='Summarize this document.', metadata={'session_id': 'abc123', 'user_tier': 'pro'})
result = await agent.run([prompt])
from pydantic_ai import ModelRetry
def after_request(ctx):
if not response_is_valid(ctx.response):
raise ModelRetry('Response failed validation, retrying')
from pydantic_ai.models.anthropic import AnthropicModelSettings
settings = AnthropicModelSettings(anthropic_eager_input_streaming=True)
from pydantic_ai import Agent
agent = Agent.from_file('my_agent.yaml')
class MyToolset(AbstractToolset):
async def for_run(self, ctx):
return MyToolset(session=ctx.deps.session)
agent = Agent('openai:gpt-5.4-nano', toolsets=[MyToolset()])
from pydantic_ai.models.bedrock import BedrockModelSettings
settings = BedrockModelSettings(
bedrock_inference_profile="us.anthropic.claude-3-5-sonnet-20241022-v2:0"
)
agent = Agent("bedrock:anthropic.claude-3-5-sonnet-20241022-v2:0", model_settings=settings)
agent = Agent(model='openai:gpt-4o', description='Summarises customer support tickets and routes to the correct team')
from pydantic_ai import PromptedOutput
output = PromptedOutput(MyModel, template=False)
print(model.model_id) # e.g. 'openai:gpt-4o'
from pydantic_ai.models.google import GoogleModel
model = GoogleModel('gemini-2.0-flash', extra_headers={'X-My-Trace-Id': 'abc123'})
from pydantic_evals import Dataset
results = await dataset.evaluate(pipeline, repeat=5)
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
agent = Agent(
AnthropicModel('claude-opus-4-6'),
model_settings=AnthropicModelSettings(
anthropic_effort='auto',
anthropic_thinking={'type': 'adaptive'}
)
)
result = agent.run_sync('Explain quantum entanglement.')
print(result.output)
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
agent = Agent(
AnthropicModel('claude-opus-4-6'),
model_settings=AnthropicModelSettings(
anthropic_betas=['interleaved-thinking-2025-05-14']
)
)
result = agent.run_sync('Draft a threat model for a SaaS API.')
print(result.output)
from pydantic_ai.models.openai import OpenAIChatModel
model = OpenAIChatModel('gpt-4o', openai_store=False)
from pydantic_ai.models.bedrock import BedrockEmbeddingModel
model = BedrockEmbeddingModel('amazon.nova-lite-v1')
result = await model.embed(['Hello, world!'])
from pydantic_ai.tools.web_search import WebSearchTool
tool = WebSearchTool(allowed_domains=["example.com", "docs.openai.com"])
from pydantic_ai import Agent
agent = Agent(
"openai:gpt-4o",
model_settings={"continuous_usage_stats": True},
)
from pydantic_ai.exceptions import ContentFilterError
try:
result = await agent.run('Generate something sensitive')
except ContentFilterError as e:
print(f'Model blocked the response: {e}')
BinaryContent.from_path('config.yaml')
from pydantic_ai.models.bedrock import BedrockModelSettings
settings = BedrockModelSettings(bedrock_service_tier='standard')
result = await agent.run('Summarize this document', model_settings=settings)
ImageGenerationTool(output_format='jpeg', output_compression=80)
clai web
from pydantic_ai import Agent
agent = Agent('openai:gpt-4o', system_prompt='You are a helpful assistant.')
agent.to_web()
class MyWorkflow:
__pydantic_ai_agents__ = [research_agent, summary_agent]
async def run(self) -> str:
...
from pydantic_ai import Agent
from pydantic import BaseModel
class Answer(BaseModel):
summary: str
confidence: float
agent = Agent('openai:gpt-4o', output_type=Answer)
print(agent.output_json_schema())
from pydantic_ai.evaluate import LLMJudge
judge = LLMJudge(model='openai:gpt-4o')
result = await judge.evaluate(question='Is Paris the capital of France?', answer='Yes')
print(result)
from pydantic_ai.adapters.vercel import VercelAIAdapter
vercel_messages = VercelAIAdapter.dump_messages(result.all_messages())
from pydantic_ai import Agent
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.models.anthropic import AnthropicModel
model = FallbackModel(OpenAIModel('gpt-4o'), AnthropicModel('claude-3-5-sonnet-latest'))
agent = Agent(model)
result = agent.run_sync('Analyze this log file for anomalies.')
print(result.output)
from pydantic_ai.messages import BinaryContent
content = BinaryContent.from_path('screenshot.png')
from pydantic_ai.mcp import MCPServerSSE
server = MCPServerSSE(url='http://localhost:8080/sse')
print(server.instructions)
from pydantic_ai.messages import ModelRequest
# metadata flows through the request/response cycle
request = ModelRequest(parts=[...], metadata={'trace_id': 'abc-123', 'env': 'prod'})
print(request.metadata) # {'trace_id': 'abc-123', 'env': 'prod'}
from pydantic_ai.exceptions import CallDeferred
raise CallDeferred(metadata={'queue': 'human-review', 'priority': 'high'})
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["server.py"],
"env": {
"API_KEY": "${MY_API_KEY}"
}
}
}
}
from pydantic_ai import Agent
from pydantic_ai.models.bedrock import BedrockConverseModel
from pydantic_ai.usage import UsageLimits
model = BedrockConverseModel('anthropic.claude-3-5-sonnet-20241022-v2:0')
agent = Agent(model)
result = await agent.run(
'Summarise this document',
usage_limits=UsageLimits(request_tokens_limit=8000, count_tokens_before_request=True),
)
result = await agent.run('What is the capital of France?')
print(result.run_id) # e.g. 'a3f1c2d4-...'
# Use result.run_id to filter logs or link all messages from this run
result = await agent.run('What is the capital of France?')
all_msgs = result.all_messages()
new_msgs = result.new_messages_json()
from pydantic_ai.models.gateway import GatewayModel
model = GatewayModel(
model_name='gpt-4o',
api_type='azure',
profile='prod-profile',
routing_group='eu-west',
)
result = await agent.run(
'Summarize this document',
instructions='Always respond in formal English and limit output to 3 sentences.'
)
from pydantic_ai import RunContext
@agent.output_validator
async def check_output(ctx: RunContext, value: MyOutput) -> MyOutput:
if ctx.partial_output is not None:
# inspect intermediate state before full validation
print('Partial so far:', ctx.partial_output)
return value
with agent.run_stream_sync('Summarise this document') as result:
for text in result.stream_text():
print(text, end='', flush=True)
from pydantic_ai import Agent
from pydantic_ai.models.outlines import OutlinesModel
model = OutlinesModel('transformers', model_name='mistralai/Mistral-7B-v0.1')
agent = Agent(model)
result = agent.run_sync('Summarize this CVE advisory: ...')
print(result.data)
from pydantic_ai.models.openai import OpenAIModelProfile
profile = OpenAIModelProfile(openai_responses_requires_function_call_status_none=True)
from pydantic_ai.tools import MCPServerTool
from pydantic_ai.exceptions import IncompleteToolCall
try:
result = await agent.run(prompt)
except IncompleteToolCall as e:
print(f'Tool call was cut off by token limit: {e}')
from pydantic_ai.providers.google import GoogleProvider
provider = GoogleProvider(api_key='YOUR_VERTEX_API_KEY')
@agent.tool(description='Fetches the current weather for a given city from the weather API')
def get_weather(ctx, city: str) -> str:
...
report = EvaluationReport(...)
print(report.render())
async for event in agent.run_stream_events('Summarize this document', deps=deps):
print(event)
result = await agent.run('What is 2 + 2?')
print(result.response.text)
info = await mcp_server.server_info
print(info)
from pydantic_ai.models.openai import ImageUrl
image = ImageUrl(
url='https://example.com/diagram.png',
vendor_metadata={'detail': 'high'}
)
from pydantic_ai.output import OutputObjectDefinition
from pydantic_ai import RunContext
async def my_tool(ctx: RunContext[None], query: str) -> str:
if ctx.last_attempt:
return f'Final attempt reached (max={ctx.max_retries}), returning cached result'
result = call_external_api(query)
return result
from pydantic_ai.toolsets import FunctionToolset
toolset = FunctionToolset(
strict=True,
sequential=False,
requires_approval=True,
metadata={"source": "internal"}
)
from pydantic_ai.tools import ToolDefinition
def only_safe_tools(tool_def: ToolDefinition) -> bool:
meta = tool_def.metadata or {}
return not meta.get("destructive", False)
with agent.sequential_tool_calls():
result = await agent.run('Book a flight then send a confirmation email')
async def handle_complete(result: AgentRunResult) -> None:
print(result.output)
await agent.run_as_agui(prompt, on_complete=handle_complete)
from pydantic_ai.settings import ModelSettings
result = await agent.run('Summarize this doc', model_settings=ModelSettings(seed=42))
from pydantic_ai.models.google import GoogleModelSettings
settings = GoogleModelSettings(
google_cached_content="cachedContents/abc123"
)
result = await agent.run("Summarize the document.", model_settings=settings)
from pydantic_ai import Agent
from pydantic_ai.settings import UsageLimits
agent = Agent('openai:gpt-4o')
result = await agent.run(
'Research and summarize the latest CVEs for OpenSSL',
usage_limits=UsageLimits(tool_calls_limit=5)
)
print(result.usage().tool_calls) # inspect actual tool calls made
from pydantic_ai.toolsets import FunctionToolset
toolset = FunctionToolset(
docstring_format='google',
require_parameter_descriptions=True
)
agent.to_cli(message_history=prior_messages)
result = await agent.run('Summarise this document')
print(result.new_messages()[-1].price())
tool = Tool.from_schema(schema=my_schema, takes_ctx=True)
from pydantic_ai.models.google import UrlContextTool
agent = Agent(model='google-gla:gemini-2.0-flash', tools=[UrlContextTool()])
from pydantic_ai.models.fallback import FallbackModel
model = FallbackModel('openai:gpt-4o', 'anthropic:claude-3-5-sonnet-latest')
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.tools.anthropic import WebSearchTool
agent = Agent(
model=AnthropicModel('claude-3-5-sonnet-latest'),
tools=[WebSearchTool(max_uses=3)],
)
result = agent.run_sync('What are the latest CVEs in OpenSSL?')
print(result.output)
from pydantic_ai import Agent
agent = Agent('openai-responses:gpt-4o')
result = await agent.run('What is the capital of France?')
print(result.output)
async with agent.run_stream('Analyze logs', event_stream_handler=my_handler) as response:
async for chunk in response.stream_text():
print(chunk)
from pydantic_ai.models.openai import OpenAIModelSettings
settings = OpenAIModelSettings(service_tier='priority')
result = await agent.run('Summarize this incident report.', model_settings=settings)
from pydantic_ai.mcp import MCPServer
server = MCPServer(
url='https://mcp.example.com/sse',
read_timeout=30,
)
from pydantic_ai.messages import BinaryContent
image = BinaryContent(data=image_bytes, media_type='image/png', identifier='screenshot-001')
result = await agent.run([image, 'Describe this image.'])
from pydantic_ai.models.openai import OpenAIModelSettings
settings = OpenAIModelSettings(
predicted_outputs={"type": "content", "content": "<your predicted text here>"}
)
result = await agent.run("Refactor this code", model_settings=settings)
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessage
def redact_secrets(messages: list[ModelMessage]) -> list[ModelMessage]:
# drop any message whose text contains an API key pattern
return [m for m in messages if 'sk-' not in str(m)]
agent = Agent('openai:gpt-4o', history_processors=[redact_secrets])
result = agent.run_sync('What did we discuss earlier?')
from pydantic_ai.models.openai import OpenAIModelSettings
settings = OpenAIModelSettings(service_tier='flex')
from pydantic_ai import Agent
from pydantic_ai.providers.heroku import HerokuProvider
agent = Agent(provider=HerokuProvider())
from pydantic_ai import Agent
def send_alert(message: str, severity: str) -> None:
... # your implementation
agent = Agent('openai:gpt-4o', output_type=send_alert)
result = await agent.run('Notify me if CPU exceeds 90%')
from pydantic_ai import Agent
from pydantic_ai.providers.together import TogetherProvider
agent = Agent(TogetherProvider(), model='meta-llama/Llama-3-70b-chat-hf')
result = await agent.run('Summarize this incident report: ...')
from pydantic_ai.mcp import MCPServerStdio
search_server = MCPServerStdio('npx', ['-y', '@modelcontextprotocol/server-brave-search'], tool_prefix='search')
fs_server = MCPServerStdio('npx', ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], tool_prefix='fs')
# Tools are now exposed as 'search_<name>' and 'fs_<name>', and duplicate bare names raise an error.
from pydantic_ai.models.openai import OpenAIModel
model = OpenAIModel('openai/gpt-4o', provider='openrouter')
from pydantic_ai.settings import InstrumentationSettings
settings = InstrumentationSettings(include_binary_content=False)
agent = Agent(model='openai:gpt-4o', system_prompt='You are a helpful assistant.')
if __name__ == '__main__':
agent.to_cli()
response = await model.request(messages, model_request_parameters)
print(response.usage)
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent(
'openai:gpt-4o',
model_settings=ModelSettings(extra_headers={'X-Custom-Header': 'my-value'})
)
result = agent.run_sync('Hello')
from pydantic_ai.providers.mistral import MistralProvider
provider = MistralProvider(base_url='https://my-mistral-instance.example.com/v1')
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
agent = Agent(OpenAIModel('o3'))
# or
agent = Agent(OpenAIModel('o4-mini'))
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent(
'openai:gpt-4o',
model_settings=ModelSettings(extra_body={'reasoning_effort': 'high'})
)
result = agent.run_sync('Explain quantum entanglement.')
print(result.data)
StdioServerParameters(command='npx', args=['-y', 'my-mcp-server'], cwd='/path/to/project')
result = await agent.run('Classify this alert.')
for span in result.spans:
print(span.name, span.start_time)
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent(
'openai:gpt-4o',
model_settings=ModelSettings(stop_sequences=['---END---']),
)
result = await agent.run('Summarize this document.')
print(result.output)
from pydantic_ai.models.openai import OpenAIResponsesModelSettings
settings = OpenAIResponsesModelSettings(
generate_summary=True,
truncation='auto'
)
MCPServerHTTP(
url='https://mcp.example.com/sse',
headers={'Authorization': 'Bearer <token>'},
timeout=30,
sse_read_timeout=60
)
from pydantic_ai import Agent
Agent.instrument_all()
agent = Agent('openai:gpt-4o', instrument=True)
async with my_graph.iter(initial_state) as graph_run:
async for node in graph_run:
print(node)
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
model = OpenAIModel('gpt-4.5-preview')
agent = Agent(model=model)
result = agent.run_sync('Summarize the threat landscape for Q1 2025.')
print(result.data)
from pydantic_ai.tools.duckduckgo import DuckDuckGoSearchTool
tool = DuckDuckGoSearchTool(max_results=5)
from pydantic_ai import Agent, RunContext
agent = Agent('openai:gpt-4o')
@agent.tool
async def my_tool(ctx: RunContext[None], query: str) -> str:
call_id = ctx.tool_call_id # new in v0.0.28
print(f'Handling call {call_id} for query: {query}')
return f'result for {query}'
from pydantic_ai import Agent
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.models.anthropic import AnthropicModel
model = FallbackModel(OpenAIModel('gpt-4o'), AnthropicModel('claude-3-5-sonnet-latest'))
agent = Agent(model=model)
result = agent.run_sync('Summarize this report.')
print(result.data)
from pydantic_ai import Agent
from pydantic_ai.models.instrumented import InstrumentedModel
from pydantic_ai.models.openai import OpenAIModel
base_model = OpenAIModel('gpt-4o')
instrumented = InstrumentedModel(base_model)
agent = Agent(instrumented)
result = await agent.run('Summarize this document.')
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
model = OpenAIModel('o3', reasoning_effort='medium')
agent = Agent(model)
result = agent.run_sync('Explain zero-day vulnerability triage strategies.')
print(result.data)
from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings
agent = Agent('openai:gpt-4o', model_settings=ModelSettings(parallel_tool_calls=False))
result = agent.run_sync('Book a flight and then a hotel')
@agent.system_prompt(dynamic=True)
def my_prompt(ctx: RunContext) -> str:
return f"Today is {date.today()}. User: {ctx.deps.username}"
result = await agent.run("Summarise this", result_type=MySummaryModel)
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
model = OpenAIModel('llama-3', base_url='http://localhost:11434/v1')
agent = Agent(model)
result = agent.run_sync('Summarize the threat report.')
print(result.data)
from pydantic_ai import Agent
from pydantic_ai.models.mistral import MistralModel
agent = Agent(MistralModel('mistral-large-latest'))
result = agent.run_sync('List the top 5 OWASP API risks.')
print(result.data)
from pydantic_ai import Agent
agent = Agent('openai:gpt-4o', name='support-agent') Summary
PydanticAI is an open-source AI tool that provides a typed, extensible agent loop connecting to various models via a string swap. It requires no explicit cost to use. Users incorporate it as a library into their existing Python code to manage agent workflows. This is intended for application developers building agent systems. Its documentation positions it alongside other frameworks for building LLM-powered applications. As of the latest commit status, the project maintains active development activity.
How Python does AI: agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.
What PydanticAI answers
Which environments can the agent loop execute within?
in a web frontend, the terminal, a voice call, a durable background queue, or as a simple callable object
What modalities can the agent interact with?
text, voice, and images
What types of external services does it support?
various models through a string swap mechanism
What kind of functionality is included out of the box?
embeddings and image generation capabilities
What is the mechanism for connecting different models?
a string swap approach
Does the agent library have a command-line interface?
yes, it includes one for terminal use
Examples
Command line
No option matches that search.
| option | found in | since | description |
|---|
No option matches that search.
Values are placeholders taken from each option’s declared default. Nothing is executed here — the output shown is a recording of a run that already happened.
Release history
- v2.36.0
PydanticAI v2.36.0 adds
@durable_operationfor third-party durable execution, stableInstructionPart.id, async-iterable audio input, and--mcp-configsupport inclai.└──▷ GET THIS VERSION$ git clone --branch v2.36.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.36.0
└──▷ USE ITStream audio from an async generator directly into a realtime voice session instead of pushing discrete chunks.async def mic_chunks(): async for chunk in microphone_stream(): yield chunk async with agent.realtime('openai:gpt-realtime-2.1').session() as session: await session.send_audio(mic_chunks())- ›Adds
--mcp-configflag to theclaiCLI, enabling MCP server configuration from the command line; also adds tool-call streaming support toclai. - ›Introduces
@durable_operationdecorator with a required explicit operation name, plus a public backend API for integrating third-party durable execution engines. - ›Gives
InstructionParta stableInstructionPart.idfield, making instruction parts addressable and stable across runs. - ›Accepts async iterables in RealtimeSession.send_audio(), enabling streaming microphone input from async generators rather than only discrete chunks.
- ›Adds
- v2.34.0
PydanticAI v2.34.0 adds GLM-5.3 support via
ZhipuModeland a LangChain migration skill.└──▷ GET THIS VERSION$ git clone --branch v2.34.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.34.0
- ›Adds a LangChain migration skill to help teams port existing LangChain agents to PydanticAI.
- v2.32.0
PydanticAI v2.32.0 adds xAI attachment search lifecycle, OpenRouter web-search annotations, and instrumentation v6 with tool-role emissions.
└──▷ GET THIS VERSION$ git clone --branch v2.32.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.32.0
- ›Surfaces OpenRouter web-search sources in
provider_details["annotations"]on message objects, making citation data accessible to downstream code. - ›Adds instrumentation version 6, emitting tool results under
role: 'tool'for improved observability of tool call/result pairs in traces. - ›Supports xAI attachment search lifecycle, enabling attachment-based search flows via the xAI provider.
- ›Surfaces OpenRouter web-search sources in
- v2.31.0
PydanticAI v2.31.0 lets UIEventStream initialize without a run_input and gives AGUIEventStream its own thread_id/run_id.
└──▷ GET THIS VERSION$ git clone --branch v2.31.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.31.0
- ›Adds support for building a
UIEventStreamwithout arun_input, enabling stream construction before run context is available. - ›Gives
AGUIEventStreamits ownthread_idandrun_idfields for independent stream identification.
- ›Adds support for building a
- v2.31.0
UIEventStream can now be built without a run_input, and AGUIEventStream gets its own thread_id and run_id.
└──▷ GET THIS VERSION$ git clone --branch v2.31.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.31.0
- ›Allows
UIEventStreamto be constructed without arun_input, enabling more flexible event stream initialization. - ›Gives
AGUIEventStreamits ownthread_idandrun_idfields for independent stream identity.
- ›Allows
- v1.107.5
Adds
allowed_hostssetting to the local dev web UI to prevent DNS rebinding attacks on Agent.to_web() /clai web.└──▷ GET THIS VERSION$ git clone --branch v1.107.5 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.107.5
- ›Adds
allowed_hostssetting to the local dev web chat UI (Agent.to_web() /clai web) to explicitly permit non-localhost hostnames, required for deployments reached under a real hostname.
└──▷ BREAKING ON UPGRADE- !The local dev web chat UI (Agent.to_web(),
clai web) now validates the Host header against localhost/loopback/LAN addresses by default; deployments served under a real (non-local) hostname will be blocked and must opt in with the newallowed_hostssetting.
- ›Adds
- v2.30.0
PydanticAI v2.30.0 adds
allowed_hostsfor the local web UI, OpenRouter web search, Gemini 3.7 Flash, and gRPC metadata on XaiProvider.└──▷ GET THIS VERSION$ git clone --branch v2.30.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.30.0
└──▷ USE ITAllow the local web UI to be reached under a custom hostname in a non-loopback deployment.agent.to_web(allowed_hosts=['mydevbox.internal'])
Run a web search via OpenRouter directly from a PydanticAI agent.from pydantic_ai import Agent agent = Agent(model='openrouter:web_search') result = agent.run_sync('What are the latest CVEs in OpenSSL?') print(result.data)- ›Adds
allowed_hostssetting to Agent.to_web() andclai webto explicitly permit non-loopback hostnames when deploying the local dev web chat UI under a real hostname. - ›Adds support for
openrouter:web_searchas a web search model via the OpenRouter provider. - ›Adds
gemini-3.7-flashto the supported Gemini model catalog. - ›Exposes gRPC
metadataonXaiProviderfor passing custom gRPC metadata to xAI endpoints.
└──▷ BREAKING ON UPGRADE- !The local dev web chat UI (Agent.to_web(),
clai web) now validates the Host header against localhost/loopback/LAN addresses by default; deployments reached under a real hostname will be blocked unlessallowed_hostsis explicitly configured.
- ›Adds
- v2.30.0
PydanticAI v2.30.0 adds
allowed_hostsfor the web UI, OpenRouter web search, Gemini Flash 3.7, and xAI gRPC metadata support.└──▷ GET THIS VERSION$ git clone --branch v2.30.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.30.0
└──▷ USE ITAllow a specific external hostname when hosting the web UI beyond localhost — required after the new Host-header validation is enforced by default.agent.to_web(allowed_hosts=['myagent.internal.example.com'])
Run a one-shot web-search-backed query through OpenRouter directly from the CLI.$ clai --model openrouter:web_search 'What are the latest CVEs in OpenSSL?'
- ›Adds
allowed_hostssetting to Agent.to_web() andclai webto explicitly permit non-localhost hostnames, required for deployments served under a real hostname (introduced alongside a Host-header validation fix for GHSA-q2xc-rrxj-58x9). - ›Supports
openrouter:web_searchas a model string for built-in web search via OpenRouter. - ›Adds
gemini-3.7-flashto the supported model catalog. - ›Exposes gRPC
metadataonXaiProviderfor passing custom gRPC metadata to xAI endpoints.
└──▷ BREAKING ON UPGRADE- !The local dev web chat UI (Agent.to_web(),
clai web) now validates the Host header against localhost/loopback/LAN addresses by default; deployments served under a real hostname will be blocked unless they opt in with the newallowed_hostssetting.
- ›Adds
- v2.29.0
PydanticAI v2.29.0 adds FastMCP 4 / MCP SDK v2 support and Azure AI Voice Live integration.
└──▷ GET THIS VERSION$ git clone --branch v2.29.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.29.0
- ›Adds
azure_voice_livesetting to enable Azure AI Voice Live realtime voice capabilities. - ›Supports FastMCP 4 and MCP SDK v2 in MCPToolset alongside the existing FastMCP 3 compatibility.
- ›Adds
- v2.29.0
PydanticAI v2.29.0 adds FastMCP 4 / MCP SDK v2 support in MCPToolset and Azure AI Voice Live via
azure_voice_live.└──▷ GET THIS VERSION$ git clone --branch v2.29.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.29.0
- ›Adds
azure_voice_livesetting to enable Azure AI Voice Live as a realtime voice backend. - ›Supports FastMCP 4 and MCP SDK v2 in MCPToolset alongside the existing FastMCP 3 compatibility.
- ›Adds
- v2.28.0
PydanticAI v2.28.0 adds real-time speech-to-speech via Agent.realtime() plus a new Crusoe provider
└──▷ GET THIS VERSION$ git clone --branch v2.28.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.28.0
- ›Adds Agent.realtime() method for real-time speech-to-speech interactions with an agent.
- ›Adds browser WebRTC and server sideband support for real-time speech-to-speech sessions.
- ›Adds Crusoe as a new LLM provider.
- ›Adds
cerebrasoptional dependency group.
- v2.28.0
PydanticAI v2.28.0 adds real-time speech-to-speech via Agent.realtime(), WebRTC sideband support, and a Crusoe model provider.
└──▷ GET THIS VERSION$ git clone --branch v2.28.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.28.0
└──▷ USE ITPut an agent on a live voice session with tools — the model calls your tools mid-conversation while it keeps talking.import asyncio from pydantic_ai import Agent agent = Agent(instructions='You are a helpful voice assistant.') @agent.tool_plain def order_status(order_id: str) -> str: """Look up the status of an order.""" return f'Order {order_id}: shipped, arriving Thursday.' async with agent.realtime('openai:gpt-realtime-2.1').session() as session: async for part in session.stream_transcripts(): print(f'{part.speaker}: {part.transcript}')- ›Adds Agent.realtime() method for real-time speech-to-speech sessions, enabling live voice conversations with tool-calling support across OpenAI Realtime, Gemini Live, Azure, and xAI Grok Voice backends.
- ›Adds browser WebRTC plus server sideband support for real-time speech-to-speech sessions initiated via Agent.realtime().
- ›Adds a
cerebrasoptional dependency group for the Cerebras provider. - ›Adds Crusoe as a new model provider.
- v2.27.0
PydanticAI v2.27.0 adds SnowflakeModel/SnowflakeProvider, xai_agent_count setting, and CompactionPart round-trip for Vercel AI and AG-UI adapters.
└──▷ GET THIS VERSION$ git clone --branch v2.27.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.27.0
- ›Adds
xai_agent_countfield toXaiModelSettingsfor controlling xAI agent concurrency. - ›Adds
SnowflakeModelandSnowflakeProviderclasses for integrating with Snowflake Cortex as an LLM backend. - ›Supports round-tripping
CompactionPartthrough the Vercel AI and AG-UI adapters, preserving compaction state across adapter boundaries.
- ›Adds
- v2.27.0
PydanticAI v2.27.0 adds Snowflake Cortex support, xAI agent count control, and CompactionPart round-tripping across Vercel AI and AG-UI adapters.
└──▷ GET THIS VERSION$ git clone --branch v2.27.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.27.0
- ›Adds
xai_agent_countfield toXaiModelSettingsto control the number of xAI agents used per request. - ›Adds
SnowflakeModelandSnowflakeProviderclasses for Snowflake Cortex LLM integration. - ›Supports round-tripping
CompactionPartthrough the Vercel AI and AG-UI adapters, preserving compaction state across adapter boundaries.
- ›Adds
- v2.26.0
PydanticAI v2.26.0 adds run cancellation, hidden/revealed tools, DeepSeek V4 Flash support, and a public AgentRunEvents handle.
└──▷ GET THIS VERSION$ git clone --branch v2.26.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.26.0
└──▷ USE ITStream agent events and cancel mid-run based on application logic using the new public AgentRunEvents handle.async with agent.run_stream_events(user_prompt) as events: async for event in events: if should_stop(event): events.cancel() breakUse DeepSeek V4 Flash in an agent via the OpenAI-compatible responses model and DeepSeek provider.from pydantic_ai.models.openai import OpenAIResponsesModel from pydantic_ai.providers.deepseek import DeepSeekProvider model = OpenAIResponsesModel('deepseek-chat', provider=DeepSeekProvider()) agent = Agent(model=model)- ›Adds AgentRun.cancel() and RunContext.cancel() for first-party run cancellation, raising
RunCancelledto stop in-flight agent runs programmatically. - ›Adds Model.resolve_prompt_cache_retention() to resolve the effective prompt-cache retention setting from model settings.
- ›Promotes the run_stream_events() iterator to a public
AgentRunEventshandle exposing cancel() and run-state access. - ›Supports hiding function tools until revealed — via tool search,
load_capability, orToolReturn.tools— using each provider's native deferral/addition channel. - ›Covers DeepSeek V4 Flash via
OpenAIResponsesModelandDeepSeekProvider.
- ›Adds AgentRun.cancel() and RunContext.cancel() for first-party run cancellation, raising
- v2.26.0
PydanticAI v2.26.0 adds first-party run cancellation, hidden/revealed tools, DeepSeek V4 Flash support, and a public AgentRunEvents handle.
└──▷ GET THIS VERSION$ git clone --branch v2.26.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.26.0
└──▷ USE ITCancel a long-running agent run from outside the agent loop — useful for enforcing timeouts or user-triggered stops.import asyncio from pydantic_ai import Agent agent = Agent('openai:gpt-4o') async def main(): async with agent.run_stream('Summarize the entire history of computing') as run: asyncio.get_event_loop().call_later(5, run.cancel) async for chunk in run.stream_text(): print(chunk, end='', flush=True) asyncio.run(main())Cancel a run from inside a tool when a condition is met — e.g. an abuse-detection tool that aborts the run immediately.from pydantic_ai import Agent, RunContext agent = Agent('openai:gpt-4o') @agent.tool def safety_check(ctx: RunContext[None], text: str) -> str: if 'forbidden' in text: ctx.cancel() return 'Aborted.' return 'OK' result = agent.run_sync('Please say something forbidden') print(result.output)- ›Adds AgentRun.cancel() and RunContext.cancel() methods plus a
RunCancelledexception for first-party run cancellation. - ›Adds Model.resolve_prompt_cache_retention() to resolve the effective prompt-cache retention from model settings.
- ›Promotes run_stream_events() to a public
AgentRunEventshandle with cancel() and run-state access. - ›Supports hiding function tools until revealed via tool search,
load_capability, orToolReturn.tools, using each provider's native deferral/addition channel. - ›Adds DeepSeek V4 Flash support via
OpenAIResponsesModelandDeepSeekProvider.
- ›Adds AgentRun.cancel() and RunContext.cancel() methods plus a
- v2.25.0
PydanticAI v2.25.0 forwards xAI FileSearchTool collection search options.
└──▷ GET THIS VERSION$ git clone --branch v2.25.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.25.0
- ›Forwards xAI
FileSearchToolcollections search options to the underlying API.
- ›Forwards xAI
- v2.25.0
PydanticAI v2.25.0 forwards xAI
FileSearchToolcollection search options to the xAI backend.└──▷ GET THIS VERSION$ git clone --branch v2.25.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.25.0
- ›Forwards xAI
FileSearchToolcollections search options through to the xAI backend, enabling parameterized file-search collection queries.
- ›Forwards xAI
- v2.23.0
PydanticAI v2.23.0 adds cost tracking with
costandcost_limit, Bedrockextra_headers, and dynamic tool availability parts.└──▷ GET THIS VERSION$ git clone --branch v2.23.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.23.0
└──▷ USE ITCap how much an agent run can spend by setting acost_limitonUsageLimitsalongside an existing token budget.from pydantic_ai import Agent from pydantic_ai.usage import UsageLimits agent = Agent('openai:gpt-4o') result = await agent.run( 'Summarize this document...', usage_limits=UsageLimits(request_limit=10, cost_limit=0.05), ) print(result.usage().cost)Pass custom headers (e.g. for cost allocation tagging) to every Bedrock request viaModelSettings.extra_headers.from pydantic_ai import Agent from pydantic_ai.settings import ModelSettings agent = Agent('bedrock:anthropic.claude-3-5-sonnet-20241022-v2:0') result = await agent.run( 'Explain zero-trust networking.', model_settings=ModelSettings(extra_headers={'x-amzn-bedrock-workload-name': 'sec-review'}), ) print(result.output)- ›Adds
costfield toRunUsageandcost_limitfield toUsageLimitsto track and cap monetary spend per agent run. - ›Adds
extra_headerssupport inModelSettingsfor Amazon Bedrock requests. - ›Adds
ToolAvailabilityDeltaPartwith nativetool_additionandadditional_toolsrendering to represent dynamic tool availability changes in agent message streams.
- ›Adds
- v2.23.0
PydanticAI v2.23.0 adds cost tracking to RunUsage, a cost_limit to UsageLimits, ToolAvailabilityDeltaPart, and Bedrock extra_headers support.
└──▷ GET THIS VERSION$ git clone --branch v2.23.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.23.0
└──▷ USE ITFail an agent run before it spends beyond a set dollar threshold — useful for enforcing per-request budget limits in production.from pydantic_ai import Agent from pydantic_ai.usage import UsageLimits agent = Agent('openai:gpt-5.6-sol') result = agent.run_sync( 'Summarize the latest earnings report.', usage_limits=UsageLimits(cost_limit=0.05), ) print(result.usage().cost)- ›Adds
costfield toRunUsageandcost_limittoUsageLimitsto track and cap monetary spend per agent run. - ›Adds
extra_headerssupport toModelSettingsfor Amazon Bedrock requests, matching parity with other providers. - ›Adds
ToolAvailabilityDeltaPartwith nativetool_additionandadditional_toolsrendering for streaming tool-availability deltas.
- ›Adds
- v2.22.0
PydanticAI v2.22.0 adds
RunContext.is_tool_available, MCP task-skipping via prefer_tasks, and Gemini VALIDATED tool mode by default.└──▷ GET THIS VERSION$ git clone --branch v2.22.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.22.0
└──▷ USE ITSkip optional MCP background tasks (e.g. sampling) when the host runtime does not support them, avoiding hangs on unsupported transports.from pydantic_ai.mcp import MCPToolset toolset = MCPToolset( server_url='http://localhost:3000', prefer_tasks=False # skip optional MCP tasks rather than blocking )- ›Adds
RunContext.is_tool_availablemethod, letting tool code check at runtime whether another named tool is accessible in the current agent context. - ›Adds
prefer_tasksparameter to MCPToolset clients, allowing optional MCP tasks to be skipped when the runtime does not support them. - ›Adds configurable
max_retriestoToolSearchToolset, giving control over how many times a tool-search lookup is retried on failure. - ›Enables Gemini
VALIDATEDtool mode by default on supported models, improving structured tool-call reliability without manual configuration. - ›Sends mid-conversation system prompts as native
systemmessages on Anthropic, aligning prompt delivery with Anthropic's native message format.
- ›Adds
- v2.22.0
PydanticAI v2.22.0 adds
RunContext.is_tool_available, MCPToolset task-skipping viaprefer_tasks, and GeminiVALIDATEDtool mode by default.└──▷ GET THIS VERSION$ git clone --branch v2.22.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.22.0
└──▷ USE ITGate one tool's behavior on whether a complementary tool is currently registered and available in the run.from pydantic_ai import Agent, RunContext agent = Agent('openai:gpt-4o') @agent.tool async def summarize(ctx: RunContext[None], text: str) -> str: if ctx.is_tool_available('fetch_document'): return f'(fetch available) Summary of: {text}' return f'Summary of: {text}'- ›Adds
RunContext.is_tool_availablemethod, letting tool code check at runtime whether another tool is currently available before attempting to call it. - ›Adds
prefer_tasksparameter to MCPToolset clients, allowing optional MCP tasks to be skipped when not needed. - ›Adds configurable
max_retriestoToolSearchToolsetfor controlling retry behavior on tool search failures. - ›Enables Gemini
VALIDATEDtool mode by default on supported models, improving structured tool-call reliability. - ›Sends mid-conversation system prompts as native
systemmessages on Anthropic models instead of user-turn injections.
- ›Adds
- v2.21.0
PydanticAI v2.21.0 adds
per_request_input_tokens_limittoUsageLimitsfor per-call token budgets.└──▷ GET THIS VERSION$ git clone --branch v2.21.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.21.0
└──▷ USE ITPrevent any single LLM call from consuming more than a set number of input tokens, useful for guarding against unexpectedly large context windows in multi-turn agents.from pydantic_ai import Agent from pydantic_ai.usage import UsageLimits agent = Agent('openai:gpt-4o') result = agent.run_sync( 'Summarize this document.', usage_limits=UsageLimits(per_request_input_tokens_limit=4000), )- ›Adds
per_request_input_tokens_limitfield toUsageLimitsto cap input tokens on a per-request basis, independently of aggregate limits.
- ›Adds
- v2.21.0
PydanticAI v2.21.0 adds
per_request_input_tokens_limittoUsageLimitsfor per-request token budgeting.└──▷ GET THIS VERSION$ git clone --branch v2.21.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.21.0
└──▷ USE ITPrevent any single LLM request from consuming more than a set number of input tokens, useful for cost-controlling agents that may construct large context windows.from pydantic_ai import Agent from pydantic_ai.usage import UsageLimits agent = Agent('openai:gpt-5.6-sol') result = agent.run_sync( 'Summarize this document.', usage_limits=UsageLimits(per_request_input_tokens_limit=4000), )- ›Adds
per_request_input_tokens_limitfield toUsageLimitsto cap input tokens on a per-request basis, independently of cumulative session limits.
- ›Adds
- v2.20.0
PydanticAI v2.20.0 adds Claude Opus 5 and OpenAI Responses API
reasoning.contextsupport for GPT-5 families.└──▷ GET THIS VERSION$ git clone --branch v2.20.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.20.0
└──▷ USE ITRun inference against the new Claude Opus 5 model.from pydantic_ai import Agent agent = Agent('anthropic:claude-opus-5') result = agent.run_sync('Summarize the OWASP Top 10 for 2025.') print(result.output)- ›Adds
reasoning.contextsupport for the OpenAI Responses API, defaulting toall_turns, for thegpt-5.4,gpt-5.5, andgpt-5.6model families. - ›Adds
claude-opus-5model support via the Anthropic provider.
- ›Adds
- v2.20.0
PydanticAI v2.20.0 adds Claude Opus 5 support and OpenAI Responses API
reasoning.contextfor the gpt-5.4/5.5/5.6 families.└──▷ GET THIS VERSION$ git clone --branch v2.20.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.20.0
└──▷ USE ITUse Claude Opus 5 as the model for a PydanticAI agent.from pydantic_ai import Agent agent = Agent('anthropic:claude-opus-5') result = agent.run_sync('Summarize the latest threat intelligence report.') print(result.output)- ›Adds
reasoning.contextsupport (defaultall_turns) in the OpenAI Responses API for thegpt-5.4,gpt-5.5, andgpt-5.6model families. - ›Adds support for
claude-opus-5via theanthropic:claude-opus-5model string.
- ›Adds
- v2.19.0
PydanticAI v2.19.0 adds
headersandretry_afterfields toModelHTTPErrorfor richer HTTP error inspection.└──▷ GET THIS VERSION$ git clone --branch v2.19.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.19.0
└──▷ USE ITRespect a provider's rate-limit retry window by readingretry_afterfrom a caughtModelHTTPError.import asyncio from pydantic_ai.exceptions import ModelHTTPError try: result = await agent.run('summarize this') except ModelHTTPError as e: wait = e.retry_after # seconds until the provider allows retry if wait: await asyncio.sleep(wait) # inspect raw response headers if needed print(e.headers)- ›Adds
headersandretry_afterattributes toModelHTTPError, populated from all provider SDKs, enabling programmatic inspection of rate-limit and retry signals from HTTP errors.
- ›Adds
- v2.19.0
PydanticAI v2.19.0 adds
headersandretry_afterfields toModelHTTPErroracross all provider SDKs.└──▷ GET THIS VERSION$ git clone --branch v2.19.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.19.0
- ›Adds
headersandretry_afterattributes toModelHTTPError, populated from all provider SDKs, giving callers direct access to HTTP response headers and rate-limit retry timing from a single exception type.
- ›Adds
- v2.18.0
PydanticAI v2.18.0 adds AdvisorTool for Anthropic/OpenRouter, BedrockMantleProvider, multi-region Google Cloud, and external web access for OpenAI WebSearchTool.
└──▷ GET THIS VERSION$ git clone --branch v2.18.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.18.0
└──▷ USE ITRoute Bedrock requests through the Mantle provider for managed AWS Bedrock access.from pydantic_ai.providers.bedrock_mantle import BedrockMantleProvider provider = BedrockMantleProvider()
- ›Adds
external_web_accessoption toWebSearchToolfor OpenAI Responses API, enabling built-in web search without a separate tool. - ›Adds
BedrockMantleProviderfor AWS Bedrock Mantle integration, with normalized response-scoped tool-call IDs. - ›Extends
AdvisorToolsupport to Anthropic and OpenRouter providers. - ›Adds
'us'and'eu'multi-region location values toGoogleCloudProviderlocation type.
- ›Adds
- v2.18.0
PydanticAI v2.18.0 adds AdvisorTool for Anthropic/OpenRouter, BedrockMantleProvider, multi-region Google Cloud, and external_web_access for WebSearchTool.
└──▷ GET THIS VERSION$ git clone --branch v2.18.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.18.0
- ›Adds
external_web_accessoption toWebSearchToolfor OpenAI Responses API, enabling web search grounding on OpenAI Responses-backed agents. - ›Adds
BedrockMantleProviderfor AWS Bedrock Mantle, with normalized response-scoped tool-call IDs. - ›Extends
AdvisorToolsupport to Anthropic and OpenRouter providers. - ›Adds
'us'and'eu'multi-region location values toGoogleCloudProviderlocation type.
- ›Adds
- v2.17.0
PydanticAI v2.17.0 adds arbitrary fields to usage types and caches OTel serialization to eliminate O(n²) instrumentation cost.
└──▷ GET THIS VERSION$ git clone --branch v2.17.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.17.0
- ›Adds support for arbitrary fields on
RequestUsageandRunUsageto accommodate extended provider-specific pricing and metadata. - ›Caches per-message OpenTelemetry serialization, eliminating O(n²) instrumentation overhead for long conversation traces.
- ›Adds support for arbitrary fields on
- v2.17.0
RequestUsage and RunUsage now accept arbitrary fields; OTel serialization cached to eliminate O(n²) instrumentation cost.
└──▷ GET THIS VERSION$ git clone --branch v2.17.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.17.0
- ›Extends
RequestUsageandRunUsageto accept arbitrary extra fields, enabling support for upcoming genai-prices metadata. - ›Caches per-message OpenTelemetry serialization to eliminate O(n²) instrumentation overhead on long runs.
- ›Extends
- v2.16.0
PydanticAI v2.16.0 adds ToolFailed, Model Armor, run_id support, Mistral caching, and OpenAI moderation surface.
└──▷ GET THIS VERSION$ git clone --branch v2.16.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.16.0
└──▷ USE ITRaise a model-visible tool error without consuming retry budget — useful when a tool call is definitively invalid rather than transiently failing.from pydantic_ai import ToolFailed @agent.tool async def lookup_user(ctx, user_id: str) -> str: if not user_id.startswith('u_'): raise ToolFailed('user_id must start with u_; got: ' + user_id) return fetch_user(user_id)Enable prompt caching and parallel tool calls for a Mistral-backed agent to reduce latency and cost on repeated prompts.result = await agent.run( 'Summarize the threat landscape', model_settings={ 'mistral_prompt_cache_key': 'threat-landscape-v1', 'parallel_tool_calls': True, }, )Attach a stablerun_idto an agent run so downstream traces, logs, and UI adapters can correlate the same logical execution.result = await agent.run( 'Analyze this incident report', run_id='incident-2025-07-14-001', )- ›Adds
mistral_prompt_cache_keysetting and passesparallel_tool_callsto the Mistral SDK via model settings. - ›Adds
openai_moderationtoOpenAIChatModelSettingsand exposes Chat Completions moderation results inprovider_details. - ›Adds Google Model Armor support for Google Cloud via
GoogleModelSettings. - ›Adds optional
run_id=parameter to agent runs, durable wrappers, and UI adapters for correlating runs. - ›Adds
ToolFailedexception class for surfacing model-visible tool failures without triggering retries.
+1 moreshow less
- ›Adds
gemini-3.6-flashandgemini-3.5-flash-liteas supported model identifiers.
- ›Adds
- v2.16.0
PydanticAI v2.16.0 adds ToolFailed, run_id, Model Armor, Mistral cache keys, OpenAI moderation, and two new Gemini models.
└──▷ GET THIS VERSION$ git clone --branch v2.16.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.16.0
└──▷ USE ITSignal a non-retriable tool failure to the model without consuming retry budget.from pydantic_ai import Agent from pydantic_ai.exceptions import ToolFailed agent = Agent('openai:gpt-4o') @agent.tool_plain def fetch_record(record_id: str) -> str: if record_id == 'missing': raise ToolFailed('Record not found; try a different ID.') return f'Record {record_id}: active'Attach a stablerun_idto an agent run for correlation across logs and durable workflows.result = await agent.run('Summarise this document', run_id='run-2025-07-abc123')- ›Adds
mistral_prompt_cache_keysetting toMistralModelSettingsand passesparallel_tool_callsthrough to the Mistral SDK. - ›Hoists
openai_moderationintoOpenAIChatModelSettingsand exposes Chat Completions moderation results inprovider_details. - ›Adds Model Armor support for Google Cloud via
GoogleModelSettings. - ›Adds optional
run_id=parameter to agent runs, durable wrappers, and UI adapters for stable run identification. - ›Adds
ToolFailedexception class for signalling model-visible tool failures without triggering retries.
+1 moreshow less
- ›Adds
gemini-3.6-flashandgemini-3.5-flash-liteas supported model identifiers.
- ›Adds
- v2.15.0
PydanticAI v2.15.0 adds per-run tool-retry budget overrides, OpenAI moderation, and DynamicCapability toolset support in durable execution.
└──▷ GET THIS VERSION$ git clone --branch v2.15.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.15.0
└──▷ TRY ITCap tool retries for a single high-stakes run without changing the agent's default retry budget.$ result = await agent.run('Fetch and summarize the report', tool_retry_budget=2)Enable OpenAI Responses API moderation and inspect the result on the model response.result = await agent.run('Draft a message', model_settings={'openai_moderation': True}) print(result.all_messages()[-1].provider_details)- ›Adds
openai_moderationsetting to expose OpenAI Responses API moderation results inprovider_details. - ›Supports overriding the tool-retry budget at
run,iter, andoverridetime, giving per-invocation control over retry limits. - ›Supports
DynamicCapabilitytoolsets in durable execution, wrappingDynamicToolsetin DBOS steps and Prefect tasks. - ›Adds explicit prompt caching support for
gpt-5.6inOpenAIModel. - ›Inlines text-like files in
MistralModelprompts for cleaner multimodal input handling.
+1 moreshow less
- ›Introduces
ExaSearchcapability in Pydantic AI Harness as the successor to the Exa search common tools.
- ›Adds
- v2.15.0
PydanticAI v2.15.0 adds per-run tool-retry budget overrides, OpenAI moderation settings, and DynamicCapability support in durable execution.
└──▷ GET THIS VERSION$ git clone --branch v2.15.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.15.0
- ›Adds
openai_moderationsetting to expose OpenAI Responses API moderation results inprovider_details. - ›Supports overriding the tool-retry budget at
run,iter, andoverridetime. - ›Supports
DynamicCapabilitytoolsets in durable execution and wrapsDynamicToolsetin DBOS steps and Prefect tasks. - ›Adds
register_legacy_workflowsto DBOSDurability for clean DBOSAgent migration. - ›Supports explicit prompt caching for
gpt-5.6inopenaiprovider.
+2 moreshow less
- ›Inlines text-like files in
MistralModelprompts. - ›Adds
ExaSearchcapability in Pydantic AI Harness as the replacement for the deprecated Exa search common tools.
- ›Adds
- v2.14.0
PydanticAI v2.14.0 adds Mistral reasoning_effort support and three new durability capability classes.
└──▷ GET THIS VERSION$ git clone --branch v2.14.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.14.0
- ›Adds
reasoning_effortsupport to the Mistral provider via thinking settings, enabling control over model reasoning depth. - ›Adds
TemporalDurability, DBOSDurability, andPrefectDurabilitycapability classes to replace the deprecated durability wrapper agents.
- ›Adds
- v2.13.0
PydanticAI v2.13.0 adds instrumentation controls, content-filter error raising, cache-hit ratio tracking, and new capability hooks.
└──▷ GET THIS VERSION$ git clone --branch v2.13.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.13.0
└──▷ USE ITSuppress large span attributes in high-volume tracing pipelines by omittingmodel_request_parametersfrom OTel spans.from pydantic_ai.settings import InstrumentationSettings settings = InstrumentationSettings(include_model_request_parameters=False)
- ›Adds
include_model_request_parametersinstrumentation setting to control whether themodel_request_parametersspan attribute is included in traces. - ›Adds
RaiseContentFilterErrorcapability to raise an error when a non-empty content filter response is returned by the model. - ›Adds
cache_hit_ratioproperty toRequestUsageandRunUsagefor tracking cache efficiency across requests and runs. - ›Adds
get_model,resolve_model_id, andfor_agentcapability hooks for customising model resolution and agent binding.
- ›Adds
- v2.12.0
PydanticAI v2.12.0 adds Kimi-K3 model support and two new agent stream events for deferred tools and enqueued messages.
└──▷ GET THIS VERSION$ git clone --branch v2.12.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.12.0
└──▷ USE ITObserve deferred tool calls and their results while streaming an agent run, useful for auditing async/human-in-the-loop tool workflows.async with agent.run_stream(prompt) as stream: async for event in stream.stream_events(): if isinstance(event, DeferredToolCallEvent): print('Tool deferred:', event) elif isinstance(event, DeferredToolResultEvent): print('Deferred result received:', event) elif isinstance(event, EnqueuedMessagesEvent): print('Enqueued messages delivered:', event)- ›Adds
DeferredToolCallEventandDeferredToolResultEventtoAgentStreamEvent, enabling stream-level visibility into deferred tool call lifecycle. - ›Emits
EnqueuedMessagesEventwhen previously enqueued messages are delivered into a run, making message-replay observable in the event stream. - ›Adds Moonshot AI
kimi-k3model support.
- ›Adds
- v2.11.0
PydanticAI v2.11.0 exports
HistoryProcessorand adds actionable hints to usage-limit and tool-retry errors.└──▷ GET THIS VERSION$ git clone --branch v2.11.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.11.0
└──▷ USE ITImportHistoryProcessordirectly to build a custom history filter that trims old messages before each agent run.from pydantic_ai import HistoryProcessor
- ›Exports
HistoryProcessorfrom the public API, making it directly importable for custom conversation-history handling. - ›Adds actionable hint messages to usage-limit and tool-retry errors, surfacing guidance at the point of failure.
- ›Exports
- v2.10.0
PydanticAI v2.10.0 adds automatic message-history repair and OpenAI background mode plus Anthropic pause-turn support.
└──▷ GET THIS VERSION$ git clone --branch v2.10.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.10.0
- ›Supports OpenAI background mode and handles Anthropic
stop_reason=pause_turnin agent runs.
- ›Supports OpenAI background mode and handles Anthropic
- v2.9.0
PydanticAI v2.9.0 adds a
/usageCLI command, GPT-5.6 + reasoning mode support, andusage_limitsexposure onRunContext.└──▷ GET THIS VERSION$ git clone --branch v2.9.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.9.0
└──▷ USE ITInspect the active run's token limits inside a tool to short-circuit expensive work before hitting the cap.from pydantic_ai import Agent, RunContext agent = Agent('openai:gpt-4o') @agent.tool async def my_tool(ctx: RunContext[None]) -> str: limits = ctx.usage_limits if limits and limits.response_tokens_limit and limits.response_tokens_limit < 500: return 'Skipping — too close to token limit' return 'Proceeding with full response'Check cumulative token consumption mid-session in the clai interactive CLI.$ /usage- ›Exposes
usage_limitsonRunContextso tools and capabilities can inspect the current run's token/request limits at call time. - ›Adds
/usageslash command to theclaiCLI to display cumulative token usage across a session. - ›Adds GPT-5.6 models and reasoning mode support to the OpenAI provider.
- ›Exposes
- v2.8.0
PydanticAI v2.8.0 lets to_cli() accept a model override and bumps the bundled chat UI to 2.0.0.
└──▷ GET THIS VERSION$ git clone --branch v2.8.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.8.0
└──▷ USE ITRun a model-agnostic agent from the CLI by supplying the model at invocation time.agent.to_cli(model='openai:gpt-4o')
- ›Adds
modelparameter to to_cli() so agents defined without a model can have one supplied at CLI invocation time. - ›Bumps bundled chat UI to
2.0.0and targetssdk_version=7in Agent.to_web().
- ›Adds
- v2.7.0
PydanticAI v2.7.0 adds azure-responses shorthand and xAI grok-4.5 model support.
└──▷ GET THIS VERSION$ git clone --branch v2.7.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.7.0
└──▷ USE ITUse the azure-responses shorthand to target a specific Azure-hosted model without verbose configuration.model = 'azure-responses:gpt-4o'
- ›Supports
azure-responses:[model-id]shorthand for specifying Azure Responses API models. - ›Adds xAI
grok-4.5model support.
- ›Supports
- v2.6.0
PydanticAI v2.6.0 adds time-to-first-token tracking, file uploads to CodeExecutionTool, and new Bedrock model profiles.
└──▷ GET THIS VERSION$ git clone --branch v2.6.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.6.0
- ›Adds
filessupport toCodeExecutionToolfor Anthropic and OpenAI providers, enabling file uploads alongside code execution requests. - ›Records time-to-first-token for streaming model requests, exposing a new latency metric for streaming runs.
- ›Adds Bedrock model profiles for Writer, Z.AI, and Moonshot AI, and refreshes
LatestBedrockModelNameswith current model listings.
- ›Adds
- v2.5.0
PydanticAI v2.5.0 adds
sanitize_messagesfor message-history hardening and multimodal tool-return round-trips in AG-UI and Vercel AI adapters.└──▷ GET THIS VERSION$ git clone --branch v2.5.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.5.0
- ›Adds
sanitize_messagesfor inbound message-history hardening, closing a dangling-tool-call re-exposure on the Agent.to_ag_ui() / AGUIAdapter serving path. - ›Supports round-trip multimodal tool returns through the AG-UI and Vercel AI adapters, covering both history and streaming paths.
- ›Adds
- v2.4.0
PydanticAI v2.4.0 adds GEval, five agentic span evaluators, and splits file-upload security controls into two distinct parameters.
└──▷ GET THIS VERSION$ git clone --branch v2.4.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.4.0
- ›Splits
preserve_file_dataintoallow_uploaded_files(inbound security control) and a separate AG-UI representation opt-in parameter, giving finer-grained control over uploaded file handling. - ›Adds GEval evaluator and standard quality metric rubrics for LLMJudge, enabling criteria-driven LLM-as-judge scoring.
- ›Adds five agentic span-based evaluators —
ToolCorrectness,TrajectoryMatch,ArgumentCorrectness,MaxToolCalls, andMaxModelRequests— for evaluating agent execution traces.
└──▷ BREAKING ON UPGRADE- !The
preserve_file_dataparameter is split intoallow_uploaded_filesand an AG-UI opt-in; code referencingpreserve_file_datawill break on upgrade.
- ›Splits
- v2.3.0
PydanticAI v2.3.0 adds a native Z.AI (Zhipu AI) provider with thinking support.
└──▷ GET THIS VERSION$ git clone --branch v2.3.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.3.0
- ›Adds native Z.AI (Zhipu AI) provider with thinking support.
- v2.2.0
PydanticAI v2.2.0 adds Claude Sonnet 5 support, retry options for GoogleProvider, factory functions for Dataset.evaluate, and OpenRouter cost fields.
└──▷ GET THIS VERSION$ git clone --branch v2.2.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.2.0
└──▷ USE ITRun a dataset evaluation with a factory function as the lifecycle argument to get a fresh lifecycle object per run.await dataset.evaluate( task=my_task, lifecycle=lambda: MyEvalLifecycle(), )- ›Adds
retry_optionsparameter toGoogleProviderfor configurable retry behavior. - ›Adds
promptandcompletionscost fields to OpenRouter model responses. - ›Supports
claude-sonnet-5as a new model identifier for Anthropic Claude Sonnet 5. - ›Allows factory functions as the
lifecycleargument inDataset.evaluate, enabling dynamic lifecycle object creation per evaluation run. - ›Adds a TwelveLabs Pegasus video-understanding integration example.
- ›Adds
- v2.1.0
PydanticAI v2.1.0 adds Anthropic web tools with server-tool replay, TypeAdapter for EvaluatorContext, and improved instrumentation serialization.
└──▷ GET THIS VERSION$ git clone --branch v2.1.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.1.0
- ›Adds
TypeAdaptersupport forEvaluatorContext, enabling structured validation and serialization of evaluator context objects. - ›Adds Anthropic
_20260209web tools with server-tool replay support for the Anthropic provider. - ›Serializes instrumentation message attributes using
to_jsoninstead ofjson.dumpsfor more robust OpenTelemetry attribute handling.
- ›Adds
- v2.0.0
PydanticAI v2.0 stable: capabilities primitive, gemini-embedding-2, AG-UI deferred tools, and new model settings.
└──▷ GET THIS VERSION$ git clone --branch v2.0.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v2.0.0
- ›Adds
xai_max_turnstoXaiModelSettingsto cap the number of turns for xAI model runs. - ›Adds
gemini-embedding-2embedding model support. - ›Adds
google_tasktext-prefix conditioning forgemini-embedding-2embeddings to tune retrieval, classification, and other task types. - ›Maps AG-UI interrupts to
DeferredToolsin AGUIAdapter, enabling human-in-the-loop interrupt handling in AG-UI workflows. - ›Introduces V2 stable with capabilities as a core composable primitive, bundling an agent's tools, hooks, instructions, and model settings into a single unit.
+1 moreshow less
- ›Adds
cerebras_clear_thinkingsetting and emitsreasoning_effort='none'for Cerebras to suppress chain-of-thought output.
- ›Adds
- v1.107.0
PydanticAI v1.107.0 adds known_model_names(), OpenRouter prompt caching, and two new Claude model aliases.
└──▷ GET THIS VERSION$ git clone --branch v1.107.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.107.0
└──▷ USE ITDiscover every model name PydanticAI recognises without reading source — useful for validation or building model-picker UIs.from pydantic_ai import known_model_names for name in known_model_names(): print(name)- ›Adds known_model_names() function to programmatically enumerate all
KnownModelNamemembers at runtime. - ›Adds
CachePointand prompt caching support for OpenRouter models. - ›Adds
claude-fable-5andclaude-mythos-5as supported model name aliases.
- ›Adds known_model_names() function to programmatically enumerate all
- v1.106.0
PydanticAI v1.106.0 adds
api_host,timeout, andseedsupport toXaiProvider└──▷ GET THIS VERSION$ git clone --branch v1.106.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.106.0
└──▷ USE ITPoint xAI at a custom host and set a request timeout when initializing the provider.from pydantic_ai.providers.xai import XaiProvider provider = XaiProvider( api_host="https://my-xai-proxy.example.com", timeout=30, )Pin xAI model outputs to a fixed seed for reproducible results in evaluations or tests.from pydantic_ai.providers.xai import XaiProvider from pydantic_ai import Agent agent = Agent( model="xai:grok-3", model_settings={"seed": 42}, provider=XaiProvider(), )- ›Adds
api_hostandtimeoutparameters toXaiProvider, enabling custom endpoint and timeout configuration for xAI connections. - ›Maps the base
seedsetting to xAI viaXaiProvider, enabling reproducible xAI model outputs.
- ›Adds
- v1.105.0
PydanticAI v1.105.0 adds on-demand deferred loading for agent capabilities and Grok 4.3
reasoning_effortsupport.└──▷ GET THIS VERSION$ git clone --branch v1.105.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.105.0
- ›Adds
reasoning_effortsupport for Grok 4.3 via xAI model settings, along with updated current xAI model names. - ›Introduces on-demand (deferred loading) capabilities, allowing instructions, tools, model settings, and hooks to be loaded lazily at runtime.
- ›Adds
- v1.104.0
PydanticAI v1.104.0 adds Claude Opus 4.8 model support.
└──▷ GET THIS VERSION$ git clone --branch v1.104.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.104.0
- ›Adds support for Claude Opus 4.8 as a usable model.
- v1.103.0
PydanticAI v1.103.0 adds MCP prompt listing, Vercel timestamp round-tripping, and OpenRouter eager streaming support.
└──▷ GET THIS VERSION$ git clone --branch v1.103.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.103.0
└──▷ USE ITEnable eager input streaming when using Anthropic-compatible models via OpenRouter to reduce time-to-first-token.from pydantic_ai.models.openrouter import OpenRouterModel model = OpenRouterModel( 'anthropic/claude-3-5-sonnet', anthropic_eager_input_streaming=True, )- ›Adds
list_promptsandget_promptmethods toMcpServer, enabling MCP clients to discover and retrieve prompts from a server. - ›Supports
anthropic_eager_input_streaminginOpenRouterModel, bringing eager input streaming parity with the native Anthropic model. - ›Round-trips message timestamps through
VercelAIAdapter'sUIMessage.metadata, preserving original message timing across the adapter boundary.
- ›Adds
- v1.101.0
PydanticAI v1.101.0 adds a pending message queue, MCP background tasks, model-agnostic XSearch, and top_k support across three model providers.
└──▷ GET THIS VERSION$ git clone --branch v1.101.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.101.0
└──▷ USE ITInject a follow-up message into a running agent mid-execution using the new pending message queue.agent_run.enqueue("Please also summarize in bullet points.")- ›Adds
ctx.enqueueandagent_run.enqueuefor a pending message queue, enabling mid-run message injection into agent execution. - ›Adds
top_kmodel setting support toGoogleModel,AnthropicModel, andCohereModel. - ›Adds MCP background task support (SEP-1686) via the MCPServer integration.
- ›Makes XSearch capability model-agnostic through a subagent fallback, removing the previous model-specific constraint.
- ›Adds
- v1.100.0
PydanticAI v1.100.0 adds Bedrock native JSON output and strict tool calls support.
└──▷ GET THIS VERSION$ git clone --branch v1.100.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.100.0
- ›Adds support for Bedrock native JSON output and strict tool calls via the Bedrock integration.
- v1.99.0
PydanticAI v1.99.0 adds support for the
gemini-3.5-flashmodel.└──▷ GET THIS VERSION$ git clone --branch v1.99.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.99.0
- ›Adds
gemini-3.5-flashas a supported model.
- ›Adds
- v1.98.0
PydanticAI v1.98.0 adds OpenAI Responses token counting and a unified
retriesparameter on Agent.└──▷ GET THIS VERSION$ git clone --branch v1.98.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.98.0
└──▷ USE ITCount input tokens for an OpenAI Responses model request before committing to the API call.from pydantic_ai.models.openai import OpenAIResponsesModel model = OpenAIResponsesModel('gpt-4o') token_count = await model.count_tokens(messages, model_settings=None)- ›Adds
OpenAIResponsesModel.count_tokensmethod to count input tokens for OpenAI Responses model calls before sending them. - ›Replaces Agent parameters
tool_retries=andoutput_retries=with a singleretries: int | AgentRetriesparameter, enabling unified retry control across tools and outputs.
└──▷ BREAKING ON UPGRADE- !The Agent constructor parameters
tool_retries=andoutput_retries=are replaced byretries: int | AgentRetries; code passing either removed keyword argument will break on upgrade.
- ›Adds
- v1.97.0
PydanticAI v1.97.0 adds MCPToolset, OnlineEvaluator error opt-in, streaming state tracking, and splits GoogleProvider into two classes.
└──▷ GET THIS VERSION$ git clone --branch v1.97.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.97.0
└──▷ USE ITEvaluate agent calls that raised errors, not just successful completions, to catch failure-mode regressions.evaluator = OnlineEvaluator(run_on_errors=True)
- ›Adds
OnlineEvaluator.run_on_errorsflag to opt into running evaluations on failed (errored) agent calls, not just successful ones. - ›Adds MCPToolset (backed by
fastmcp-slim[client]) as the new MCP integration class, replacing the deprecated MCPServer* andFastMCPToolset. - ›Splits GoogleProvider(vertexai=True|False) into two separate classes:
GoogleProvider(formerlygoogle-gla:, now provider IDgoogle:) andGoogleCloudProvider(formerlygoogle-vertex:, now provider IDgoogle-cloud:). - ›Sets
ModelResponse.statetoincompletewhile a response is still streaming, enabling callers to distinguish in-progress from finished responses. - ›Promotes
pydantic_graph.betaAPI out of beta into the stable namespace.
+2 moreshow less
- ›Adds stream_response() (singular) as the replacement for stream_responses(); the new method yields
ModelResponsedirectly instead of a (ModelResponse, is_last) tuple. - ›Replaces the bundled
fasta2aA2A integration with an externalfasta2a.pydantic_aiadapter (requiresfasta2av0.6.1+), following DataLayer's adoption of the project.
└──▷ BREAKING ON UPGRADE- !The
google-gla:provider ID is renamed togoogle:andgoogle-vertex:is renamed togoogle-cloud:; old names are deprecated and will be removed in v2. - !stream_responses() is deprecated in favor of stream_response(); the new singular form yields
ModelResponseinstead of (ModelResponse, is_last), so any code unpacking the tuple will break when migrated. - !Agent.to_a2a() and the bundled
fasta2aintegration are deprecated; users must switch tofasta2a.pydantic_ai(requiresfasta2av0.6.1) from the external package. - !The
pydantic_graph.betamodule is deprecated; import paths that relied on the.betanamespace must be updated to the stable API.
- ›Adds
- v1.95.0
PydanticAI v1.95.0 adds native Tool Search on Anthropic/OpenAI, an Instrumentation capability class, and Gemini 3 structured-output + tool combinations.
└──▷ GET THIS VERSION$ git clone --branch v1.95.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.95.0
└──▷ USE ITRegister a native tool and instrumentation together using the newcapabilities=API instead of deprecated per-argument options.agent = Agent( 'openai:gpt-4o', capabilities=[NativeTool(...), Instrumentation(...)] )- ›Adds native Tool Search support for Anthropic and OpenAI providers, with custom search strategies available on any provider.
- ›Introduces the Instrumentation capability class; the existing Agent(instrument=...) parameter is now deprecated in favour of
capabilities=[Instrumentation(...)]. - ›Renames 'built-in tools' to 'native tools'; native tools are now registered via
capabilities=[NativeTool(...)]; old fields are deprecated ahead of v2. - ›Adds
local=opt-in parameter for provider-adaptive capability fallback; auto-fallback is deprecated. - ›Supports combining structured output and tool use together for Gemini 3 models via the Google provider.
- v1.94.0
PydanticAI v1.94.0 adds
openai_chat_supports_multiple_system_messagesprofile flag for OpenAI chat configuration.└──▷ GET THIS VERSION$ git clone --branch v1.94.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.94.0
- ›Adds
openai_chat_supports_multiple_system_messagesprofile flag to control whether multiple system messages are supported in OpenAI chat requests.
└──▷ BREAKING ON UPGRADE- !The
mistralaipackage is no longer installed as a dependency ofpydantic-ai; installations that relied on it being pulled in transitively must now declare it explicitly.
- ›Adds
- v1.93.0
PydanticAI v1.93.0 adds
tool_choicesetting and new output tool call events for structured agent control.└──▷ GET THIS VERSION$ git clone --branch v1.93.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.93.0
- ›Adds
tool_choicesetting to control which tool the model selects during agent runs. - ›Introduces
OutputToolCallEventandOutputToolResultEventstream events for output tool calls, replacing deprecated function-tool events for failing output tool calls.
- ›Adds
- v1.92.0
PydanticAI v1.92.0 adds Anthropic task budget support and a runtime
output_retriesoverride for agents.└──▷ GET THIS VERSION$ git clone --branch v1.92.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.92.0
- ›Adds runtime
output_retriesoverride on agent runs, allowing per-call control of output retry counts without reconfiguring the agent;retriesis now deprecated in favour ofoutput_retries. - ›Adds Anthropic task budget support, enabling token/compute budget constraints on Anthropic-backed agent calls.
- ›Adds runtime
- v1.91.0
PydanticAI v1.91.0 adds gpt-image-2 options for OpenAI and support for deepseek-v4-flash and deepseek-v4-pro models.
└──▷ GET THIS VERSION$ git clone --branch v1.91.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.91.0
- ›Supports
gpt-image-2model options via the OpenAI provider. - ›Adds
deepseek-v4-flashanddeepseek-v4-proto the DeepSeek provider.
- ›Supports
- v1.90.0
PydanticAI v1.90.0 adds OpenAI Conversations API state support and typed OTel metadata for tool call syntax highlighting.
└──▷ GET THIS VERSION$ git clone --branch v1.90.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.90.0
└──▷ USE ITResume a stateful OpenAI conversation across multiple agent calls by passing a stable conversation ID.settings = OpenAIResponsesModelSettings(openai_conversation_id='<your-conversation-id>') result = await agent.run('Follow-up question', model_settings=settings)- ›Adds
OpenAIResponsesModelSettings.openai_conversation_idto persist conversation state across turns using the OpenAI Conversations API. - ›Adds typed OpenTelemetry metadata for code tool call syntax highlighting, enabling richer tracing of tool invocations.
- ›Adds
- v1.89.1
PydanticAI v1.89.1 adds bundled Library Skills for improved coding-agent support.
└──▷ GET THIS VERSION$ git clone --branch v1.89.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.89.1
- ›Adds bundled Library Skills (library-skills.io) to improve coding-agent support and tool discovery.
- v1.89.0
PydanticAI v1.89.0 adds cross-run conversation correlation, dynamic model capabilities, and builtin-tool overrides.
└──▷ GET THIS VERSION$ git clone --branch v1.89.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.89.0
└──▷ USE ITDisable or replace builtin tools for a specific agent run, e.g. in tests or sandboxed environments.with agent.override(builtin_tools=[]): result = await agent.run('What time is it?')- ›Adds
conversation_idto enable cross-run correlation, linking multiple agent runs into a single logical conversation. - ›Adds
builtin_toolsparameter to agent.override(), allowing builtin tools to be overridden at runtime. - ›Supports dynamic model capabilities via callables in the capabilities list, enabling runtime-evaluated capability flags.
- ›Adds
- v1.88.0
PydanticAI v1.88.0 adds output validate/process hooks, cross-provider
service_tier, Anthropic fast mode, and new UI sanitization APIs.└──▷ GET THIS VERSION$ git clone --branch v1.88.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.88.0
└──▷ USE ITEnforce consistent service priority across providers without per-model configuration.from pydantic_ai import Agent agent = Agent( 'anthropic:claude-opus-4-6', model_settings={'service_tier': 'priority'}, ) result = agent.run_sync('Summarize this document.') print(result.output)- ›Adds
prepare_output_toolshook alongsideprepare_tools—prepare_toolsis now scoped to function tools only, while output validate/process hooks give fine-grained control over output tool execution. - ›Adds cross-provider
service_tiermodel setting with support for Anthropic, Gemini API, and Vertex Priority PayGo. - ›Adds
fastspeed mode for Anthropic Opus 4.6. - ›Adds
UIAdapter.sanitize_messagesandallowed_file_url_schemesto the UI adapter for controlling which file URL schemes are permitted in messages. - ›Supports OpenAI Responses
phasefield on assistant messages.
└──▷ BREAKING ON UPGRADE- !
prepare_toolsis now scoped to function tools only; callers relying on it to prepare output tools must migrate to the newprepare_output_toolshook.
- ›Adds
- v1.87.0
PydanticAI v1.87.0 adds deferred tool call handling, event stream processing capability, and GPT-5.5 thinking support.
└──▷ GET THIS VERSION$ git clone --branch v1.87.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.87.0
- ›Adds
HandleDeferredToolCallscapability andhandle_deferred_tool_callshook for handling deferred tool calls in agent workflows. - ›Adds
ProcessEventStreamcapability for processing event streams from model responses. - ›Supports the thinking setting for GPT-5.5 models.
- ›Adds
- v1.86.0
PydanticAI v1.86.0 adds
UIAdapter.manage_system_promptandReinjectSystemPromptfor dynamic system prompt control in UI adapters.└──▷ GET THIS VERSION$ git clone --branch v1.86.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.86.0
- ›Adds
UIAdapter.manage_system_promptmethod andReinjectSystemPromptcapability, enabling UI adapters to control and reinject system prompts at runtime.
- ›Adds
- v1.85.0
PydanticAI v1.85.0 adds online evaluation surfaced through OpenTelemetry events.
└──▷ GET THIS VERSION$ git clone --branch v1.85.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.85.0
- ›Adds online evaluation via OpenTelemetry events, enabling real-time assessment of agent runs as telemetry data.
- v1.84.0
PydanticAI v1.84.0 adds Claude Opus 4.7 support, stateful compaction for OpenAI, and a dedicated OllamaModel subclass.
└──▷ GET THIS VERSION$ git clone --branch v1.84.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.84.0
- ›Adds
OllamaModelsubclass with corrected Ollama capability flags, enabling reliable structured output on Ollama Cloud. - ›Adds stateful compaction mode to
OpenAICompactionfor managing conversation context across long runs. - ›Adds support for the Claude Opus 4.7 model.
- ›Adds
- v1.83.0
PydanticAI v1.83.0 adds xAI tool support, FastMCP metadata injection, Bedrock/Anthropic prompt caching, and a graceful parallel-tool end strategy.
└──▷ GET THIS VERSION$ git clone --branch v1.83.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.83.0
└──▷ USE ITUse the graceful end strategy so a parallel tool run completes in-flight calls before stopping, rather than cancelling abruptly.agent = Agent(model=model, end_strategy='graceful')
Declare an agent whose output may be a plain string or absent, avoiding a required structured-output wrapper.agent = Agent(model=model, output_type=str | None)
- ›Adds
XSearchToolandFileSearchsupport for the xAI provider. - ›Adds metadata injection per tool call via
FastMCPToolset. - ›Adds prompt cache TTL support for the Bedrock provider.
- ›Adds automatic prompt caching support for Anthropic.
- ›Adds a
'graceful'end strategy for parallel tool calls.
+1 moreshow less
- ›Supports Agent(output_type=str | None) for optional agent output.
- ›Adds
- v1.80.0
PydanticAI v1.80.0 adds capability ordering, hooks ordering, and server-side context compaction for OpenAI and Anthropic
└──▷ GET THIS VERSION$ git clone --branch v1.80.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.80.0
└──▷ USE ITUseOpenAICompactionto automatically compact context on the server side when approaching token limits with an OpenAI model.from pydantic_ai.capabilities import OpenAICompaction agent = Agent( 'openai:gpt-4o', capabilities=[OpenAICompaction()], )Declare that one capability must wrap another usingCapabilityOrderingto enforce a guaranteed composition order.from pydantic_ai.capabilities import CapabilityOrdering ordering = CapabilityOrdering(my_outer_capability, wraps=my_inner_capability)
- ›Adds
CapabilityOrderingwith relationship descriptorsinnermost,outermost,wraps,wrapped_by, andrequiresto control how capabilities compose and resolve ordering. - ›Adds an ordering parameter to Hooks and supports instance references in
wraps/wrapped_byfor finer control over hook execution order. - ›Adds
OpenAICompactionandAnthropicCompactioncapability classes to enable server-side context window compaction for those providers.
- ›Adds
- v1.79.0
PydanticAI v1.79.0 adds AG-UI 0.1.13/0.1.15 support, a new async HTTP client factory, and apply() on capability classes.
└──▷ GET THIS VERSION$ git clone --branch v1.79.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.79.0
└──▷ USE ITUsecreate_async_http_clientas a context manager to control the lifetime of the shared async HTTP client explicitly.from pydantic_ai.http import create_async_http_client async with create_async_http_client() as client: agent = MyAgent(http_client=client) result = await agent.run('Hello')- ›Adds
create_async_http_clientcontext manager to replace the internal HTTP client cache, giving callers explicit lifecycle control over async HTTP clients. - ›Adds apply() method to
AbstractCapability,CombinedCapability, andWrapperCapability, enabling capabilities to be applied directly. - ›Adds full AG-UI 0.1.13 and 0.1.15 support, including reasoning, multi-modal messaging, and
dump_messages.
- ›Adds
- v1.78.0
PydanticAI v1.78.0 adds
return_schema,function_signature, andSetToolMetadatatoToolDefinition, plus OTel cached token span attributes.└──▷ GET THIS VERSION$ git clone --branch v1.78.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.78.0
└──▷ USE ITInspect a tool's return schema and function signature at definition time to validate or log tool contracts.from pydantic_ai.tools import ToolDefinition def my_tool(x: int) -> str: return str(x) td = ToolDefinition( name='my_tool', description='Converts int to str', parameters_json_schema={}, return_schema=..., # new field function_signature=..., # new field ) print(td.return_schema) print(td.function_signature)- ›Adds
return_schemaandfunction_signaturefields toToolDefinition, exposing richer tool metadata for inspection and downstream use. - ›Adds
SetToolMetadatacapability, enabling dynamic mutation of tool metadata at runtime. - ›Adds cached token span attributes to OTel traces per the OpenTelemetry specification, improving observability of token usage.
- ›Adds
- v1.77.0
PydanticAI v1.77.0 adds a local WebFetch tool, deferred tool loading, a ThreadExecutor capability, and smart Anthropic/Bedrock instruction caching.
└──▷ GET THIS VERSION$ git clone --branch v1.77.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.77.0
└──▷ USE ITDefer tool loading so tools are only resolved at call time, enabling dynamic tool search before execution.from pydantic_ai import Agent from pydantic_ai.tools import Tool def my_tool_fn(ctx, query: str) -> str: return f'result for {query}' tool = Tool(my_tool_fn, defer_loading=True) agent = Agent('openai:gpt-4o', tools=[tool])Run an agent in a thread executor to avoid blocking the event loop when integrating with sync-heavy workloads.import asyncio from pydantic_ai import Agent agent = Agent('anthropic:claude-sonnet-4-5') async def main(): async with agent.using_thread_executor(): result = await agent.run('Summarize this document.') print(result.output) asyncio.run(main())- ›Adds
defer_loadingparameter to tools and toolsets, enabling lazy/deferred tool loading to support tool search workflows. - ›Adds Agent.using_thread_executor() method and a
ThreadExecutorcapability for running agents in thread executors. - ›Adds a local
WebFetchtool that activates automatically when a provider lacks built-in web-fetch support, extendingWebFetchcapability to more providers. - ›Adds smart instruction caching for Anthropic and Bedrock providers — automatically inserts a cache boundary at the static/dynamic instruction split.
- ›Adds support for
server_message_idinVercelAIEventStream.
- ›Adds
- v1.76.0
PydanticAI v1.76.0 adds agent self-reference in RunContext and automatic image-generation fallback via subagent.
└──▷ GET THIS VERSION$ git clone --branch v1.76.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.76.0
└──▷ USE ITAccess the running agent from inside a tool viaRunContext.agent— useful for dynamic dispatch or introspection without globals.@agent.tool async def my_tool(ctx: RunContext[MyDeps]) -> str: current_agent = ctx.agent # newly available in v1.76.0 return f"Running as: {current_agent.name}"- ›Adds
agentattribute toRunContext, giving tools and callbacks direct access to the running agent instance. - ›Adds automatic fallback for
ImageGeneration: when the main model lacks image-generation capability, PydanticAI transparently delegates to a subagent running a dedicated imagegen model. - ›Updates the Mistral integration to support mistralai SDK v2.
- ›Adds
- v1.75.0
PydanticAI v1.75.0 adds Gemini embedding types/limits and Flex PayGo support for Vertex AI.
└──▷ GET THIS VERSION$ git clone --branch v1.75.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.75.0
- ›Adds types and limits for
gemini-embedding-2-previewin the embeddings module. - ›Implements support for Flex PayGo billing mode with the Vertex AI provider.
- ›Adds types and limits for
- v1.74.0
PydanticAI v1.74.0 adds online evaluation infrastructure,
TextContentmetadata, time-sortable run IDs, and MCP Server instructions support.└──▷ GET THIS VERSION$ git clone --branch v1.74.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.74.0
└──▷ USE ITAttach invisible metadata to a user prompt — useful for tagging messages with session or request context without leaking it to the model.from pydantic_ai.messages import TextContent prompt = TextContent(text='Summarize this document.', metadata={'session_id': 'abc123', 'user_tier': 'pro'}) result = await agent.run([prompt])- ›Adds
AbstractToolset.get_instructionsmethod andinclude_instructionsargument to MCP Servers, enabling toolsets to surface dynamic instructions to agents. - ›Adds
TextContentclass for user prompts, supporting ametadatafield that is attached to the content object but not sent to the model. - ›Introduces online evaluation infrastructure for
pydantic-evals, enabling live/online evaluation workflows. - ›Makes agent run IDs time-sortable and propagates agent name and run ID as span attributes on all agent run child spans, improving observability.
- ›Adds
- v1.73.0
PydanticAI v1.73.0 adds CaseLifecycle hooks to Dataset.evaluate and lets hooks swap models or trigger retries.
└──▷ GET THIS VERSION$ git clone --branch v1.73.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.73.0
└──▷ USE ITRetry a model request from within a hook when a validation condition is not met.from pydantic_ai import ModelRetry def after_request(ctx): if not response_is_valid(ctx.response): raise ModelRetry('Response failed validation, retrying')- ›Adds
CaseLifecyclehooks toDataset.evaluatefor lifecycle callbacks around each evaluation case. - ›Allows before/wrap model request hooks to swap the active model via
ModelRequestContext. - ›Allows hooks to raise
ModelRetryto control retry flow from within hook logic.
- ›Adds
- v1.72.0
PydanticAI v1.72.0 adds Anthropic eager input streaming, sync tool prep functions, and implicit MCP URLs
└──▷ GET THIS VERSION$ git clone --branch v1.72.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.72.0
└──▷ USE ITEnable eager input streaming for an Anthropic model when you want streamed responses to begin as soon as input is ready.from pydantic_ai.models.anthropic import AnthropicModelSettings settings = AnthropicModelSettings(anthropic_eager_input_streaming=True)
- ›Adds
anthropic_eager_input_streamingtoAnthropicModelSettingsto control eager streaming behaviour for Anthropic models. - ›Supports synchronous tool preparation functions alongside existing async ones, removing the requirement to define
async deffor tool prep. - ›Removes the requirement to specify an explicit
url=argument on theMCPcapability, both in Python and inAgentSpecconfiguration.
- ›Adds
- v1.71.0
PydanticAI v1.71.0 adds Capabilities, AgentSpec, Hooks, Thinking, provider-adaptive tools, and two new OpenAI models.
└──▷ GET THIS VERSION$ git clone --branch v1.71.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.71.0
└──▷ USE ITLoad a fully-configured agent from a YAML file with templated instructions referencing runtime deps.from pydantic_ai import Agent agent = Agent.from_file('my_agent.yaml')Isolate toolset state per run so concurrent agent calls do not share mutable tool state.class MyToolset(AbstractToolset): async def for_run(self, ctx): return MyToolset(session=ctx.deps.session) agent = Agent('openai:gpt-5.4-nano', toolsets=[MyToolset()])- ›Adds
Agent.from_filefor loading agents from YAML/JSON files, with templated instructions that reference deps viaTemplateStr. - ›Adds
AbstractToolset.for_runandfor_run_stepmethods for per-run and per-step state isolation in toolsets. - ›Adds Capabilities: composable, reusable units of agent behavior that bundle tools, lifecycle hooks, instructions, and model settings into a single class pluggable into any agent.
- ›Adds
AgentSpecfor declarative agent definitions loadable from YAML/JSON. - ›Adds Hooks capability for defining lifecycle hooks using decorators.
+3 moreshow less
- ›Adds Thinking capability and a cross-provider
thinkingmodel setting. - ›Adds provider-adaptive tool capabilities
WebSearch,WebFetch,MCP, andImageGenerationthat automatically fall back from builtin (provider) tools to local tools. - ›Adds
openai:gpt-5.4-miniandopenai:gpt-5.4-nanomodel identifiers.
- ›Adds
- v1.70.0
PydanticAI v1.70.0 adds
bedrock_inference_profileto Bedrock model and embedding settings.└──▷ GET THIS VERSION$ git clone --branch v1.70.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.70.0
└──▷ USE ITRoute Bedrock LLM calls through a specific inference profile, e.g. a cross-region profile, without changing your agent logic.from pydantic_ai.models.bedrock import BedrockModelSettings settings = BedrockModelSettings( bedrock_inference_profile="us.anthropic.claude-3-5-sonnet-20241022-v2:0" ) agent = Agent("bedrock:anthropic.claude-3-5-sonnet-20241022-v2:0", model_settings=settings)- ›Adds
bedrock_inference_profilefield toBedrockModelSettingsandBedrockEmbeddingSettings, enabling inference profile selection for AWS Bedrock model and embedding calls.
- ›Adds
- v1.69.0
PydanticAI v1.69.0 adds agent descriptions for tracing, multimodal tool results, and response-based FallbackModel support.
└──▷ GET THIS VERSION$ git clone --branch v1.69.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.69.0
└──▷ USE ITAttach a human-readable description to an agent so tracing spans carry meaningful context in your observability backend.agent = Agent(model='openai:gpt-4o', description='Summarises customer support tickets and routes to the correct team')
- ›Adds response-based fallback support to
FallbackModel, enabling fallback logic driven by the model response rather than only on errors. - ›Sends multimodal tool results to APIs directly as a single part instead of splitting them into user parts.
- ›Adds response-based fallback support to
- v1.67.0
PydanticAI v1.67.0 adds GPT-5.4 support, WebSearchTool for OpenRouter, a Tavily search overhaul, and native structured output for Ollama.
└──▷ GET THIS VERSION$ git clone --branch v1.67.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.67.0
- ›Supports
WebSearchToolforOpenRouterModelvia OpenRouter plugins, enabling web search through the OpenRouter provider. - ›Enables native structured output support for the Ollama provider.
- ›Adds GPT-5.4 model support.
- ›Rehauled
TavilySearchToolwith updated internals and capabilities.
- ›Supports
- v1.66.0
PydanticAI v1.66.0 adds native structured output for Qwen 3.5 models and support for the Gemini image-preview model.
└──▷ GET THIS VERSION$ git clone --branch v1.66.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.66.0
- ›Enables native structured output for Qwen 3.5 models.
- ›Adds support for
gemini-3.1-flash-image-preview(Nano Banana 2) as a supported model.
- v1.65.0
PydanticAI v1.65.0 adds provider-uploaded file support via
UploadedFileand thegemini-3.1-flash-lite-previewmodel.└──▷ GET THIS VERSION$ git clone --branch v1.65.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.65.0
- ›Adds
UploadedFileobject to support files uploaded directly to providers, enabling agents to work with provider-hosted file references. - ›Adds
gemini-3.1-flash-lite-previewas a supported model identifier.
- ›Adds
- v1.64.0
PydanticAI v1.64.0 adds
template=FalseonPromptedOutputandNativeOutputto suppress schema prompts.└──▷ GET THIS VERSION$ git clone --branch v1.64.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.64.0
└──▷ USE ITSuppress the auto-generated schema prompt on a structured output when you are supplying your own formatting instructions.from pydantic_ai import PromptedOutput output = PromptedOutput(MyModel, template=False)
- ›Adds
template=Falseparameter toPromptedOutputandNativeOutputto disable automatic schema prompt injection when you want full control over the model prompt.
- ›Adds
- v1.63.0
PydanticAI v1.63.0 adds
args_validatorfor tools, Gemini 2.5 Pro Preview support, and Gemini logprob output.└──▷ GET THIS VERSION$ git clone --branch v1.63.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.63.0
- ›Adds
args_validatorparameter to tool definitions for pre-execution argument validation before a tool runs. - ›Adds logprob support for Gemini models.
- ›Adds
- v1.62.0
PydanticAI v1.62.0 adds tool approval for Vercel AI, plus LinePlot, ROCAUCEvaluator, and KolmogorovSmirnovEvaluator.
└──▷ GET THIS VERSION$ git clone --branch v1.62.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.62.0
- ›Adds
LinePlotanalysis type, ROCAUCEvaluator, andKolmogorovSmirnovEvaluatorfor evaluating model outputs with statistical analysis. - ›Adds tool approval integration for the Vercel AI adapter, enabling human-in-the-loop approval flows for tool calls.
- ›Adds
- v1.61.0
PydanticAI v1.61.0 adds Python 3.14 support and Claude Sonnet 4.6 via updated Anthropic SDK.
└──▷ GET THIS VERSION$ git clone --branch v1.61.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.61.0
- ›Supports Python 3.14.
- ›Adds Claude Sonnet 4.6 model availability via Anthropic SDK upgrade to 0.80.0.
- v1.60.0
PydanticAI v1.60.0 adds video URL support to OpenRouterModel and upgrades OTel instrumentation for multimodal input.
└──▷ GET THIS VERSION$ git clone --branch v1.60.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.60.0
- ›Adds
video_urlsupport toOpenRouterModel, enabling video content to be passed as multimodal input through OpenRouter. - ›Upgrades instrumentation to version 4 to align with OTel GenAI semantic conventions for multimodal input.
- ›Adds
- v1.59.0
PydanticAI v1.59.0 adds Model.model_id, aggregated usage flag, BaseModel support in Contains, and Vercel AI metadata injection
└──▷ GET THIS VERSION$ git clone --branch v1.59.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.59.0
└──▷ USE ITInspect which provider and model a configured agent is using at runtime, without string-parsing.print(model.model_id) # e.g. 'openai:gpt-4o'
- ›Adds
Model.model_idproperty that returns the model identifier inprovider:modelformat. - ›Adds opt-in flag for aggregated usage attribute names.
- ›Enhances Contains evaluator to support
pydantic.BaseModelinstances as expected values. - ›Allows
BaseChunks to be injected into the Vercel AI adapter throughToolReturnPart.metadata.
- ›Adds
- v1.58.0
PydanticAI v1.58.0 adds report-level evaluators, multi-run aggregation, and extra_headers for Google provider
└──▷ GET THIS VERSION$ git clone --branch v1.58.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.58.0
└──▷ USE ITPass custom headers (e.g. for tracing or billing) when using the Google model provider.from pydantic_ai.models.google import GoogleModel model = GoogleModel('gemini-2.0-flash', extra_headers={'X-My-Trace-Id': 'abc123'})Re-run each evaluation case multiple times and aggregate results to reduce variance in LLM scoring.from pydantic_evals import Dataset results = await dataset.evaluate(pipeline, repeat=5)
- ›Adds
extra_headerssupport to the Google model provider, enabling custom HTTP headers on requests. - ›Adds a
repeatparameter to pydantic-evals for multi-run aggregation, enabling statistical analysis across repeated experiment runs. - ›Introduces report-level evaluators and experiment-wide analyses to pydantic-evals, enabling summary metrics across all cases in an evaluation run.
- ›Adds
- v1.56.0
PydanticAI v1.56.0 adds Claude Opus 4.6 support, adaptive thinking, and new Anthropic model settings fields.
└──▷ GET THIS VERSION$ git clone --branch v1.56.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.56.0
└──▷ USE ITEnable adaptive extended thinking on a Claude Opus 4.6 call to let the model self-determine reasoning depth.from pydantic_ai import Agent from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings agent = Agent( AnthropicModel('claude-opus-4-6'), model_settings=AnthropicModelSettings( anthropic_effort='auto', anthropic_thinking={'type': 'adaptive'} ) ) result = agent.run_sync('Explain quantum entanglement.') print(result.output)Opt into an Anthropic beta feature (e.g. a preview API) on a per-agent basis usinganthropic_betas.from pydantic_ai import Agent from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings agent = Agent( AnthropicModel('claude-opus-4-6'), model_settings=AnthropicModelSettings( anthropic_betas=['interleaved-thinking-2025-05-14'] ) ) result = agent.run_sync('Draft a threat model for a SaaS API.') print(result.output)- ›Adds
anthropic_effortandanthropic_thinking.type='adaptive'to Anthropic model settings, enabling adaptive extended thinking for Claude models. - ›Adds
anthropic_betasfield toAnthropicModelSettings, allowing opt-in to Anthropic beta features per request. - ›Adds support for Claude Opus 4.6 as a new model option.
- ›Adds
- v1.54.0
PydanticAI v1.54.0 adds concurrency limiting for Agents and Models
└──▷ GET THIS VERSION$ git clone --branch v1.54.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.54.0
- ›Adds concurrency limiting for Agents and Models to cap parallel executions and prevent resource exhaustion.
- v1.53.0
PydanticAI v1.53.0 automatically infers the gateway base URL from the token region.
└──▷ GET THIS VERSION$ git clone --branch v1.53.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.53.0
- ›Automatically infers the gateway base URL from the token region, removing the need to manually specify it.
- v1.52.0
PydanticAI v1.52.0 adds OpenAI data-retention control, retry counts in run context, and reasoning-content passthrough.
└──▷ GET THIS VERSION$ git clone --branch v1.52.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.52.0
└──▷ USE ITDisable OpenAI data retention for a model when handling sensitive workloads.from pydantic_ai.models.openai import OpenAIChatModel model = OpenAIChatModel('gpt-4o', openai_store=False)- ›Adds
openai_storesetting toOpenAIChatModelto control whether OpenAI retains request/response data. - ›Exposes the number of output-validation retries in the agent's run context, making retry count available to tool and result handlers.
- ›Makes
OpenAIChatModelreturn reasoning content via the same field it was received in, preserving round-trip fidelity of reasoning tokens.
- ›Adds
- v1.51.0
PydanticAI v1.51.0 adds
html_sourceparameter to customize the Chat UI source.└──▷ GET THIS VERSION$ git clone --branch v1.51.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.51.0
- ›Adds
html_sourceparameter to the Chat UI to allow customization of the HTML source rendered by the chat interface.
- ›Adds
- v1.50.0
PydanticAI v1.50.0 exposes usage limits and model settings to CLI users and adds OpenAI raw text annotation access.
└──▷ GET THIS VERSION$ git clone --branch v1.50.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.50.0
- ›Adds
usage_limitsandmodel_settingsparameters accessible to users running agents with to_cli(), enabling runtime control of limits and settings from the command line. - ›Adds a setting to include OpenAI raw text annotations in
TextPart.provider_details, surfacing provider-level annotation data to callers.
- ›Adds
- v1.49.0
PydanticAI v1.49.0 adds BedrockEmbeddingModel for Nova/Cohere/Titan and parallel tool calls in DBOSAgent.
└──▷ GET THIS VERSION$ git clone --branch v1.49.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.49.0
└──▷ USE ITGenerate embeddings via AWS Bedrock's Nova, Cohere, or Titan endpoints using the newBedrockEmbeddingModel.from pydantic_ai.models.bedrock import BedrockEmbeddingModel model = BedrockEmbeddingModel('amazon.nova-lite-v1') result = await model.embed(['Hello, world!'])- ›Adds
BedrockEmbeddingModelclass supporting AWS Bedrock embedding endpoints for Nova, Cohere, and Titan models. - ›Enables parallel tool call execution in DBOSAgent.
- ›Updates Vercel AI SDK type definitions to match AI SDK v6.
- ›Adds
- v1.48.0
PydanticAI v1.48.0 adds domain allowlisting for WebSearchTool, continuous usage stats for OpenAI, and model_settings support for Mistral streaming.
└──▷ GET THIS VERSION$ git clone --branch v1.48.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.48.0
└──▷ USE ITRestrict an OpenAI web search agent to only retrieve results from trusted domains, reducing noise from untrusted sources.from pydantic_ai.tools.web_search import WebSearchTool tool = WebSearchTool(allowed_domains=["example.com", "docs.openai.com"])
Enable per-chunk token accounting during OpenAI streaming to monitor costs in real time.from pydantic_ai import Agent agent = Agent( "openai:gpt-4o", model_settings={"continuous_usage_stats": True}, )- ›Adds
allowed_domainsparameter toWebSearchToolto restrict OpenAI web searches to specific domains. - ›Adds
continuous_usage_statsmodel setting for OpenAI to receive token usage statistics on every streamed chunk. - ›Applies
model_settingsto Mistral streaming JSON mode, enabling per-request model configuration during Mistral streaming.
- ›Adds
- v1.47.0
PydanticAI v1.47.0 preserves thought signatures and provider metadata through Vercel AI frontend round trips.
└──▷ GET THIS VERSION$ git clone --branch v1.47.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.47.0
- ›Thought signatures and other provider metadata now survive a round trip through a Vercel AI frontend.
- v1.46.0
PydanticAI v1.46.0 adds a native xAI SDK model class, replacing the OpenAI-compatible Grok provider.
└──▷ GET THIS VERSION$ git clone --branch v1.46.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.46.0
- ›Adds
XaiModelclass that integrates with the xAI SDK natively, replacing the deprecatedGrokProviderwhich relied on the OpenAI-compatible API.
└──▷ BREAKING ON UPGRADE- !
GrokProvideris deprecated; callers should migrate toXaiModelwhich uses the xAI SDK directly.
- ›Adds
- v1.45.0
PydanticAI v1.45.0 adds VoyageAI embeddings support.
└──▷ GET THIS VERSION$ git clone --branch v1.45.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.45.0
- ›Adds VoyageAI embeddings support as a new integration.
- v1.44.0
PydanticAI v1.44.0 adds Exa search tools integration and AWS Bedrock Nova 2.0 Code Interpreter support.
└──▷ GET THIS VERSION$ git clone --branch v1.44.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.44.0
- ›Adds Exa search tools integration, enabling agents to perform web search via the Exa API as a built-in tool.
- ›Adds support for the AWS Bedrock Nova 2.0 built-in Code Interpreter tool, allowing agents backed by Bedrock Nova 2.0 to execute code natively.
- v1.43.0
PydanticAI v1.43.0 adds support for Google embedding models.
└──▷ GET THIS VERSION$ git clone --branch v1.43.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.43.0
- ›Supports Google embedding models, enabling text embedding workflows via the Google provider.
- v1.42.0
PydanticAI v1.42.0 adds SambaNova provider, ContentFilterError for empty responses, and OTel GenAI semantic attributes.
└──▷ GET THIS VERSION$ git clone --branch v1.42.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.42.0
└──▷ USE ITCatch content-filter rejections explicitly instead of handling empty or opaque responses.from pydantic_ai.exceptions import ContentFilterError try: result = await agent.run('Generate something sensitive') except ContentFilterError as e: print(f'Model blocked the response: {e}')- ›Raises
ContentFilterErrorconsistently when a model returns an empty response due to a content filter, giving callers a typed exception to catch. - ›Adds SambaNova as a supported provider.
- ›Adds OpenTelemetry GenAI semantic convention attributes to telemetry output.
- ›Raises
- v1.41.0
PydanticAI v1.41.0 adds YAML/TOML media type support in BinaryContent and metadata for DeferredToolResults.
└──▷ GET THIS VERSION$ git clone --branch v1.41.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.41.0
└──▷ USE ITLoad a YAML file as binary content to pass structured data directly into an agent.BinaryContent.from_path('config.yaml')- ›Adds YAML and TOML media type support to
BinaryContent.from_path, enabling those file types to be loaded as binary content. - ›Adds
metadatasupport forDeferredToolResults, allowing metadata to be attached to deferred tool result objects.
- ›Adds YAML and TOML media type support to
- v1.40.0
PydanticAI v1.40.0 adds human-readable Temporal activity summaries and configurable retries for nonexistent tool calls.
└──▷ GET THIS VERSION$ git clone --branch v1.40.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.40.0
- ›Agents now retry calls to nonexistent tools up to the Agent
retrieslimit, matching the existing retry behavior for real tools. - ›Sets human-readable activity summaries for Temporal activities, improving observability in Temporal-based agent workflows.
- ›Agents now retry calls to nonexistent tools up to the Agent
- v1.39.0
PydanticAI v1.39.0 adds embedding model support, agent run metadata on results and spans, and a new BedrockModelSettings tier field.
└──▷ GET THIS VERSION$ git clone --branch v1.39.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.39.0
└──▷ USE ITSet a specific AWS Bedrock service tier on a model to control throughput or priority for an agent run.from pydantic_ai.models.bedrock import BedrockModelSettings settings = BedrockModelSettings(bedrock_service_tier='standard') result = await agent.run('Summarize this document', model_settings=settings)- ›Adds
bedrock_service_tiersetting toBedrockModelSettingsfor controlling AWS Bedrock service tier per agent run. - ›Adds agent and agent run metadata, exposed on result objects and OpenTelemetry span attributes.
- ›Introduces embedding model support via new embedding model classes and APIs.
- ›Supports
ThinkingPartin MCP Sampling, enabling reasoning-aware model responses over the Model Context Protocol. - ›Allows system prompt functions to return None, treating it as a no-op rather than an error.
- ›Adds
- v1.38.0
PydanticAI v1.38.0 adds local timestamps to request/response models and typed RunContext support in TextOutput signatures.
└──▷ GET THIS VERSION$ git clone --branch v1.38.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.38.0
- ›Adds typed
RunContext[Deps]support inTextOutputfunction signatures, enabling dependency-injected output handlers. - ›Adds local timestamps to request and response models, with provider timestamps surfaced in
provider_details. - ›Supports
VideoUrl.vendor_metadatafor GCS URIs on the Google Vertex provider.
- ›Adds typed
- v1.37.0
PydanticAI v1.37.0 adds runtime model switching and DynamicToolset for TemporalAgent, plus Vertex AI image output controls.
└──▷ GET THIS VERSION$ git clone --branch v1.37.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.37.0
└──▷ USE ITControl image output format and compression when generating images with a Vertex AI Gemini model.ImageGenerationTool(output_format='jpeg', output_compression=80)
- ›Adds
output_compressionandoutput_formatparameters toImageGenerationToolfor Vertex AI Gemini image models. - ›Enables
TemporalAgentto switch model atagent.run-time, allowing per-run model selection. - ›Adds
DynamicToolsetsupport in Temporal, enabling runtime-defined tool sets for Temporal workflows. - ›Adds a model profile flag for APIs that support native output but still require JSON schema in instructions.
- ›Updates known Groq model names to add production/preview variants and remove deprecated entries.
+1 moreshow less
- ›Sets a configurable message on
ToolRetryErrorfor clearer retry error reporting.
- ›Adds
- v1.35.0
PydanticAI v1.35.0 adds FileSearchTool, DashScopeProvider, AG-UI multimodal messages, and Gemini 3 Flash support.
└──▷ GET THIS VERSION$ git clone --branch v1.35.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.35.0
- ›Adds
FileSearchToolclass with support for OpenAI and Google backends, enabling file-search capabilities within PydanticAI agents. - ›Adds
DashScopeProviderfor Alibaba Cloud, plus audio input support for Qwen Omni models. - ›Adds
sizeparameter toImageGenerationToolfor Gemini image models, controlling generated image dimensions. - ›Supports OpenAI reasoning summary option
'auto'for reasoning-capable models. - ›Adds Gemini 3 Flash model support.
+2 moreshow less
- ›Supports AG-UI multi-modal messages, enabling richer message types in AG-UI integrations.
- ›Sets timestamps on AG-UI events for improved event traceability.
- ›Adds
- v1.34.0
PydanticAI v1.34.0 adds a Web Chat UI launchable via
clai webor Agent.to_web(), plusFileUrl.force_downloadsupport for Anthropic and OpenAI Responses models.└──▷ GET THIS VERSION$ git clone --branch v1.34.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.34.0
└──▷ TRY ITQuickly spin up an interactive web chat interface for an existing agent without writing a frontend.$ clai webProgrammatically launch the Web Chat UI from within Python for a configured agent.from pydantic_ai import Agent agent = Agent('openai:gpt-4o', system_prompt='You are a helpful assistant.') agent.to_web()- ›Adds
clai webCLI command and Agent.to_web() method to launch a Web Chat UI for any agent. - ›Supports
FileUrl.force_downloadinAnthropicModelandOpenAIResponsesModelfor forced file downloads. - ›Makes
OpenRouterProviderandDeepSeekProvider__init__overloads less restrictive, broadening valid initialization patterns.
- ›Adds
- v1.33.0
PydanticAI v1.33.0 adds native s3:// URL support in BedrockConverseModel and broadens instructions support across models.
└──▷ GET THIS VERSION$ git clone --branch v1.33.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.33.0
- ›Passes
s3://file URLs directly to the API inBedrockConverseModel, enabling S3-hosted files to be referenced without pre-fetching. - ›Inserts agent
instructionsaftersystem_prompts for models that don't natively support instructions, broadening the operational surface of theinstructionsfield across providers.
- ›Passes
- v1.32.0
PydanticAI v1.32.0 adds tool timeouts, multi-agent Temporal workflow registration, and OTel log-based observability.
└──▷ GET THIS VERSION$ git clone --branch v1.32.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.32.0
└──▷ USE ITRegister multiple TemporalAgents to a single Temporal workflow so the worker can discover and run them.class MyWorkflow: __pydantic_ai_agents__ = [research_agent, summary_agent] async def run(self) -> str: ...- ›Adds tool timeout support, allowing individual tools to be given a maximum execution duration.
- ›Allows
TemporalAgents to be registered to a Temporal workflow via the__pydantic_ai_agents__field on a workflow class. - ›Extends
end_strategyto apply to output tools in addition to regular tools, giving consistent early-exit behaviour across both tool types. - ›Replaces OpenTelemetry events with OTel logs for agent observability, aligning with the OTel logging data model.
└──▷ BREAKING ON UPGRADE- !OTel events emitted by PydanticAI are replaced with OTel logs; any pipeline or backend that consumes the old event format will no longer receive those signals.
- v1.31.0
PydanticAI v1.31.0 adds prompt caching for AWS Bedrock, Agent.output_json_schema(), custom MCP clientInfo, and GPT-5.2 support.
└──▷ GET THIS VERSION$ git clone --branch v1.31.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.31.0
└──▷ USE ITRetrieve the JSON schema for an agent's structured output to validate or document the expected response shape.from pydantic_ai import Agent from pydantic import BaseModel class Answer(BaseModel): summary: str confidence: float agent = Agent('openai:gpt-4o', output_type=Answer) print(agent.output_json_schema())Use a plain model name string in LLMJudge instead of a model object, for quick evaluation scripting.from pydantic_ai.evaluate import LLMJudge judge = LLMJudge(model='openai:gpt-4o') result = await judge.evaluate(question='Is Paris the capital of France?', answer='Yes') print(result)
- ›Adds Agent.output_json_schema() method to retrieve the JSON schema for an agent's output type programmatically.
- ›Adds
provider_urlfield toModelResponse, used by cost() to route cost calculations correctly across providers. - ›Adds prompt caching support for AWS Bedrock, reducing latency and token costs on repeated prompts.
- ›Allows custom
clientInfowhen connecting to MCP servers, enabling clients to self-identify to MCP endpoints. - ›Allows model to be passed as a plain string in LLMJudge, simplifying evaluation setup.
+1 moreshow less
- ›Adds support for GPT-5.2 and bumps the OpenAI dependency to v2.11.0.
- v1.30.0
PydanticAI v1.30.0 adds CerebrasModel, prompt caching options for OpenAI, and multi-modal output in LLMJudge.
└──▷ GET THIS VERSION$ git clone --branch v1.30.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.30.0
- ›Adds
CerebrasModelas a new supported LLM provider integration. - ›Adds prompt caching options to
OpenAIChatModelSettingsfor controlling OpenAI prompt cache behavior. - ›Supports multi-modal output in LLMJudge evaluations.
- ›Adds
- v1.29.0
PydanticAI v1.29.0 adds aspect ratio support for Gemini image generation and passes
container_idto the Anthropic API.└──▷ GET THIS VERSION$ git clone --branch v1.29.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.29.0
- ›Passes
container_idback to the Anthropic API, enabling container-scoped tool interactions. - ›Adds aspect ratio support for Gemini image generation.
- ›Removes the requirement for the
anthropicdependency when using an Anthropic model through a third-party provider.
- ›Passes
- v1.28.0
PydanticAI v1.28.0 adds structured output for claude-haiku-4-5 and multi-character Bedrock geo-prefix support.
└──▷ GET THIS VERSION$ git clone --branch v1.28.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.28.0
- ›Adds native structured output support for
claude-haiku-4-5. - ›Supports
us-gov.and other multi-character AWS Bedrock geo prefixes.
- ›Adds native structured output support for
- v1.27.0
PydanticAI v1.27.0 adds dynamic built-in tool config via RunContext, MCP tool/resource caching, CoT reasoning support, and VercelAIAdapter message conversion.
└──▷ GET THIS VERSION$ git clone --branch v1.27.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.27.0
└──▷ USE ITConvert a PydanticAI conversation history to Vercel AI message format for streaming to a Next.js frontend.from pydantic_ai.adapters.vercel import VercelAIAdapter vercel_messages = VercelAIAdapter.dump_messages(result.all_messages())
- ›Adds VercelAIAdapter.dump_messages() method to convert PydanticAI messages to Vercel AI message format.
- ›Supports tool and resource caching for MCP servers that emit change notifications, reducing redundant round-trips.
- ›Enables dynamic runtime configuration of built-in tools via
RunContext, allowing per-run tool behavior without rebuilding agents. - ›Supports raw Chain-of-Thought (CoT) reasoning output from LM Studio and other OpenAI Responses-compatible APIs.
- ›Uses a custom reasoning field for OpenRouter to surface model reasoning traces.
- v1.26.0
PydanticAI v1.26.0 adds Grok models, custom OpenAI reasoning fields, Deepseek JSON output, and gateway model name support.
└──▷ GET THIS VERSION$ git clone --branch v1.26.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.26.0
- ›Adds custom reasoning field support to OpenAI model profiles, enabling configuration of reasoning behaviour for compatible models.
- ›Adds
gateway/...:...pattern to known model names, allowing gateway-routed models to be referenced by name without custom setup. - ›Supports JSON object output for the Deepseek provider, enabling structured response parsing from Deepseek models.
- ›Adds latest Grok (xAI) models to the supported model list.
- ›Automatically omits
TTLfromcache_controlwhenAnthropicModelis used with a Bedrock client, preventing unsupported-field errors.
- v1.25.0
PydanticAI v1.25.0 adds support for
gemini-3-pro-image-previewand improved Google tool error reporting.└──▷ GET THIS VERSION$ git clone --branch v1.25.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.25.0
- ›Adds support for the
gemini-3-pro-image-previewmodel. - ›Returns tool errors to Google in the
errorkey, enabling structured error feedback in Google model integrations.
- ›Adds support for the
- v1.24.0
PydanticAI v1.24.0 adds native JSON output for Anthropic, Pydantic validation context, logprobs from Responses API, and instructions-only agent runs.
└──▷ GET THIS VERSION$ git clone --branch v1.24.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.24.0
- ›Supports instructions-only agent runs with
OpenAIResponsesModel, enabling prompts without user message content. - ›Adds native JSON output and strict tool calls for Anthropic models.
- ›Supports Pydantic validation context, allowing contextual data to be passed into validators during model output parsing.
- ›Supports logprobs output from the OpenAI Responses API.
- ›Supports instructions-only agent runs with
- v1.23.0
PydanticAI v1.23.0 adds Anthropic WebFetchTool, cache-message settings, HITL user prompts, and Gemini 3 Pro via OpenRouter.
└──▷ GET THIS VERSION$ git clone --branch v1.23.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.23.0
- ›Adds
anthropic_cache_messagesmodel setting for Anthropic models, with automatic stripping of cache points that exceed the provider limit. - ›Adds support for Anthropic's built-in
WebFetchTool, enabling web-fetch capability natively through the Anthropic provider. - ›Allows
user_promptto be supplied in Human-in-the-Loop (HITL) interactions. - ›Adds Gemini 3 Pro support to
OpenRouterModel. - ›Ensures the
openrouter_reasoningmodel setting is correctly forwarded to the OpenRouter API.
- ›Adds
- v1.22.0
PydanticAI v1.22.0 adds OpenRouterModel, broadens FallbackModel error handling, and extends Anthropic caching support.
└──▷ GET THIS VERSION$ git clone --branch v1.22.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.22.0
└──▷ USE ITChain multiple models so that any API-level failure (not just HTTP errors) automatically tries the next model.from pydantic_ai import Agent from pydantic_ai.models.fallback import FallbackModel from pydantic_ai.models.openai import OpenAIModel from pydantic_ai.models.anthropic import AnthropicModel model = FallbackModel(OpenAIModel('gpt-4o'), AnthropicModel('claude-3-5-sonnet-latest')) agent = Agent(model) result = agent.run_sync('Analyze this log file for anomalies.') print(result.output)- ›Adds
OpenRouterModelas anOpenAIChatModelsubclass with additional feature support for the OpenRouter API. - ›Expands
FallbackModelto fall back on all model API errors, not only HTTP 4xx+ status responses. - ›Adds
documentto the allowedcacheable_typesfor Anthropic, enabling document caching.
- ›Adds
- v1.21.0
PydanticAI v1.21.0 adds MCP client resource support, server instructions exposure, and a BinaryContent path loader.
└──▷ GET THIS VERSION$ git clone --branch v1.21.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.21.0
└──▷ USE ITLoad a local image or binary file into an agent message without manually reading bytes.from pydantic_ai.messages import BinaryContent content = BinaryContent.from_path('screenshot.png')Inspect the instructions a connected MCP server advertises, useful for debugging server configuration.from pydantic_ai.mcp import MCPServerSSE server = MCPServerSSE(url='http://localhost:8080/sse') print(server.instructions)
- ›Adds
BinaryContent.from_pathconvenience method for loading binary content directly from a file path. - ›Exposes MCP server instructions via the
MCPServer.instructionsproperty. - ›Adds MCP client Resources support, enabling agents to read resources from MCP servers.
- ›Enforces that message history always starts with a user message.
- ›Always strips Markdown fences from structured output, improving reliability of parsed responses.
└──▷ BREAKING ON UPGRADE- !Message history that does not start with a user message is now rejected — any existing code passing histories beginning with a non-user message will break.
- ›Adds
- v1.20.0
PydanticAI v1.20.0 adds Gemini 3 Pro support, metadata fields on model messages, TTL for Anthropic cache, and enhanced Gemini JSON Schema features.
└──▷ GET THIS VERSION$ git clone --branch v1.20.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.20.0
└──▷ USE ITAttach trace or correlation metadata to a model request and inspect it on the response — useful for logging and auditing multi-step agent runs.from pydantic_ai.messages import ModelRequest # metadata flows through the request/response cycle request = ModelRequest(parts=[...], metadata={'trace_id': 'abc-123', 'env': 'prod'}) print(request.metadata) # {'trace_id': 'abc-123', 'env': 'prod'}- ›Adds
ModelRequest.metadataandModelResponse.metadatafields for attaching arbitrary metadata to model messages. - ›Adds
ttlfield toCachePointand Anthropic caching model settings, enabling control over cache entry lifetime. - ›Adds support for Gemini 3 Pro via
GoogleModel. - ›Supports Gemini enhanced JSON Schema features when using
GoogleModel. - ›Makes
RunContext.usageavailable in Temporal workflow contexts.
+2 moreshow less
- ›Wraps
google.genai.errors.APIErrorinModelHTTPErrorsoGoogleModelerrors are handled correctly byFallbackModel. - ›Extracts Google model usage metrics using genai-prices for more accurate token cost tracking.
- ›Adds
- v1.19.0
PydanticAI v1.19.0 adds metadata passthrough to deferred tool exceptions and Anthropic token-counting support.
└──▷ GET THIS VERSION$ git clone --branch v1.19.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.19.0
└──▷ USE ITAttach routing or audit metadata to a deferred tool call so downstream handlers know what to do with it.from pydantic_ai.exceptions import CallDeferred raise CallDeferred(metadata={'queue': 'human-review', 'priority': 'high'})- ›Adds
count_tokensmethod toAnthropicModelfor explicit token counting. - ›Adds support for
UsageLimits.count_tokens_before_requestwithAnthropicModel, enabling pre-flight token budget checks. - ›Allows
metadatato be passed toCallDeferredandApprovalRequiredexceptions, propagating it ontoDeferredToolRequests.
- ›Adds
- v1.18.0
PydanticAI v1.18.0 adds Anthropic prompt caching support and recognizes GPT-5.1 as a known model name.
└──▷ GET THIS VERSION$ git clone --branch v1.18.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.18.0
- ›Adds Anthropic prompt caching support.
- ›Adds
gpt-5.1to the list of known OpenAI model names; bumpsopenaidependency to v2.8.0 (v1 still supported). - ›Bumps
temporalioto v1.19.0 and adoptsSimplePlugin.
- v1.17.0
PydanticAI v1.17.0 adds Temporal support for FastMCPToolset and environment variable expansion in mcp.json
└──▷ GET THIS VERSION$ git clone --branch v1.17.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.17.0
└──▷ USE ITInject secrets or environment-specific values into your MCP server config without hardcoding them in mcp.json.{ "mcpServers": { "my-server": { "command": "python", "args": ["server.py"], "env": { "API_KEY": "${MY_API_KEY}" } } } }- ›Supports environment variable expansion inside
mcp.jsonwhen loading servers via load_mcp_servers(). - ›Enables
FastMCPToolsetto work with Temporal for durable, workflow-based MCP tool execution.
- ›Supports environment variable expansion inside
- v1.15.0
PydanticAI v1.15.0 adds run IDs across run/message classes and token-counting support for BedrockConverseModel.
└──▷ GET THIS VERSION$ git clone --branch v1.15.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.15.0
└──▷ USE ITEnforce a pre-request token budget on a Bedrock-backed agent — now possible because BedrockConverseModel supports count_tokens.from pydantic_ai import Agent from pydantic_ai.models.bedrock import BedrockConverseModel from pydantic_ai.usage import UsageLimits model = BedrockConverseModel('anthropic.claude-3-5-sonnet-20241022-v2:0') agent = Agent(model) result = await agent.run( 'Summarise this document', usage_limits=UsageLimits(request_tokens_limit=8000, count_tokens_before_request=True), )Correlate log entries or trace spans from a single agent run using the new run_id available on the result.result = await agent.run('What is the capital of France?') print(result.run_id) # e.g. 'a3f1c2d4-...' # Use result.run_id to filter logs or link all messages from this run- ›Adds
BedrockConverseModel.count_tokensmethod, enablingUsageLimits.count_tokens_before_requestto work with Bedrock-backed agents. - ›Adds a unique
run_idfield to run, run result, and message (request and response) classes for correlating events across a single agent run. - ›Wraps
BedrockConverseModelerrors inModelHTTPError, making Bedrock failures handled correctly when used inside aFallbackModel.
- ›Adds
- v1.14.0
PydanticAI v1.14.0 allows custom provider factories to be passed into
infer_model.└──▷ GET THIS VERSION$ git clone --branch v1.14.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.14.0
- ›Supports passing a custom provider factory into
infer_model, enabling user-defined model resolution logic.
- ›Supports passing a custom provider factory into
- v1.13.0
PydanticAI v1.13.0 adds AgentRun message accessors and new gateway config fields for API type, profile, and routing group.
└──▷ GET THIS VERSION$ git clone --branch v1.13.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.13.0
└──▷ USE ITInspect all messages from a completed agent run, including tool calls and responses, for logging or audit.result = await agent.run('What is the capital of France?') all_msgs = result.all_messages() new_msgs = result.new_messages_json()Route gateway traffic to a specific profile and routing group when using the PydanticAI gateway integration.from pydantic_ai.models.gateway import GatewayModel model = GatewayModel( model_name='gpt-4o', api_type='azure', profile='prod-profile', routing_group='eu-west', )- ›Adds AgentRun.all_messages(), AgentRun.new_messages(), AgentRun.all_messages_json(), and AgentRun.new_messages_json() methods to retrieve accumulated or incremental messages from an agent run.
- ›Adds
api_typesupport to the gateway integration, enabling selection of the backend API type via gateway config. - ›Adds
profileandrouting_groupsupport to the gateway integration, enabling fine-grained routing control. - ›Expands known model lists for Cerebras and Heroku providers.
- v1.11.1
PydanticAI v1.11.1 adds FallbackModel support for Native output mode and
ModelProfile.default_structured_output_mode└──▷ GET THIS VERSION$ git clone --branch v1.11.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.11.1
- ›Adds
ModelProfile.default_structured_output_modesupport toFallbackModel, enabling native output mode control when falling back across models.
- ›Adds
- v1.11.0
PydanticAI v1.11.0 adds runtime instructions to agent.run() and partial_output access in output validators.
└──▷ GET THIS VERSION$ git clone --branch v1.11.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.11.0
└──▷ USE ITInject context-specific instructions at invocation time without creating a new agent — useful for per-request system guidance.result = await agent.run( 'Summarize this document', instructions='Always respond in formal English and limit output to 3 sentences.' )Inspect the partially-constructed output inside an output validator to apply conditional validation logic before the full object is finalised.from pydantic_ai import RunContext @agent.output_validator async def check_output(ctx: RunContext, value: MyOutput) -> MyOutput: if ctx.partial_output is not None: # inspect intermediate state before full validation print('Partial so far:', ctx.partial_output) return value- ›Adds
instructionsparameter to agent.run(), allowing additional instructions to be injected at call time without reconfiguring the agent. - ›Adds
partial_outputfield toRunContextsupplied to output validators, exposing the partially-constructed output during validation.
- ›Adds
- v1.10.0
PydanticAI v1.10.0 adds synchronous streaming via
Agent.run_stream_sync,application/mswordfile detection, andOpenAIResponsesModel.base_url.└──▷ GET THIS VERSION$ git clone --branch v1.10.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.10.0
└──▷ USE ITRun a streaming agent response synchronously — useful in scripts or frameworks where an event loop is unavailable.with agent.run_stream_sync('Summarise this document') as result: for text in result.stream_text(): print(text, end='', flush=True)- ›Adds
Agent.run_stream_syncmethod and synchronous convenience methods onStreamedRunResultfor consuming streamed agent runs without an async runtime. - ›Implements
OpenAIResponsesModel.base_urlproperty, exposing the configured base URL on the responses model. - ›Adds support for detecting and handling
application/mswordfiles as agent inputs.
- ›Adds
- v1.9.1
PydanticAI v1.9.1 adds AsyncAnthropicVertex support and makes AG-UI frontend state readable from on_complete handlers.
└──▷ GET THIS VERSION$ git clone --branch v1.9.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.9.1
- ›Supports
AsyncAnthropicVertexas the value forAnthropicProvider.anthropic_client, enabling async Anthropic Vertex AI usage. - ›Sets AG-UI frontend state directly on the provided
depsobject so it can be read from theon_completehandler.
- ›Supports
- v1.9.0
PydanticAI v1.9.0 adds support for the Vercel AI Data Stream Protocol.
└──▷ GET THIS VERSION$ git clone --branch v1.9.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.9.0
- ›Supports the Vercel AI Data Stream Protocol, enabling PydanticAI agents to stream responses in a format compatible with Vercel AI SDK consumers.
- v1.8.0
PydanticAI v1.8.0 adds experiment metadata support and honors
openai_supports_tool_choice_requiredin OpenAI Responses models.└──▷ GET THIS VERSION$ git clone --branch v1.8.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.8.0
- ›Adds
openai_supports_tool_choice_requiredmodel profile setting support inOpenAIResponsesModel, enabling correct tool-choice behavior for OpenAI-compatible endpoints that do or don't support required tool choice. - ›Adds experiment metadata support via the new experiment metadata API.
- ›Adds
- v1.7.0
PydanticAI v1.7.0 adds OutlinesModel for running local LLMs via Transformers, Llama.cpp, MLXLM, SGLang, and vLLM
└──▷ GET THIS VERSION$ git clone --branch v1.7.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.7.0
└──▷ USE ITRun a structured-output agent against a local model without any cloud API keys, using the Transformers backend via Outlines.from pydantic_ai import Agent from pydantic_ai.models.outlines import OutlinesModel model = OutlinesModel('transformers', model_name='mistralai/Mistral-7B-v0.1') agent = Agent(model) result = agent.run_sync('Summarize this CVE advisory: ...') print(result.data)- ›Adds
OutlinesModelclass to run local models through the Outlines library, supporting Transformers, Llama.cpp, MLXLM, SGLang, and vLLM backends.
- ›Adds
- v1.6.0
PydanticAI v1.6.0 adds FastMCPToolset and a vLLM Responses API compatibility flag for OpenAI model profiles.
└──▷ GET THIS VERSION$ git clone --branch v1.6.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.6.0
└──▷ USE ITEnable vLLM Responses API compatibility when using an OpenAI model profile that requires function call status to be set to none.from pydantic_ai.models.openai import OpenAIModelProfile profile = OpenAIModelProfile(openai_responses_requires_function_call_status_none=True)
- ›Adds
OpenAIModelProfile.openai_responses_requires_function_call_status_noneflag to enable compatibility with vLLM's Responses API. - ›Adds
FastMCPToolsetfor integrating FastMCP tools into PydanticAI agents. - ›Auto-generated output tool names are now sanitized to support generic types.
- ›Adds
- v1.5.0
PydanticAI v1.5.0 introduces a beta graph API and improves OTel span naming for non-default backends.
└──▷ GET THIS VERSION$ git clone --branch v1.5.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.5.0
- ›Introduces a new graph API in beta for building agent execution graphs.
- ›Pre-formats run graph and node span names for compatibility with non-Logfire OTel backends.
- v1.4.0
PydanticAI v1.4.0 adds native MCP server support for OpenAI and Anthropic via the built-in
MCPServerTool.└──▷ GET THIS VERSION$ git clone --branch v1.4.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.4.0
└──▷ USE ITUseMCPServerToolto connect an OpenAI or Anthropic agent to a native MCP server without writing a custom tool wrapper.from pydantic_ai.tools import MCPServerTool
- ›Adds
MCPServerToolbuilt-in tool to support OpenAI and Anthropic native MCP (Model Context Protocol) server integration. - ›Raises a clear error when a Google content filter produces an empty response, making content-filter failures visible instead of silent.
- ›Adds
- v1.3.0
PydanticAI v1.3.0 adds AWS Bedrock gateway support, OVHcloud provider, IncompleteToolCall errors, and expanded OTel attributes.
└──▷ GET THIS VERSION$ git clone --branch v1.3.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.3.0
└──▷ USE ITCatch truncated tool calls gracefully in CI pipelines where token budgets are tight.from pydantic_ai.exceptions import IncompleteToolCall try: result = await agent.run(prompt) except IncompleteToolCall as e: print(f'Tool call was cut off by token limit: {e}')Connect to Vertex AI using an API key instead of application-default credentials.from pydantic_ai.providers.google import GoogleProvider provider = GoogleProvider(api_key='YOUR_VERTEX_API_KEY')
- ›Raises
IncompleteToolCallexception when a token limit is reached mid-generation of a tool call, giving callers a typed signal to handle truncated tool invocations. - ›Adds
http_clientoption toGoogleProviderand addsapi_keysupport for Vertex AI; uses PydanticAI's cached httpx client by default. - ›Uses
gateway/<upstream_provider>:as the provider name prefix for Gateway model references. - ›Adds AWS Bedrock support to the PydanticAI Gateway.
- ›Adds OVHcloud AI Endpoints as a new provider.
+4 moreshow less
- ›Makes
AbstractBuiltinToolserializable and compatible with durable execution workflows. - ›Includes eval report averages in OpenTelemetry span attributes.
- ›Includes all usage fields (beyond token counts) in OpenTelemetry span attributes.
- ›Ensures toolset spans (e.g. MCP sampling) are nested under the agent run span in traces.
- ›Raises
- v1.2.0
PydanticAI v1.2.0 adds Claude Haiku 4.5 support and genai-prices-based OpenAI usage extraction.
└──▷ GET THIS VERSION$ git clone --branch v1.2.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.2.0
- ›Adds Claude Haiku 4.5 as a supported model.
- ›Extracts OpenAI usage data via the
genai-priceslibrary for more accurate token cost reporting. - ›Includes
final_resultas an agent span attribute after streaming completes, improving observability in traces.
- v1.1.0
PydanticAI v1.1.0 adds Prefect durable execution support and a
descriptionargument for tool decorators.└──▷ GET THIS VERSION$ git clone --branch v1.1.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.1.0
└──▷ USE ITDocument a tool's purpose inline when the function's docstring is absent or insufficient.@agent.tool(description='Fetches the current weather for a given city from the weather API') def get_weather(ctx, city: str) -> str: ...- ›Adds
descriptionargument to tool function decorators, allowing inline documentation of tools without relying solely on docstrings. - ›Adds durable execution support with Prefect, enabling fault-tolerant, resumable agent runs orchestrated via Prefect workflows.
- ›Adds
- v1.0.18
PydanticAI v1.0.18 adds Nebius AI Studio provider, EvaluationReport.render(), and
ToolCallPart.idfor OpenAI Responses.└──▷ GET THIS VERSION$ git clone --branch v1.0.18 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.18
└──▷ USE ITRender a human-readable evaluation report after running evals against your agent.report = EvaluationReport(...) print(report.render())
- ›Adds
ToolCallPart.idfield to carry tool-call identifiers from the OpenAI Responses API. - ›Adds
rendermethod to theEvaluationReportclass for displaying evaluation results. - ›Adds Nebius AI Studio as a supported model provider.
- ›Adds
anyioandhttpcoreto Temporal passthrough modules, enabling those libraries to work correctly in Temporal workflows.
- ›Adds
- v1.0.17
PydanticAI v1.0.17 lets you pass
builtin_toolsat agent run time instead of only at agent definition time.└──▷ GET THIS VERSION$ git clone --branch v1.0.17 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.17
- ›Allows
builtin_toolsto be specified at agent run time, enabling per-run control over which built-in tools are available without redefining the agent.
- ›Allows
- v1.0.16
PydanticAI v1.0.16 adds datetime.time/timedelta XML formatting, contextual agent name overrides, and FileUrl force-download support.
└──▷ GET THIS VERSION$ git clone --branch v1.0.16 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.16
- ›Respects
FileUrl.force_downloadflag in OpenAI Chat and Responses model integrations. - ›Supports
datetime.timeandtimedeltatypes informat_as_xml, enabling richer XML serialization of time-based fields. - ›Allows agent name to be overridden contextually at runtime, without changing the agent's definition.
- ›Accepts
Sequence[ModelMessage]instead oflistfor method argument types, broadening compatibility with any sequence type. - ›Validates
FileUrlandBinaryContentobjects without anidentifieras valid inputs.
- ›Respects
- v1.0.15
PydanticAI v1.0.15 adds image generation support, streaming events API, and new ModelResponse convenience methods.
└──▷ GET THIS VERSION$ git clone --branch v1.0.15 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.15
└──▷ USE ITStream agent events without manually wiring up an event_stream_handler — useful for real-time UIs or logging pipelines.async for event in agent.run_stream_events('Summarize this document', deps=deps): print(event)Extract just the text from the latest model response after a run, without manually iterating over message parts.result = await agent.run('What is 2 + 2?') print(result.response.text)- ›Adds
AgentRunResult.responseconvenience method to retrieve the latest model response from a completed agent run. - ›Adds
ModelResponse.text,ModelResponse.thinking,ModelResponse.files,ModelResponse.images,ModelResponse.tool_calls, andModelResponse.builtin_tool_callsconvenience methods for accessing parts of a model response. - ›Adds Agent.run_stream_events() convenience method as a shorthand wrapper around run(event_stream_handler=...).
- ›Supports image generation and image output with Google and OpenAI providers.
- ›Adds content (e.g. files) returned by a tool to
FunctionToolResultEvent, making tool output accessible in event streams.
+3 moreshow less
- ›Sets MCPServer
idandtool_prefixattributes automatically inload_mcp_servers. - ›Adds
gemini-2.5-flashandgemini-2.5-flash-litemodel names and aliases for the Google Gemini provider. - ›Supports enums in
format_as_xmlfor structured XML formatting of enum values.
- ›Adds
- v1.0.13
PydanticAI v1.0.13 adds contextual agent instruction overrides, exposes MCPServer.server_info, and upgrades OTel instrumentation.
└──▷ GET THIS VERSION$ git clone --branch v1.0.13 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.13
└──▷ USE ITInspect MCP server metadata after connecting — useful for logging or validating server capabilities before dispatching tool calls.info = await mcp_server.server_info print(info)
- ›Exposes
server_infoon MCPServer instances, giving access to MCP server metadata at runtime. - ›Supports contextually overriding agent instructions at runtime, enabling dynamic per-request instruction customization.
- ›Upgrades OpenTelemetry instrumentation to version 3 with updated eval attributes for improved observability.
- ›Exposes
- v1.0.12
PydanticAI v1.0.12 adds Anthropic built-in memory tool support, OpenAI document URL/binary content for text/JSON/XML/YAML, and evals cost metrics.
└──▷ GET THIS VERSION$ git clone --branch v1.0.12 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.12
- ›Adds
retryargs topydantic_evals.Dataset.evaluate_syncfor configurable retry behavior in evaluation runs. - ›Adds cost metric to
pydantic-evalsoutput, giving visibility into token spend per evaluation. - ›Supports Anthropic's built-in memory tool, enabling agents to persist and recall information across turns via the provider-native mechanism.
- ›Supports text, JSON, XML, and YAML
DocumentUrlandBinaryContenton OpenAI, expanding the range of document types agents can process. - ›Prefers
structuredContentin MCP tool results when present, enabling richer structured data from MCP tool calls.
+4 moreshow less
- ›Exposes
.messagesand.toolsetstypes in the top-levelpydantic_ainamespace to improve IDE auto-import discovery. - ›Broadens the type of
common_toolsto work with agents of any deps type, removing a previous type-narrowing restriction. - ›Handles Gemini responses with more than one candidate without raising an error.
- ›Handles Ollama responses that omit
finish_reasonand adds documentation for Ollama Cloud.
- ›Adds
- v1.0.11
PydanticAI v1.0.11 adds OpenAI image detail via vendor_metadata, operation.cost metrics, and makes OutputObjectDefinition public.
└──▷ GET THIS VERSION$ git clone --branch v1.0.11 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.11
└──▷ USE ITPass OpenAI image detail level when sending an image to a vision model, to control token usage vs. resolution trade-off.from pydantic_ai.models.openai import ImageUrl image = ImageUrl( url='https://example.com/diagram.png', vendor_metadata={'detail': 'high'} )Import and use OutputObjectDefinition directly to build structured output schemas programmatically.from pydantic_ai.output import OutputObjectDefinition
- ›Supports OpenAI image detail level on
ImageUrlandBinaryContentvia thevendor_metadataparameter, enabling fine-grained vision API control. - ›Adds
operation.costmetric to instrumented models, exposing per-call cost data through OpenTelemetry instrumentation. - ›Makes
OutputObjectDefinitionpublicly importable frompydantic_ai.output, enabling programmatic construction of output schemas. - ›Supports callable classes (not just functions) as history processors, broadening the composition options for message-history pipelines.
- ›Adds
claude-sonnet-4-5to the list of known model name strings recognized by the library.
- ›Supports OpenAI image detail level on
- v1.0.10
PydanticAI v1.0.10 adds model class names as XML tags and field-level metadata options to
format_as_xml.└──▷ GET THIS VERSION$ git clone --branch v1.0.10 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.10
- ›Adds option to include field titles and descriptions as attributes in
format_as_xml, and uses model class names as XML tags by default.
- ›Adds option to include field titles and descriptions as attributes in
- v1.0.9
PydanticAI v1.0.9 adds RunContext retry introspection and streams built-in tool calls from OpenAI, Google, and Anthropic.
└──▷ GET THIS VERSION$ git clone --branch v1.0.9 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.9
└──▷ USE ITGate expensive fallback logic so it only runs on the last allowed attempt inside a tool.from pydantic_ai import RunContext async def my_tool(ctx: RunContext[None], query: str) -> str: if ctx.last_attempt: return f'Final attempt reached (max={ctx.max_retries}), returning cached result' result = call_external_api(query) return result- ›Adds
RunContext.max_retriesandRunContext.last_attemptso tool functions can inspect retry limits and detect whether the current invocation is the final attempt. - ›Streams built-in tool calls from OpenAI, Google, and Anthropic and returns them on the next request, enabling support for OpenAI reasoning models.
- ›Includes built-in tool calls and their results in OpenTelemetry (OTel) messages for full observability of tool interactions.
- ›Adds
- v1.0.8
PydanticAI v1.0.8 lets tools emit AG-UI events independently from the result returned to the model.
└──▷ GET THIS VERSION$ git clone --branch v1.0.8 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.8
- ›Tools can now return AG-UI events separately from the result sent to the model, enabling richer streaming side-effects without coupling event emission to the model's input.
- v1.0.7
PydanticAI v1.0.7 adds MCP metadata filtering, FunctionToolset defaults, and improved RunContext prompt access.
└──▷ GET THIS VERSION$ git clone --branch v1.0.7 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.7
└──▷ USE ITSet toolset-wide defaults so every tool in the FunctionToolset inherits the same strict mode and approval requirement without per-tool decoration.from pydantic_ai.toolsets import FunctionToolset toolset = FunctionToolset( strict=True, sequential=False, requires_approval=True, metadata={"source": "internal"} )Filter or inspect MCP tools at runtime by reading annotations fromToolDefinition.metadatabefore passing them to the agent.from pydantic_ai.tools import ToolDefinition def only_safe_tools(tool_def: ToolDefinition) -> bool: meta = tool_def.metadata or {} return not meta.get("destructive", False)- ›Adds
ToolDefinition.metadatafield to carry MCP metadata and annotations, enabling filtering of MCP tools by metadata. - ›Adds support for default values for
strict,sequential,requires_approval, andmetadataparameters onFunctionToolset, reducing per-tool boilerplate. - ›When a run starts with a message history ending in a
ModelRequest, its content is now available inRunContext.prompt. - ›Removes the requirement to install
mcporlogfireextras when using Temporal or DBOS integrations. - ›Combines consecutive AG-UI user and assistant messages into a single model request/response.
- ›Adds
- v1.0.6
PydanticAI v1.0.6 adds
previous_response_idsupport for the Responses API and file-based MCP server loading.└──▷ GET THIS VERSION$ git clone --branch v1.0.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.6
- ›Adds
previous_response_idparameter support for the OpenAI Responses API, enabling stateful multi-turn conversations backed by server-side response chaining. - ›Enables MCP servers to be loaded from a file, allowing declarative configuration of MCP server definitions outside of Python code.
- ›Adds
- v1.0.4
PydanticAI v1.0.4 adds a Pydantic AI Gateway provider for routing and managing LLM calls.
└──▷ GET THIS VERSION$ git clone --branch v1.0.4 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.4
- ›Adds a Pydantic AI Gateway provider, enabling use of the Pydantic AI Gateway as an LLM backend.
- v1.0.3
PydanticAI v1.0.3 adds sequential tool call context manager, AG-UI callbacks, and Google model seed support
└──▷ GET THIS VERSION$ git clone --branch v1.0.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.3
└──▷ USE ITForce an agent to execute tools one at a time — useful when tools have side effects that must not run concurrently.with agent.sequential_tool_calls(): result = await agent.run('Book a flight then send a confirmation email')Inspect the full AgentRunResult after an AG-UI run completes, e.g. to log structured output or trigger downstream actions.async def handle_complete(result: AgentRunResult) -> None: print(result.output) await agent.run_as_agui(prompt, on_complete=handle_complete)Pin a Google model to a fixed random seed so repeated runs return deterministic results during testing.from pydantic_ai.settings import ModelSettings result = await agent.run('Summarize this doc', model_settings=ModelSettings(seed=42))- ›Adds agent.sequential_tool_calls() context manager to enforce sequential (non-parallel) tool execution within an agent run.
- ›Adds
on_completecallback to AG-UI functions, providing access toAgentRunResultwhen a run finishes. - ›Supports
ModelSettings.seedinGoogleModelfor reproducible outputs. - ›Supports
NativeOutputwithFunctionModel, enabling native structured output in function-backed models. - ›Sends AG-UI thinking start and end events, surfacing model reasoning steps to AG-UI consumers.
+3 moreshow less
- ›Includes thinking parts in subsequent model requests to improve performance and cache hit rates.
- ›Raises a clear error when
WebSearchToolis used withOpenAIChatModeland an unsupported model, rather than failing silently. - ›Supports models that return output tool args as
{"response": "<JSON string>"}, broadening compatibility with non-standard model response formats.
- v1.0.2
PydanticAI v1.0.2 adds DBOS durable execution, sequential tool calling, and Google cached content support
└──▷ GET THIS VERSION$ git clone --branch v1.0.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.2
└──▷ USE ITUse Google's cached content in a model call to avoid re-processing large, repeated context on every request.from pydantic_ai.models.google import GoogleModelSettings settings = GoogleModelSettings( google_cached_content="cachedContents/abc123" ) result = await agent.run("Summarize the document.", model_settings=settings)- ›Adds
GoogleModelSettings.google_cached_contentfield to passcached_contentwhen calling Google models, enabling prompt caching. - ›Adds
ModelResponse.finish_reasonattribute and populatesprovider_response_idduring streaming responses. - ›Adds support for
gen_ai.response.idin OpenTelemetry instrumentation spans. - ›Adds support for durable execution with DBOS, enabling fault-tolerant, resumable agent workflows.
- ›Adds support for sequential tool calling, allowing agents to invoke tools one at a time in order rather than in parallel.
- ›Adds
- v1.0.0
PydanticAI v1.0.0 adds human-in-the-loop tool approval, LiteLLM provider, tool-call usage limits, and NativeOutput for Groq.
└──▷ GET THIS VERSION$ git clone --branch v1.0.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v1.0.0
└──▷ USE ITCap the number of tool calls an agent can make in a single run to prevent runaway tool loops.from pydantic_ai import Agent from pydantic_ai.settings import UsageLimits agent = Agent('openai:gpt-4o') result = await agent.run( 'Research and summarize the latest CVEs for OpenSSL', usage_limits=UsageLimits(tool_calls_limit=5) ) print(result.usage().tool_calls) # inspect actual tool calls madeControl how tool schemas are generated from docstrings — useful when enforcing that all parameters must be documented before deployment.from pydantic_ai.toolsets import FunctionToolset toolset = FunctionToolset( docstring_format='google', require_parameter_descriptions=True )- ›Adds
tool_calls_limittoUsageLimitsandtool_callstoRunUsageto cap and track tool-call counts per run. - ›Adds
docstring_format,require_parameter_descriptions, andschema_generatorparameters toFunctionToolsetfor fine-grained tool schema control. - ›Adds
operation.costspan attribute to model request spans; renames ModelResponse.price() to ModelResponse.cost(). - ›Adds
identifierfield toFileUrland its subclasses. - ›Adds human-in-the-loop tool call approval support, enabling agents to pause and await human confirmation before executing tools.
+5 moreshow less
- ›Adds a LiteLLM provider for OpenAI-API-compatible models.
- ›Supports
NativeOutputwith Groq models. - ›Bundles
logfirewith thepydantic-aipackage so tracing is available without a separate install. - ›Allows most types used in documentation examples to be imported directly from
pydantic_ai. - ›Defaults
InstrumentationSettingsversionto2.
└──▷ BREAKING ON UPGRADE- !Python 3.9 is no longer supported; the minimum supported version is now Python 3.10.
- !ModelResponse.price() is renamed to ModelResponse.cost(); call sites using .price() will break.
- !
OpenAIModelProfile.openai_supports_sampling_settingsis deprecated. - !
mcp-run-pythonhas been moved to its own repository and is no longer part of this package.
- ›Adds
- v0.8.1
PydanticAI v0.8.1 adds system-instructions tracing to agent run spans and renames key streaming and response methods.
└──▷ GET THIS VERSION$ git clone --branch v0.8.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.8.1
- ›Adds
gen_ai.system_instructionsattribute to agent run spans, exposing system prompt content in OpenTelemetry traces. - ›Renames
StreamedRunResultmethods to be consistent withAgentStream(see breaking changes). - ›Renames
ModelResponse.provider_request_idtoprovider_response_id(see breaking changes).
└──▷ BREAKING ON UPGRADE- !
StreamedRunResultmethods are renamed to matchAgentStreamnaming conventions — callers using the old method names will break on upgrade. - !
ModelResponse.provider_request_idis renamed toprovider_response_id— any code referencingprovider_request_idwill break on upgrade. - !Specifying a model name without a provider prefix is deprecated, as is the
vertexaiprovider name — configurations using bare model names orvertexaiwill need to be updated.
- ›Adds
- v0.8.0
PydanticAI v0.8.0 adds elicitation callbacks for MCP servers, message history in CLI agents, and a richer AgentStreamEvent union type.
└──▷ GET THIS VERSION$ git clone --branch v0.8.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.8.0
└──▷ USE ITSeed a CLI agent session with prior message history so returning users resume context rather than starting fresh.agent.to_cli(message_history=prior_messages)
- ›Adds
message_historyparameter to agent.to_cli() to seed CLI sessions with prior conversation context. - ›Adds elicitation callback support to MCP servers, enabling agents to request additional input from users during tool execution.
- ›Makes
AgentStreamEventa union ofModelResponseStreamEventandHandleResponseEvent, expanding the event types available when streaming agent responses.
- ›Adds
- v0.7.6
PydanticAI v0.7.6 adds a Cerebras provider and renames the OpenAI model class.
└──▷ GET THIS VERSION$ git clone --branch v0.7.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.6
- ›Adds
CerebrasProvider(Cerebras provider integration) for running agents against Cerebras-hosted models. - ›Replaces
all_messages_eventswithpydantic_ai.all_messagesspan/event name under InstrumentationSettings(version=2). - ›Deprecates
OpenAIModelin favor of the newOpenAIChatModelclass.
└──▷ BREAKING ON UPGRADE- !The tenacity retry implementation has changed behavior — existing retry logic built on the prior
AsyncTenacityTransportsemantics may behave differently on upgrade.
- ›Adds
- v0.7.5
PydanticAI v0.7.5 adds cost pricing on ModelResponse, span/trace IDs on EvaluationReport, and updated OpenTelemetry GenAI conventions.
└──▷ GET THIS VERSION$ git clone --branch v0.7.5 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.5
└──▷ USE ITInspect the monetary cost of a model response after an agent run, useful for budget tracking or logging.result = await agent.run('Summarise this document') print(result.new_messages()[-1].price())- ›Adds price() method to
ModelResponseto retrieve cost information for a model response. - ›Adds
span_idandtrace_idfields toEvaluationReportfor linking evaluations to distributed traces. - ›Updates OpenTelemetry instrumentation to use the new GenAI chat span attribute conventions.
- ›Includes thoughts tokens in
output_tokensaccounting for Google models. - ›Allows proper typing on
AnthropicProviderwhen using the Bedrock backend.
└──▷ BREAKING ON UPGRADE- !OpenTelemetry span attributes for GenAI chat now follow the new GenAI conventions — any dashboards, alerts, or attribute-based queries built on the old attribute names will need to be updated.
- ›Adds price() method to
- v0.7.4
PydanticAI v0.7.4 adds
takes_ctxtoTool.from_schemaand supports Google'surl_contextbuilt-in tool.└──▷ GET THIS VERSION$ git clone --branch v0.7.4 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.4
└──▷ USE ITCreate a schema-derived tool that receives the agent context, enabling context-aware logic inside the tool handler.tool = Tool.from_schema(schema=my_schema, takes_ctx=True)
Enable Google's URL context built-in tool so the agent can fetch and reason over live web content during a run.from pydantic_ai.models.google import UrlContextTool agent = Agent(model='google-gla:gemini-2.0-flash', tools=[UrlContextTool()])
- ›Adds
takes_ctxargument toTool.from_schema, letting callers control whether the generated tool receives the agent context. - ›Supports Google's
url_contextbuilt-in tool via the newUrlContextToolclass, now exported in__all__.
- ›Adds
- v0.7.3
PydanticAI v0.7.3 adds a CLI clipboard command, lets FallbackModel accept string names, and splits Usage into RequestUsage and RunUsage.
└──▷ GET THIS VERSION$ git clone --branch v0.7.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.3
└──▷ USE ITUse a string model name directly in FallbackModel instead of constructing a model object.from pydantic_ai.models.fallback import FallbackModel model = FallbackModel('openai:gpt-4o', 'anthropic:claude-3-5-sonnet-latest')- ›Adds
/cpcommand to the CLI to copy the last response to the clipboard. - ›
FallbackModelnow accepts plain string model names in addition to model objects. - ›Moves
system_prompt_rolefromOpenAIModeltoOpenAIModelProfile, making it configurable at the profile level. - ›Introduces
RequestUsageandRunUsageas replacements for the unified Usage class, providing finer-grained usage tracking.
└──▷ BREAKING ON UPGRADE- !Usage is deprecated in favour of
RequestUsageandRunUsage; code referencing Usage directly will need to migrate to the appropriate replacement class.
- ›Adds
- v0.7.2
PydanticAI v0.7.2 adds OllamaProvider, HuggingFace profile/settings, and max_uses for Anthropic WebSearchTool.
└──▷ GET THIS VERSION$ git clone --branch v0.7.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.2
└──▷ USE ITCap web searches to 3 per agent run when using Anthropic's built-in WebSearchTool to control cost and latency.from pydantic_ai import Agent from pydantic_ai.models.anthropic import AnthropicModel from pydantic_ai.tools.anthropic import WebSearchTool agent = Agent( model=AnthropicModel('claude-3-5-sonnet-latest'), tools=[WebSearchTool(max_uses=3)], ) result = agent.run_sync('What are the latest CVEs in OpenSSL?') print(result.output)- ›Adds
OllamaProviderfor connecting PydanticAI agents to locally hosted Ollama models. - ›Adds
profileandsettingsparameters toHuggingfaceModelfor finer control over HuggingFace inference. - ›Forwards
max_usesparameter to Anthropic'sWebSearchTool, allowing callers to cap the number of web searches per run. - ›Allows message history to end on a
ModelResponseand automatically executes any pending tool calls, enabling richer conversation resumption. - ›Prompts the model to retry when it produces a response containing only thinking tokens (no text or tool calls), improving reliability with reasoning models.
└──▷ BREAKING ON UPGRADE- !Removes the
anthropic-betadefault header previously set inAnthropicModel; integrations relying on that header being sent automatically will need to set it explicitly.
- ›Adds
- v0.7.1
PydanticAI v0.7.1 adds GPT-5 models, OpenAI verbosity support, pre-request token counting via Gemini, and a new model inference string.
└──▷ GET THIS VERSION$ git clone --branch v0.7.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.1
└──▷ USE ITSelect the OpenAI Responses API using the new inference string shorthand instead of importing a model class.from pydantic_ai import Agent agent = Agent('openai-responses:gpt-4o') result = await agent.run('What is the capital of France?') print(result.output)- ›Adds
UsageLimits.count_tokens_before_requestto count tokens using Gemini'scount_tokensAPI before a request is sent, enabling proactive limit enforcement. - ›Supports the
"openai-responses"model inference string for selecting the OpenAI Responses API via string-based model configuration. - ›Adds support for the OpenAI
verbosityparameter in the Responses API. - ›Adds new OpenAI GPT-5 models to the supported model list.
- ›Adds
- v0.7.0
PydanticAI v0.7.0 adds Temporal workflow support, dynamic toolsets, event stream handlers, and new agent abstractions.
└──▷ GET THIS VERSION$ git clone --branch v0.7.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.7.0
└──▷ USE ITTap into the live event stream of an agent run — useful for streaming intermediate tool-call and model-request events to a UI or logger.async with agent.run_stream('Analyze logs', event_stream_handler=my_handler) as response: async for chunk in response.stream_text(): print(chunk)- ›Adds
event_stream_handlerparameter to agent and run methods for subscribing to agent event streams. - ›Adds Agent.override(tools=...) to replace or inject tools into an existing agent at runtime.
- ›Adds
AbstractAgentandWrapperAgentbase classes for building composable agent wrappers. - ›Enables running Agent inside a Temporal workflow by dispatching model requests, tool calls, and MCP as Temporal activities.
- ›Supports dynamically building toolsets based on run context via the toolset API.
+1 moreshow less
- ›Adds a history processor API that replaces message history on each run, enabling custom context-window management.
- ›Adds
- v0.6.2
PydanticAI v0.6.2 adds
builtin_toolsparameter to the Agent class.└──▷ GET THIS VERSION$ git clone --branch v0.6.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.6.2
- ›Adds
builtin_toolsparameter to Agent, enabling control over which built-in tools are available to an agent.
- ›Adds
- v0.6.1
PydanticAI v0.6.1 adds automatic OpenAI strict mode, Bedrock thinking parts, AWS bearer token support, and new Heroku models.
└──▷ GET THIS VERSION$ git clone --branch v0.6.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.6.1
- ›Supports
AWS_BEARER_TOKEN_BEDROCKenvironment variable for authenticating with AWS Bedrock via bearer token. - ›Makes
InlineDefsJsonSchemaTransformerpart of the public API, allowing direct use in custom JSON schema transformations. - ›Automatically enables OpenAI strict mode for output types that are strict-compatible, removing the need for manual configuration.
- ›Sends
ThinkingParts back to Anthropic when accessed through AWS Bedrock, enabling extended thinking round-trips. - ›Adds new Heroku models to the supported model list.
- ›Supports
- v0.6.0
PydanticAI v0.6.0 adds a new Anthropic model and removes a wave of long-deprecated APIs.
└──▷ GET THIS VERSION$ git clone --branch v0.6.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.6.0
- ›Adds a new Anthropic model (removes older deprecated Anthropic models in the same change).
└──▷ BREAKING ON UPGRADE- !The next() method is removed from Graph.
- !The
dataattribute is removed fromFinalResult. - !The
get_dataandvalidate_structured_resultmethods are removed fromStreamedRunResult. - !The
format_as_xmlmodule is removed entirely. - !The
result_typeparameter (and similar parameters) is removed from Agent. - !Four months of accumulated deprecation warnings are now hard removals — any code that relied on those deprecated APIs will break.
- v0.5.0
PydanticAI v0.5.0 expands OpenAI strict JSON mode compatibility and adds default values to tool argument schemas.
└──▷ GET THIS VERSION$ git clone --branch v0.5.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.5.0
- ›Enables more
BaseModels to use OpenAI strict JSON mode by defaultingadditionalProperties=Falseautomatically. - ›Supports string
format,pattern, and related constraints within OpenAI strict JSON mode. - ›Includes default values in the JSON schema generated for tool arguments.
└──▷ BREAKING ON UPGRADE- !The
EvaluationReport.printandEvaluationReport.console_tablemethods now require most arguments to be passed by keyword. - !The
sourcefield ofEvaluationResultis now of typeEvaluatorSpecinstead of the actual Evaluator instance; existing code that accessed the live evaluator instance viasourcewill break.
- ›Enables more
- v0.4.11
PydanticAI v0.4.11 adds AG-UI convenience functions and custom thinking-tag support on model profiles.
└──▷ GET THIS VERSION$ git clone --branch v0.4.11 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.11
- ›Supports custom thinking tags specified on the model profile, letting callers control how chain-of-thought tokens are surfaced per model.
- ›Adds convenience functions to handle AG-UI requests with request-specific dependencies.
- v0.4.10
PydanticAI v0.4.10 adds
priorityservice_tierto OpenAI settings and HTTP Referer header support for Vercel AI Gateway.└──▷ GET THIS VERSION$ git clone --branch v0.4.10 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.10
└──▷ USE ITRoute OpenAI requests through the priority service tier to reduce latency for time-sensitive workloads.from pydantic_ai.models.openai import OpenAIModelSettings settings = OpenAIModelSettings(service_tier='priority') result = await agent.run('Summarize this incident report.', model_settings=settings)- ›Adds
priorityservice_tieroption toOpenAIModelSettings, respected byOpenAIResponsesModel, enabling OpenAI priority-tier routing from model configuration. - ›Adds HTTP Referer request header support to the Vercel AI Gateway provider.
- ›Adds
- v0.4.8
PydanticAI v0.4.8 adds tenacity retry integration and thinking-part tracing in OpenTelemetry model response events.
└──▷ GET THIS VERSION$ git clone --branch v0.4.8 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.8
- ›Adds tenacity utilities and integration for improved retry handling in agent workflows.
- ›Includes
ThinkingPartin OpenTelemetry OTEL events emitted viaModelResponse, surfacing model reasoning in traces.
- v0.4.7
PydanticAI v0.4.7 adds MoonshotAI, Vercel AI Gateway providers, Gemini Files API support, and MCP ResourceLink handling.
└──▷ GET THIS VERSION$ git clone --branch v0.4.7 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.7
└──▷ USE ITConnect an MCP server using the renamedread_timeoutparameter to avoid breaking on upgrade.from pydantic_ai.mcp import MCPServer server = MCPServer( url='https://mcp.example.com/sse', read_timeout=30, )- ›Renames MCPServer parameter
sse_read_timeouttoread_timeout, which is now passed through toClientSession. - ›Adds
MoonshotAIprovider with Kimi-K2 model support. - ›Adds Vercel AI Gateway provider.
- ›Supports passing files uploaded to the Gemini Files API and setting a custom media type.
- ›Parses
<think>tags in streamed text as thinking parts (ThinkingPart).
+1 moreshow less
- ›Adds support for
MCP ResourceLinkreturned from tools.
└──▷ BREAKING ON UPGRADE- !The MCPServer parameter
sse_read_timeoutis renamed toread_timeout; any code passingsse_read_timeoutby keyword will break on upgrade.
- ›Renames MCPServer parameter
- v0.4.6
PydanticAI v0.4.6 adds URL and binary PDF support for the Mistral provider.
└──▷ GET THIS VERSION$ git clone --branch v0.4.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.6
- ›Adds URL and binary PDF input support for the Mistral provider, enabling document-based prompts via URL or raw binary PDF.
- ›Speeds up the internal
_estimate_string_tokensfunction, improving throughput for token-heavy workloads.
- v0.4.5
PydanticAI v0.4.5 adds streamable HTTP transport support to mcp-run-python and changes format_as_xml defaults.
└──▷ GET THIS VERSION$ git clone --branch v0.4.5 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.5
- ›Supports streamable HTTP transport in
mcp-run-python, enabling streaming MCP server connections over HTTP.
└──▷ BREAKING ON UPGRADE- !The default values for
format_as_xmlhave changed; existing code relying on the previous defaults may produce different XML output after upgrading.
- ›Supports streamable HTTP transport in
- v0.4.4
PydanticAI v0.4.4 adds Toolsets, AG-UI protocol support, new OpenAI/Grok/Kimi models, and an
identifierfield onBinaryContent.└──▷ GET THIS VERSION$ git clone --branch v0.4.4 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.4
└──▷ USE ITAttach a binary file to an agent message and reference it later by a stable identifier.from pydantic_ai.messages import BinaryContent image = BinaryContent(data=image_bytes, media_type='image/png', identifier='screenshot-001') result = await agent.run([image, 'Describe this image.'])
- ›Adds
identifierfield to theBinaryContentclass for tagging binary content objects. - ›Introduces Toolsets and Deferred Tools, enabling grouped and lazily-resolved tool registration on agents.
- ›Supports the AG-UI protocol for frontend-agent communication.
- ›Adds OpenAI models
o1-pro,o3-pro,o3-deep-research, andcomputer-useas selectable models. - ›Adds
grok-4andkimi-k2(via Groq) as selectable models.
+1 moreshow less
- ›Speeds up
AgentRunResult._set_output_tool_returnby ~18,798%, unlocking high-throughput agent run scenarios.
└──▷ BREAKING ON UPGRADE- !Old Google models have been removed; any code referencing those model identifiers will break on upgrade.
- ›Adds
- v0.4.3
PydanticAI v0.4.3 adds Hugging Face provider support, output function tracing, and base64 encoding for tool returns.
└──▷ GET THIS VERSION$ git clone --branch v0.4.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.3
- ›Adds base64 encoding support to
tool_return_ta, enabling binary data to be returned from tools. - ›Adds output function tracing, allowing agent output functions to be captured in traces.
- ›Adds Hugging Face as a new model provider.
└──▷ BREAKING ON UPGRADE- !The
duckduckgo-searchpackage dependency is renamed toddgs; any install or import referencingduckduckgo-searchwill break.
- ›Adds base64 encoding support to
- v0.4.2
PydanticAI v0.4.2 adds StructuredDict for custom JSON schema outputs, model settings on model classes, and DeepSeek reasoning_content streaming support.
└──▷ GET THIS VERSION$ git clone --branch v0.4.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.2
- ›Adds
StructuredDictclass for defining structured outputs with a custom JSON schema, giving callers direct control over the schema shape returned by the model. - ›Allows model
settingsto be passed directly to model classes, enabling per-model configuration at instantiation time. - ›Supports DeepSeek
reasoning_contentfield in streamed responses, surfacing chain-of-thought reasoning tokens from DeepSeek models during streaming. - ›Speeds up internal
_ensure_decodeablefunction by 634%, unlocking higher-throughput decoding for workloads processing large volumes of model output.
└──▷ BREAKING ON UPGRADE- !FastA2A has been dropped from the PydanticAI repository and is no longer available as part of the package.
- ›Adds
- v0.4.1
PydanticAI v0.4.1 adds sync task evaluation support and drops FastA2A as a transitive dependency.
└──▷ GET THIS VERSION$ git clone --branch v0.4.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.1
- ›Adds support for evaluating synchronous tasks in PydanticAI's evals framework, expanding coverage beyond async-only workflows.
└──▷ BREAKING ON UPGRADE- !FastA2A is no longer a PydanticAI dependency; projects that relied on it being pulled in transitively must now declare it as a direct dependency.
- v0.4.0
PydanticAI v0.4.0 adds broader Gemini audio support and makes
ToolDefinition.descriptionoptional.└──▷ GET THIS VERSION$ git clone --branch v0.4.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.4.0
- ›Makes
ToolDefinition.descriptionoptional, removing the requirement to supply a description when defining tools. - ›Adds all Gemini-supported audio types to
AudioUrl, expanding multimodal input coverage for Gemini models. - ›Retains default values in non-strict OpenAI schemas, preserving schema fidelity when targeting OpenAI backends.
└──▷ BREAKING ON UPGRADE- !
EvaluationReportandReportCaseare now generic dataclasses — any code that instantiates or type-annotates these without type parameters may require updates.
- ›Makes
- v0.3.7
PydanticAI v0.3.7 adds GitHub Models provider, ACI.dev Tools integration, sync streaming, and Google video analysis args.
└──▷ GET THIS VERSION$ git clone --branch v0.3.7 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.7
- ›Adds
model_request_stream_syncto the direct API, enabling synchronous streaming of model requests. - ›Adds GitHub Models as a new provider via the GitHub Models provider integration.
- ›Adds support for Google-specific arguments for video analysis in the Google provider.
- ›Implements ACI.dev Tools integration, providing a convenient way to use ACI.dev tools in PydanticAI.
- ›
AgentStream.stream_output(available insideagent.iter) now streams validated output data instead of raising validation errors mid-stream.
- ›Adds
- v0.3.6
PydanticAI v0.3.6 adds predicted outputs to OpenAIModelSettings and records tool responses in trace spans.
└──▷ GET THIS VERSION$ git clone --branch v0.3.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.6
└──▷ USE ITPass a predicted output to OpenAI to reduce latency when the likely response text is known in advance.from pydantic_ai.models.openai import OpenAIModelSettings settings = OpenAIModelSettings( predicted_outputs={"type": "content", "content": "<your predicted text here>"} ) result = await agent.run("Refactor this code", model_settings=settings)- ›Adds support for
predicted_outputsinOpenAIModelSettings, enabling speculative/predicted output hints when calling OpenAI models. - ›Records tool response data in tool-run spans, enriching tracing and observability for agent tool calls.
- ›Improves model communication by marking a
RetryPromptPartnot tied to a tool call as validation feedback rather than a user message, giving the model clearer signal on why a retry is occurring. - ›Switches agent overriding from a local attribute to
contextvars, making agent context propagation safe across async/concurrent workloads.
- ›Adds support for
- v0.3.5
PydanticAI v0.3.5 lets tools return
ToolReturnfor richer model content and adds strict mode toNativeOutput.└──▷ GET THIS VERSION$ git clone --branch v0.3.5 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.5
- ›Supports strict mode in
NativeOutput, enabling stricter schema validation for native model outputs. - ›Allows tools to return a
ToolReturnobject to pass additional content to the model or attach metadata that is not forwarded to the model. - ›Sets
'us-central1'as the default region onGoogleProvider, removing the need to configure it explicitly. - ›Moves
ThinkingPartto precedeTextPartinOpenAIResponsesModel, aligning reasoning output ordering. - ›Adds a progress bar during evaluation runs.
└──▷ BREAKING ON UPGRADE- !The default region for
GoogleProvideris now'us-central1'; existing setups that relied on no default region being set may route requests differently after upgrading.
- ›Supports strict mode in
- v0.3.4
PydanticAI v0.3.4 adds sensitive-content scrubbing to agent pipelines.
└──▷ GET THIS VERSION$ git clone --branch v0.3.4 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.4
- ›Adds sensitive content scrubbing to redact or sanitize private data within agent interactions.
- v0.3.3
PydanticAI v0.3.3 adds NativeOutput and PromptedOutput modes and captures more OpenAI-compatible usage fields.
└──▷ GET THIS VERSION$ git clone --branch v0.3.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.3
- ›Adds
NativeOutputandPromptedOutputoutput modes alongside the existingToolOutputmode, giving agents more control over how structured results are produced. - ›Captures additional usage fields returned by OpenAI-compatible APIs, surfacing richer token and cost details in Usage objects.
- ›Makes Edge hashable, enabling graph edges to be stored in sets and used as dict keys.
- ›Adds
- v0.3.0
PydanticAI v0.3.0 adds
ThinkingPartsupport, parsing provider thinking blocks into a dedicated message part type.└──▷ GET THIS VERSION$ git clone --branch v0.3.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.3.0
- ›Adds
ThinkingPartas a new message part type: provider-specific<think>...</think>blocks in text responses are now parsed and surfaced as structuredThinkingPartobjects rather than raw text.
└──▷ BREAKING ON UPGRADE- !
ThinkingParts are not sent back to the provider in subsequent turns — existing agents that relied on thinking content being echoed back in the message history will no longer include it, reducing costs but changing round-trip behavior.
- ›Adds
- v0.2.20
PydanticAI v0.2.20 adds a process_tool_call hook for MCP servers and RunContext support in history processors.
└──▷ GET THIS VERSION$ git clone --branch v0.2.20 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.20
- ›Adds
process_tool_callhook to MCP servers, enabling interception and modification of tool arguments, metadata, and return values before and after MCP tool execution. - ›Adds
RunContextsupport to history processors, giving them access to the full run context when processing conversation history. - ›Adds
ModelSettings.timeoutenforcement inGoogleModel, so timeout settings are now respected when calling Google models.
- ›Adds
- v0.2.19
PydanticAI v0.2.19 adds
history_processorsto Agent and surfaces events for unknown tool calls└──▷ GET THIS VERSION$ git clone --branch v0.2.19 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.19
└──▷ USE ITFilter or redact sensitive messages from history before every model call, e.g. to strip PII in a compliance-sensitive pipeline.from pydantic_ai import Agent from pydantic_ai.messages import ModelMessage def redact_secrets(messages: list[ModelMessage]) -> list[ModelMessage]: # drop any message whose text contains an API key pattern return [m for m in messages if 'sk-' not in str(m)] agent = Agent('openai:gpt-4o', history_processors=[redact_secrets]) result = agent.run_sync('What did we discuss earlier?')- ›Adds
history_processorsparameter to Agent for programmatic pre-processing of message history before each model call. - ›Yields streaming events for unknown tool calls instead of silently dropping them, enabling downstream handling of unrecognised tool responses.
- ›Makes
infer_providermore flexible, accepting a broader range of inputs when resolving provider from a model string. - ›Ignores dynamic instructions that return an empty string, preventing blank system-prompt entries from being appended to the message list.
└──▷ BREAKING ON UPGRADE- !Anthropic
max_tokensis now set to 4096 by default; any agent relying on the previous default behaviour may produce truncated responses or incur different token usage.
- ›Adds
- v0.2.18
PydanticAI v0.2.18 adds MCP Streamable HTTP, OpenAI Responses API vendor ID, and reuses last message when no prompt is given.
└──▷ GET THIS VERSION$ git clone --branch v0.2.18 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.18
- ›Exposes the OpenAI Responses API response ID as
vendor_idon the model response object. - ›Adds MCP Streamable HTTP transport implementation.
- ›Reuses the last request from message history automatically when no user prompt is provided, enabling continuation flows without re-supplying context.
- ›Switches Gemini inference to use
GoogleModelinstead ofGeminiModel.
- ›Exposes the OpenAI Responses API response ID as
- v0.2.17
PydanticAI v0.2.17 adds token usage to InstrumentedModel, service_tier for OpenAI, custom httpx clients for MCP, and Gemini direct file URL support.
└──▷ GET THIS VERSION$ git clone --branch v0.2.17 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.17
└──▷ USE ITSet a specific OpenAI service tier (e.g. 'flex' or 'auto') for cost or latency control in your agent's model settings.from pydantic_ai.models.openai import OpenAIModelSettings settings = OpenAIModelSettings(service_tier='flex')
- ›Adds
service_tierfield toOpenAIModelSettingsto control OpenAI service tier selection. - ›Adds token usage metrics to
InstrumentedModelfor observability of model calls. - ›Allows users to supply a custom
httpx.AsyncClientinMCPServerHTTPfor full control over HTTP transport. - ›Supports
fileDatafield (direct file URL) forGeminiModelandGoogleModel, enabling direct URL-based file inputs. - ›Suppresses inapplicable sampling settings (
temperature,top_p) when targeting OpenAI reasoning models.
- ›Adds
- v0.2.16
PydanticAI v0.2.16 adds HerokuProvider, stop_sequences for Google models, and LangChain community tool integration.
└──▷ GET THIS VERSION$ git clone --branch v0.2.16 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.16
└──▷ USE ITRoute agent inference through a Heroku-hosted model endpoint.from pydantic_ai import Agent from pydantic_ai.providers.heroku import HerokuProvider agent = Agent(provider=HerokuProvider())
- ›Adds
HerokuProviderto connect agents to Heroku-hosted models. - ›Adds
stop_sequencesparameter support for Google models. - ›Adds a convenience method to use LangChain community tools directly within PydanticAI agents.
- ›Improves output type inference when callables are provided as output types.
- ›Adds
- v0.2.13
PydanticAI v0.2.13 adds expected-output support to LLMJudge evaluations.
└──▷ GET THIS VERSION$ git clone --branch v0.2.13 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.13
- ›Adds option to pass expected output to LLMJudge, enabling reference-based LLM evaluation scoring.
- v0.2.12
PydanticAI v0.2.12 adds function output types, ModelProfile config, Together/Fireworks/Grok providers, and Claude 4 on Bedrock.
└──▷ GET THIS VERSION$ git clone --branch v0.2.12 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.12
└──▷ USE ITUse a plain function as an agent's output type so the model's response directly invokes structured tool-like logic.from pydantic_ai import Agent def send_alert(message: str, severity: str) -> None: ... # your implementation agent = Agent('openai:gpt-4o', output_type=send_alert) result = await agent.run('Notify me if CPU exceeds 90%')Route agent calls to Together AI or Fireworks AI using the new dedicated provider classes with automatic model profile selection.from pydantic_ai import Agent from pydantic_ai.providers.together import TogetherProvider agent = Agent(TogetherProvider(), model='meta-llama/Llama-3-70b-chat-hf') result = await agent.run('Summarize this incident report: ...')- ›Adds
ModelProfileclass to configure model-specific behaviors independently of the model class, enabling fine-grained control over provider quirks without subclassing. - ›Adds new provider classes for Together AI, Fireworks AI, and Grok with automatic model profile selection.
- ›Adds
vendor_idandvendor_details.finish_reasonfields to Gemini/Google model response objects. - ›Supports functions as
output_typein agents, including lists of functions mixed with other types. - ›Adds support for Claude 4 Sonnet and Opus models via the Bedrock provider.
+1 moreshow less
- ›Enhances Gemini usage tracking to collect comprehensive token data beyond basic prompt/completion counts.
- ›Adds
- v0.2.10
PydanticAI v0.2.10 adds Claude Sonnet 4 support, MCP Streamable HTTP transport, and MCP client init timeouts.
└──▷ GET THIS VERSION$ git clone --branch v0.2.10 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.10
- ›Adds support for Claude Sonnet 4 as a model target.
- ›Adds MCP Streamable HTTP transport support, enabling HTTP-based MCP server connections alongside the existing stdio transport.
- ›Adds a timeout for initializing MCP clients, preventing indefinite hangs during MCP server startup.
- ›Updates supported Google models.
- v0.2.9
PydanticAI v0.2.9 adds Vertex AI label support for Gemini/Google models and improves Agent CLI output handling.
└──▷ GET THIS VERSION$ git clone --branch v0.2.9 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.9
- ›Supports
labelsfield forGeminiModelandGoogleModelon Vertex AI, enabling resource labeling for cost attribution and organization. - ›Non-textual responses in
Agent.to_cliare now cast tostr, allowing the CLI interface to handle structured or binary model outputs.
- ›Supports
- v0.2.7
PydanticAI v0.2.7 adds MCP tool_prefix namespacing, real-time Anthropic streaming, and a customizable prog_name for CLI agents.
└──▷ GET THIS VERSION$ git clone --branch v0.2.7 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.7
└──▷ USE ITNamespace tools from two MCP servers that might share names to avoid conflicts and make tool origins clear in logs.from pydantic_ai.mcp import MCPServerStdio search_server = MCPServerStdio('npx', ['-y', '@modelcontextprotocol/server-brave-search'], tool_prefix='search') fs_server = MCPServerStdio('npx', ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'], tool_prefix='fs') # Tools are now exposed as 'search_<name>' and 'fs_<name>', and duplicate bare names raise an error.- ›Adds
tool_prefixoption to MCP servers to namespace tool names and raises an error on conflicting tool names across servers. - ›Makes
prog_namecustomizable on CLI agents, allowing teams to brand or script against a consistent program name. - ›Removes the hardcoded
nparameter fromOpenAIModelrequests, unlocking use of endpoints and deployments that reject that field. - ›Streams tool calls and structured output from Anthropic incrementally as tokens arrive instead of buffering the full response.
- ›Supports streaming tool calls from models that pass
argsas None when a function has no parameters.
- ›Adds
- v0.2.6
PydanticAI v0.2.6 adds
prepare_toolsparam to Agent and'openrouter'as a supported OpenAIModel provider.└──▷ GET THIS VERSION$ git clone --branch v0.2.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.6
└──▷ USE ITRoute LLM calls through OpenRouter using the existing OpenAIModel with the new'openrouter'provider string.from pydantic_ai.models.openai import OpenAIModel model = OpenAIModel('openai/gpt-4o', provider='openrouter')- ›Adds
prepare_toolsparameter to the Agent class, enabling dynamic control over which tools are presented to the model at runtime. - ›Supports
'openrouter'as a valid string value for theproviderparameter ofOpenAIModel, enabling routing through OpenRouter.
- ›Adds
- v0.2.5
PydanticAI v0.2.5 adds OpenRouter and Google GenAI providers, logprobs support, and new instrumentation controls.
└──▷ GET THIS VERSION$ git clone --branch v0.2.5 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.5
└──▷ USE ITSuppress binary content (images, files) from being sent to your OTel backend to reduce trace payload size.from pydantic_ai.settings import InstrumentationSettings settings = InstrumentationSettings(include_binary_content=False)
- ›Adds
include_binary_contentflag toInstrumentationSettingsto control whether binary content is captured in traces; renames the OTel attribute key fromcontenttobinary_contentforBinaryParts. - ›Adds
logprobsto OpenAI model settings and response objects, exposing token-level log probability data. - ›Adds
vendor_idfield to model response objects. - ›Adds ability to specify the evaluation name for all built-in Evaluators.
- ›Adds OpenRouter provider for routing requests across LLM backends.
+2 moreshow less
- ›Adds Google GenAI provider for direct integration with Google's generative AI APIs.
- ›Makes
capabilitiesa required field onAgentCardin the fasta2a integration.
└──▷ BREAKING ON UPGRADE- !The OTel attribute key for
BinaryParts is renamed fromcontenttobinary_content; any dashboards, queries, or processors filtering on the old key will stop matching. - !
capabilitiesis now required onAgentCardin fasta2a; existingAgentCardinstantiations that omitcapabilitieswill raise a validation error.
- ›Adds
- v0.2.3
PydanticAI v0.2.3 adds an A2A server, a
directpublic API, and model-settings support for LLMJudge.└──▷ GET THIS VERSION$ git clone --branch v0.2.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.3
- ›Adds
directpublic API for invoking models directly. - ›Adds an A2A (Agent-to-Agent) server, enabling agents to communicate via the A2A protocol.
- ›Allows
ModelSettingsto be defined on LLMJudge to control model behavior during evaluations.
- ›Adds
- v0.2.2
PydanticAI v0.2.2 adds a to_cli() method to Agent for instant command-line interfaces.
└──▷ GET THIS VERSION$ git clone --branch v0.2.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.2
└──▷ USE ITTurn an existing PydanticAI agent into a runnable CLI tool without writing argument-parsing boilerplate.agent = Agent(model='openai:gpt-4o', system_prompt='You are a helpful assistant.') if __name__ == '__main__': agent.to_cli()- ›Adds to_cli() method to the Agent class, enabling any agent to be exposed as a CLI application.
- v0.2.1
PydanticAI v0.2.1 adds AWS Profile support, CLI config persistence, and OpenTelemetry BinaryContent tracing.
└──▷ GET THIS VERSION$ git clone --branch v0.2.1 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.1
- ›CLI now stores prompt history and configuration under
~/.pydantic-aifor persistence across sessions. - ›OpenTelemetry integration now sends
BinaryContentinformation in traces. - ›Adds AWS Profile support for authenticating with AWS-backed models.
- ›Improves Agent.is_*_node() type narrowing by switching to
TypeIsfor more precise static analysis.
- ›CLI now stores prompt history and configuration under
- v0.2.0
PydanticAI v0.2.0 moves usage data into ModelResponse and adds non-string enum support for Gemini.
└──▷ GET THIS VERSION$ git clone --branch v0.2.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.2.0
└──▷ USE ITAccess token usage directly from a model response after the return-type change, instead of unpacking a tuple.response = await model.request(messages, model_request_parameters) print(response.usage)
- ›Adds
usagefield toModelResponse(defaults to Usage() for backward-compatible deserialization), making token/cost usage directly accessible on every model response and in message history sequences. - ›Adds support for non-string enums in Gemini model integrations.
└──▷ BREAKING ON UPGRADE- !The return type of
Model.requestchanged fromtuple[ModelResponse, Usage]toModelResponse— callers that unpack the two-element tuple will break; usage is now accessed viaresponse.usage.
- ›Adds
- v0.1.11
PydanticAI v0.1.11 renames the CLI entry point to
clai.└──▷ GET THIS VERSION$ git clone --branch v0.1.11 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.11
- ›Renames the CLI entry point to
clai, replacing the previous command name.
└──▷ BREAKING ON UPGRADE- !The CLI command is now
clai; any scripts or aliases invoking the old CLI name will break on upgrade.
- ›Renames the CLI entry point to
- v0.1.10
PydanticAI v0.1.10 adds extra_headers to ModelSettings and thinking_config to GeminiModel
└──▷ GET THIS VERSION$ git clone --branch v0.1.10 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.10
└──▷ USE ITAttach custom HTTP headers (e.g. for routing or auth) to every request made through a PydanticAI agent.from pydantic_ai import Agent from pydantic_ai.settings import ModelSettings agent = Agent( 'openai:gpt-4o', model_settings=ModelSettings(extra_headers={'X-Custom-Header': 'my-value'}) ) result = agent.run_sync('Hello')- ›Adds
extra_headersfield toModelSettingsto pass custom HTTP headers to model API calls. - ›Adds
thinking_configparameter toGeminiModelto control extended thinking behavior. - ›Allows setting
temperatureto0onBedrockConverseModelfor deterministic outputs.
- ›Adds
- v0.1.9
PydanticAI v0.1.9 adds base_url support for Mistral, richer Anthropic usage details, and multi-modal MCP tool call responses.
└──▷ GET THIS VERSION$ git clone --branch v0.1.9 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.9
└──▷ USE ITPoint the Mistral provider at a self-hosted or alternative Mistral-compatible endpoint instead of the default API.from pydantic_ai.providers.mistral import MistralProvider provider = MistralProvider(base_url='https://my-mistral-instance.example.com/v1')
- ›Adds
base_urlparameter to the Mistral provider, enabling custom or self-hosted Mistral endpoint configuration. - ›Stores additional usage details returned by Anthropic in the response metadata.
- ›Handles multi-modal and error responses from MCP tool calls, broadening the range of MCP tool outputs PydanticAI can process.
- ›Adds
- v0.1.8
PydanticAI v0.1.8 lets tools return multi-modal content such as images and audio alongside text.
└──▷ GET THIS VERSION$ git clone --branch v0.1.8 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.8
- ›Tools can now return multi-modal content (e.g. images, audio, binary data) directly from tool functions, not just text or structured data.
- v0.1.7
PydanticAI v0.1.7 adds Gemini video support, multi-instruction agents, and attribute docstrings on tools by default.
└──▷ GET THIS VERSION$ git clone --branch v0.1.7 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.7
- ›Sets
use_attribute_docstrings=Trueas the default on tools, so attribute-level docstrings are automatically used in tool schemas without explicit configuration. - ›Supports multiple
instructionson an Agent, with correct concatenation when more than one instruction is provided. - ›Adds Gemini video support, enabling video content to be passed to Gemini models via the PydanticAI message API.
- ›Sets
- v0.1.6
PydanticAI v0.1.6 adds OpenTelemetry tracing for AudioUrl, VideoUrl, DocumentUrl, and ImageUrl content.
└──▷ GET THIS VERSION$ git clone --branch v0.1.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.6
- ›OpenTelemetry spans now include
AudioUrl,VideoUrl,DocumentUrl, andImageUrlcontent metadata, enabling full observability over multimodal model interactions.
- ›OpenTelemetry spans now include
- v0.1.4
PydanticAI v0.1.4 adds MCP logging, o3/o4-mini support, and OpenAI document input types.
└──▷ GET THIS VERSION$ git clone --branch v0.1.4 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.4
└──▷ USE ITTarget OpenAI's o3 or o4-mini reasoning models in an agent definition.from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel agent = Agent(OpenAIModel('o3')) # or agent = Agent(OpenAIModel('o4-mini'))- ›Supports
DocumentUrlandBinaryContentdocument types for OpenAI provider inputs. - ›Adds support for OpenAI
o3ando4-minimodels. - ›Supports MCP logging and raises minimum MCP version requirement to
1.6.0. - ›Makes agent and graph runs serializable, enabling persistence and resumption of run state.
└──▷ BREAKING ON UPGRADE- !Minimum MCP version is now
1.6.0; installations using an older MCP version will break.
- ›Supports
- v0.1.3
PydanticAI v0.1.3 adds
extra_bodytoModelSettings, OpenTelemetry instruction spans, and Gemini 2.5 Flash support.└──▷ GET THIS VERSION$ git clone --branch v0.1.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.3
└──▷ USE ITPass provider-specific body parameters that PydanticAI does not natively expose, such as enabling extended thinking on a compatible model.from pydantic_ai import Agent from pydantic_ai.settings import ModelSettings agent = Agent( 'openai:gpt-4o', model_settings=ModelSettings(extra_body={'reasoning_effort': 'high'}) ) result = agent.run_sync('Explain quantum entanglement.') print(result.data)- ›Adds
extra_bodyfield toModelSettingsfor passing arbitrary additional body parameters to model API requests. - ›Adds OpenTelemetry span events for
instructions, making instruction content visible in traces. - ›Adds support for the
gemini-2.5-flash-preview-04-17model.
- ›Adds
- v0.1.2
PydanticAI v0.1.2 exposes
StdioServerParameters.cwdfor controlling MCP server working directories.└──▷ GET THIS VERSION$ git clone --branch v0.1.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.2
└──▷ USE ITLaunch an MCP stdio server from a specific working directory so relative paths in the server process resolve correctly.StdioServerParameters(command='npx', args=['-y', 'my-mcp-server'], cwd='/path/to/project')
- ›Exposes
StdioServerParameters.cwdparameter, allowing callers to set the working directory for stdio MCP server processes.
- ›Exposes
- v0.1.0
PydanticAI v0.1.0 renames result→output, adds VideoUrl for Bedrock, spans on run results, and an instructions parameter.
└──▷ GET THIS VERSION$ git clone --branch v0.1.0 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.1.0
└──▷ USE ITAccess OpenTelemetry spans attached to a run result for custom trace export or assertion in tests.result = await agent.run('Classify this alert.') for span in result.spans: print(span.name, span.start_time)- ›Adds
VideoUrlinput support toBedrockConverseModelfor passing video content to the Bedrock Converse API. - ›Adds additional configuration fields to
BedrockConverseModelfor the Bedrock Runtime API. - ›Adds
instructionsparameter to agents for supplying system-level instructions at call time. - ›Exposes
spansas an attribute on agent/graph runs and run results for OpenTelemetry trace access. - ›Adds support for
gemini-2.5-pro-preview-03-25(paid tier of Gemini 2.5 Pro).
+1 moreshow less
- ›Generalizes JSON schema transformations across model backends.
└──▷ BREAKING ON UPGRADE- !The
resultfield/attribute is renamed tooutputacross agent runs and run results — any code referencing.resultwill break on upgrade. - !
format_as_xmlhas been moved to a new location — imports referencing the old module path will break on upgrade.
- ›Adds
- v0.0.55
PydanticAI v0.0.55 allows empty user prompts in streaming runs and adds a PydanticAI User-Agent header to outbound requests.
└──▷ GET THIS VERSION$ git clone --branch v0.0.55 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.55
- ›Adds a
PydanticAIUser-Agent header to all outbound HTTP requests, enabling easier identification of traffic in server logs and API dashboards. - ›Supports empty
user_promptvalues inrun_stream, allowing streaming runs to be initiated with no user message.
- ›Adds a
- v0.0.54
PydanticAI v0.0.54 adds
stop_sequencestoModelSettings, optionaluser_prompt, and yields the initial graph node during iteration.└──▷ GET THIS VERSION$ git clone --branch v0.0.54 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.54
└──▷ USE ITStop model generation at a known delimiter — useful when parsing structured output from models that don't support native structured output.from pydantic_ai import Agent from pydantic_ai.settings import ModelSettings agent = Agent( 'openai:gpt-4o', model_settings=ModelSettings(stop_sequences=['---END---']), ) result = await agent.run('Summarize this document.') print(result.output)- ›Adds
stop_sequencesfield toModelSettingsto control where model output is terminated. - ›Makes
user_promptoptional, allowing agent invocations without a required user-facing prompt. - ›Graph (and therefore Agent) iteration now yields the initial node, giving callers visibility into the full execution sequence from the start.
- ›Adds
- v0.0.53
PydanticAI v0.0.53 adds OpenAI strict mode support for structured output.
└──▷ GET THIS VERSION$ git clone --branch v0.0.53 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.53
- ›Adds OpenAI strict mode support, enabling stricter schema enforcement when using OpenAI models for structured output generation.
- v0.0.52
PydanticAI v0.0.52 adds dependency injection support to the evals framework.
└──▷ GET THIS VERSION$ git clone --branch v0.0.52 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.52
- ›Enables passing dependencies into evals, bringing PydanticAI's dependency-injection model to the evaluation framework.
- v0.0.51
PydanticAI v0.0.51 switches mcp-run-python to Deno and aligns OpenAI model strictness.
└──▷ GET THIS VERSION$ git clone --branch v0.0.51 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.51
- ›Switches the
mcp-run-pythonserver runtime from its previous backend to Deno. - ›Matches OpenAI models in strictness, aligning structured-output enforcement with OpenAI's strict mode behavior.
- ›Switches the
- v0.0.49
PydanticAI v0.0.49 adds Gemini 2.5 Pro, OpenAI built-in tools, and new
OpenAIResponsesModelSettingsfields└──▷ GET THIS VERSION$ git clone --branch v0.0.49 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.49
└──▷ USE ITControl response summarization and truncation behaviour when using the OpenAI Responses API.from pydantic_ai.models.openai import OpenAIResponsesModelSettings settings = OpenAIResponsesModelSettings( generate_summary=True, truncation='auto' )- ›Adds
generate_summaryandtruncationfields toOpenAIResponsesModelSettingsfor controlling response summarization and context truncation. - ›Adds OpenAI built-in tools support, exposing OpenAI-native tool integrations through the PydanticAI interface.
- ›Adds Gemini 2.5 Pro model support alongside CLI improvements.
- ›Anthropic models now pass
ImageUrlandDocumentUrlreferences directly without downloading content, enabling more efficient media handling.
- ›Adds
- v0.0.48
PydanticAI v0.0.48 adds support for the OpenAI Responses API.
└──▷ GET THIS VERSION$ git clone --branch v0.0.48 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.48
- ›Adds support for the OpenAI Responses API, enabling PydanticAI agents to use OpenAI's newer stateful response interface.
- v0.0.47
PydanticAI v0.0.47 ships the new
pydantic-evalspackage, read/connect timeouts for Bedrock, and OpenTelemetry spans around tool calls.└──▷ GET THIS VERSION$ git clone --branch v0.0.47 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.47
- ›Adds
read_timeoutandconnect_timeoutsettings to the Bedrock provider for finer-grained network control. - ›Introduces the
pydantic-evalspackage, a new library for evaluating AI agent outputs. - ›Wraps every tool call in an OpenTelemetry span for deeper observability into agent execution.
- ›Supports passing a plain
stras the model argument, broadening how models can be specified at call sites. - ›Allows running under
PYTHONOPTIMIZE=1(stripped assertions) without errors.
- ›Adds
- v0.0.46
PydanticAI v0.0.46 adds headers, timeout, and SSE read timeout to MCPServerHTTP
└──▷ GET THIS VERSION$ git clone --branch v0.0.46 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.46
└──▷ USE ITConnect to an authenticated MCP server over HTTP with custom timeouts and authorization headers.MCPServerHTTP( url='https://mcp.example.com/sse', headers={'Authorization': 'Bearer <token>'}, timeout=30, sse_read_timeout=60 )- ›Adds
headers,timeout, andsse_read_timeoutparameters toMCPServerHTTPfor fine-grained control over HTTP MCP server connections. - ›Uses different HTTP clients based on providers, enabling provider-specific HTTP client behaviour.
- ›Adds
- v0.0.45
PydanticAI v0.0.45 adds
usermapping support in OpenAI chat completion requests.└──▷ GET THIS VERSION$ git clone --branch v0.0.45 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.45
- ›Adds
usermapping in OpenAI chat completion requests, allowing callers to pass a user identifier through to the OpenAI API.
- ›Adds
- v0.0.44
PydanticAI v0.0.44 adds a Cohere provider, exposes tool definitions on chat spans, and drops the
systemparameter fromOpenAIModel.└──▷ GET THIS VERSION$ git clone --branch v0.0.44 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.44
- ›Adds
model_request_parametersattribute (containing tool definitions) to chat spans, making tool configurations observable in traces. - ›Adds a Cohere provider class for inference, enabling PydanticAI agents to target Cohere models via the provider pattern.
- ›Migrates OpenAI models from
max_tokenstomax_completion_tokensin requests. - ›Adds function return docstrings to the generated tool description passed to models.
└──▷ BREAKING ON UPGRADE- !The
systemparameter is removed fromOpenAIModel; code that passessystem=toOpenAIModelwill break on upgrade.
- ›Adds
- v0.0.43
PydanticAI v0.0.43 adds a timestamp field to SystemPromptPart and auto-refreshes Google Vertex tokens on 401.
└──▷ GET THIS VERSION$ git clone --branch v0.0.43 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.43
- ›Adds
timestampfield toSystemPromptPart, enabling precise tracking of when system prompts were created. - ›Automatically recreates the access token on HTTP 401 responses for the Google Vertex provider, enabling uninterrupted long-running sessions.
- ›Adds
- v0.0.42
PydanticAI v0.0.42 adds MCP server support, a Python sandbox MCP server, and customizable tool JSON schema generation.
└──▷ GET THIS VERSION$ git clone --branch v0.0.42 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.42
- ›Renames
MCPServerSSEtoMCPServerHTTPfor connecting agents to MCP servers over HTTP (see breaking changes). - ›Adds support for MCP (Model Context Protocol) servers, allowing agents to connect to and use tools exposed via MCP.
- ›Adds a built-in MCP server for running Python code in a sandbox environment.
- ›Enables overriding JSON schema generation for tools, giving developers control over how tool parameters are described to the model.
└──▷ BREAKING ON UPGRADE- !
MCPServerSSEis renamed toMCPServerHTTP; any code referencingMCPServerSSEwill break on upgrade.
- ›Renames
- v0.0.41
PydanticAI v0.0.41 adds Anthropic and Mistral provider classes.
└──▷ GET THIS VERSION$ git clone --branch v0.0.41 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.41
- ›Adds Anthropic provider classes for direct integration with Anthropic models.
- ›Adds Mistral provider classes for direct integration with Mistral models.
- v0.0.40
PydanticAI v0.0.40 adds AzureProvider, env-var base URL for OpenAIProvider, state persistence, and Anthropic PDF support.
└──▷ GET THIS VERSION$ git clone --branch v0.0.40 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.40
- ›Adds
AzureProviderclass for connecting PydanticAI agents to Azure-hosted OpenAI deployments. - ›Adds environment variable support for base URL configuration in
OpenAIProvider, removing the need to hard-code endpoints. - ›Adds state persistence support, enabling agents to save and restore conversational state across runs.
- ›Adds PDF document support to the Anthropic provider, allowing PDF content to be passed as model input.
- ›Adds
- v0.0.39
PydanticAI v0.0.39 adds Groq provider classes for LLM integration.
└──▷ GET THIS VERSION$ git clone --branch v0.0.39 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.39
- ›Adds Groq provider classes, enabling Groq-hosted models as a PydanticAI LLM backend.
- v0.0.38
PydanticAI v0.0.38 adds DocumentUrl and BinaryContent document support for passing documents to models.
└──▷ GET THIS VERSION$ git clone --branch v0.0.38 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.38
- ›Adds
DocumentUrlclass to pass documents to models by URL. - ›Adds document support via
BinaryContentfor passing raw binary document data to models.
- ›Adds
- v0.0.37
PydanticAI v0.0.37 adds
base_urlto models, tool name override on decorators, and VertexAI pre-loaded service account support.└──▷ GET THIS VERSION$ git clone --branch v0.0.37 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.37
- ›Adds
base_urlparameter to models, and populatesserver.addressandserver.portfields in OpenTelemetry spans for tracing. - ›Allows specifying a custom tool name when registering a function with the tool decorator.
- ›Supports pre-loaded VertexAI service account info, removing the need to read credentials from disk at runtime.
- ›Serializes
bytesvalues as base64 automatically when converting to JSON.
- ›Adds
- v0.0.36
PydanticAI v0.0.36 adds AWS Bedrock Converse API support and expands VertexAI region coverage.
└──▷ GET THIS VERSION$ git clone --branch v0.0.36 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.36
- ›Adds support for the AWS Bedrock Converse API as a new model backend.
- ›Expands
VertexAIRegionLiteral with updated region URLs for broader Vertex AI regional coverage.
- v0.0.34
PydanticAI v0.0.34 adds Agent.instrument_all(), a
paiCLI, and tool names in response events.└──▷ GET THIS VERSION$ git clone --branch v0.0.34 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.34
└──▷ USE ITInstrument every agent in your application at startup without modifying each agent definition.from pydantic_ai import Agent Agent.instrument_all()
- ›Adds Agent.instrument_all() class method to instrument all agents globally by default, without configuring each agent individually.
- ›Adds
paiCLI for interacting with PydanticAI from the command line. - ›Adds tool name to tool response events, making it easier to identify which tool produced a given response in streaming or event-driven workflows.
- v0.0.33
PydanticAI v0.0.33 introduces a new Providers API for configuring model backends.
└──▷ GET THIS VERSION$ git clone --branch v0.0.33 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.33
- ›Adds a Providers API for configuring and supplying model backends to agents.
- v0.0.32
PydanticAI v0.0.32 adds an
instrumentparam to Agent, supports Claude Sonnet 3.7 and Gemini 2.0 Pro Exp.└──▷ GET THIS VERSION$ git clone --branch v0.0.32 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.32
└──▷ USE ITRe-enable OpenTelemetry tracing for an agent after the default changed to off.agent = Agent('openai:gpt-4o', instrument=True)- ›Adds
instrumentparam to Agent to opt into OpenTelemetry tracing explicitly, replacing the previous always-on auto-instrumentation. - ›Adds support for
claude-sonnet-3-7model. - ›Adds support for
gemini-2.0-pro-exp-02-05model.
└──▷ BREAKING ON UPGRADE- !OpenTelemetry instrumentation is now DISABLED by default; agents that relied on automatic tracing must now pass
instrument=Trueto Agent(...) explicitly to restore telemetry.
- ›Adds
- v0.0.31
PydanticAI v0.0.31 adds recursive return types, async graph iteration, and improved OpenTelemetry instrumentation.
└──▷ GET THIS VERSION$ git clone --branch v0.0.31 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.31
└──▷ USE ITIterate over graph execution asynchronously using the new asyncGraph.itercontext manager.async with my_graph.iter(initial_state) as graph_run: async for node in graph_run: print(node)- ›Supports recursive objects in
return_type, enabling agents to return self-referential data structures. - ›Makes
Graph.iteran async context manager, enabling asynchronous iteration over graph execution. - ›Replaces the
model requestspan withInstrumentedModelfor more structured OpenTelemetry tracing. - ›Replaces
all_messagesin the agent span withall_messages_events, aligning its format with theInstrumentedModelspan.
└──▷ BREAKING ON UPGRADE- !
HandleResponseNodeis renamed toCallToolsNode— any code referencingHandleResponseNodeby name will break. - !
Graph.iteris now an async context manager — code using it as a sync context manager will break. - !The
model requestspan is replaced byInstrumentedModel— any telemetry pipelines filtering on themodel requestspan name will no longer receive it. - !The
all_messagesfield in the agent span is replaced byall_messages_events— any telemetry pipelines readingall_messagesfrom agent spans will no longer find it.
- ›Supports recursive objects in
- v0.0.30
PydanticAI v0.0.30 adds GPT-4.5 support, attributes mode for InstrumentedModel, and richer TestModel content inputs.
└──▷ GET THIS VERSION$ git clone --branch v0.0.30 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.30
└──▷ USE ITUse the new GPT-4.5 preview model in an agent when you want to leverage OpenAI's latest capabilities.from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel model = OpenAIModel('gpt-4.5-preview') agent = Agent(model=model) result = agent.run_sync('Summarize the threat landscape for Q1 2025.') print(result.data)- ›Adds
gpt-4.5-previewas a supported model name forOpenAIModel. - ›Adds attributes mode to
InstrumentedModelfor OpenTelemetry instrumentation. - ›Supports different content input types in
TestModelfor richer test scenarios. - ›Replaces the existing streaming implementation with the .iter() API.
- ›Adds
- v0.0.29
PydanticAI v0.0.29 adds
max_resultsparameter to the DuckDuckGo search tool.└──▷ GET THIS VERSION$ git clone --branch v0.0.29 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.29
└──▷ USE ITLimit DuckDuckGo search results to a specific count to reduce token usage and focus agent context.from pydantic_ai.tools.duckduckgo import DuckDuckGoSearchTool tool = DuckDuckGoSearchTool(max_results=5)
- ›Adds
max_resultsparameter to the DuckDuckGo search tool to control the number of results returned per query.
- ›Adds
- v0.0.28
PydanticAI v0.0.28 adds DuckDuckGo and Tavily search tools, exposes
tool_call_idonRunContext, and broadens Anthropic image MIME support.└──▷ GET THIS VERSION$ git clone --branch v0.0.28 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.28
└──▷ USE ITAccess thetool_call_idinside a tool to correlate a tool invocation with its call context for logging or deduplication.from pydantic_ai import Agent, RunContext agent = Agent('openai:gpt-4o') @agent.tool async def my_tool(ctx: RunContext[None], query: str) -> str: call_id = ctx.tool_call_id # new in v0.0.28 print(f'Handling call {call_id} for query: {query}') return f'result for {query}'- ›Adds
tool_call_idfield toRunContext, giving tool implementations access to the specific call ID during execution. - ›Adds
DuckDuckGoSearchbuilt-in tool for agent web search without an API key. - ›Adds
TavilySearchbuilt-in tool for agent web search via the Tavily API. - ›Broadens accepted MIME types for
ImageUrlwhen using Anthropic models, enabling a wider range of image formats.
- ›Adds
- v0.0.27
PydanticAI v0.0.27 adds FallbackModel for automatic model failover
└──▷ GET THIS VERSION$ git clone --branch v0.0.27 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.27
└──▷ USE ITChain multiple LLM providers so your agent automatically retries with the next model on failure.from pydantic_ai import Agent from pydantic_ai.models.fallback import FallbackModel from pydantic_ai.models.openai import OpenAIModel from pydantic_ai.models.anthropic import AnthropicModel model = FallbackModel(OpenAIModel('gpt-4o'), AnthropicModel('claude-3-5-sonnet-latest')) agent = Agent(model=model) result = agent.run_sync('Summarize this report.') print(result.data)- ›Adds
FallbackModelclass to enable automatic failover across multiple LLM backends when a model call fails.
- ›Adds
- v0.0.26
PydanticAI v0.0.26 adds multimodal input support for agents.
└──▷ GET THIS VERSION$ git clone --branch v0.0.26 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.26
- ›Adds multimodal input support, enabling agents to accept non-text content (e.g. images, audio) alongside text messages.
- v0.0.25
PydanticAI v0.0.25 adds InstrumentedModel with OTel/streaming support and a new GraphRun object for ergonomic agent graph traversal.
└──▷ GET THIS VERSION$ git clone --branch v0.0.25 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.25
└──▷ USE ITWrap an existing model with OpenTelemetry instrumentation to trace all LLM calls in your agent.from pydantic_ai import Agent from pydantic_ai.models.instrumented import InstrumentedModel from pydantic_ai.models.openai import OpenAIModel base_model = OpenAIModel('gpt-4o') instrumented = InstrumentedModel(base_model) agent = Agent(instrumented) result = await agent.run('Summarize this document.')- ›Adds
InstrumentedModelclass to wrap any model with OpenTelemetry instrumentation, using raw OTel and actual event loggers. - ›Adds
request_streamsupport toInstrumentedModel, enabling streaming calls alongside standard instrumented requests. - ›Adds
GraphRunobject to make use ofnextmore ergonomic when iterating agent graph execution. - ›Adds placeholder API key support for OpenAI-compatible models, easing integration with local or third-party OpenAI-compatible endpoints.
└──▷ BREAKING ON UPGRADE- !The
namemethods are removed from OpenAI and Mistral model classes; any code calling those methods will break on upgrade.
- ›Adds
- v0.0.24
PydanticAI v0.0.24 adds Gemini 2.0 production models and populates
ModelResponse.model_name from live responses.└──▷ GET THIS VERSION$ git clone --branch v0.0.24 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.24
- ›Populates
ModelResponse.model_nameautomatically from actual model responses, giving agents visibility into which model variant handled a request. - ›Adds new Gemini 2.0 models for production use.
- ›Populates
- v0.0.23
PydanticAI v0.0.23 adds o3 model support, OpenAI reasoning_effort param, and Gemini safety settings.
└──▷ GET THIS VERSION$ git clone --branch v0.0.23 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.23
└──▷ USE ITCap reasoning cost on an o3 agent by settingreasoning_effortto 'low', 'medium', or 'high'.from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel model = OpenAIModel('o3', reasoning_effort='medium') agent = Agent(model) result = agent.run_sync('Explain zero-day vulnerability triage strategies.') print(result.data)- ›Supports
reasoning_effortparameter forOpenAIModel, enabling control over reasoning depth on compatible OpenAI models. - ›Adds
o3model support toOpenAIModel. - ›Adds Gemini safety settings support for configuring content safety thresholds on Gemini models.
└──▷ BREAKING ON UPGRADE- !The
AgentModelclass has been removed.
- ›Supports
- v0.0.22
PydanticAI v0.0.22 adds new Gemini experimental models and support for locally served models without API keys.
└──▷ GET THIS VERSION$ git clone --branch v0.0.22 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.22
- ›Supports locally served models that do not require an API key, enabling use of self-hosted LLM endpoints.
- ›Adds new Gemini experimental models to the supported model list.
- ›Ports
pydantic_ai.Agentinternals to usepydantic_graphas its execution backend.
- v0.0.21
PydanticAI v0.0.21 adds model-specific ModelSettings subclasses, drops OllamaModel in favor of OpenAIModel, and adds Cohere support.
└──▷ GET THIS VERSION$ git clone --branch v0.0.21 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.21
- ›Adds subclasses of
ModelSettingsto support specialized, per-model request parameters beyond the base settings common to all models. - ›Removes
OllamaModel— Ollama is now used viaOpenAIModelwith the appropriate base URL, consolidating provider support. - ›Adds Cohere model support with documentation and live tests.
└──▷ BREAKING ON UPGRADE- !
OllamaModelhas been removed; existing code usingOllamaModelmust be migrated to useOpenAIModelwith Ollama's OpenAI-compatible endpoint. - !
ArgsDictandArgsJsonhave been removed from the public API. - !
AgentDepstype alias is renamed toAgentDepsT.
- ›Adds subclasses of
- v0.0.20
PydanticAI v0.0.20 adds Cohere model support, Anthropic streaming, parallel tool calls, and DeepSeek-R1 via Ollama.
└──▷ GET THIS VERSION$ git clone --branch v0.0.20 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.20
└──▷ USE ITDisable parallel tool calls when you need strict sequential tool execution, e.g. to avoid race conditions on shared state.from pydantic_ai import Agent from pydantic_ai.settings import ModelSettings agent = Agent('openai:gpt-4o', model_settings=ModelSettings(parallel_tool_calls=False)) result = agent.run_sync('Book a flight and then a hotel')- ›Adds
parallel_tool_callsfield toModelSettingsto control whether the model may invoke multiple tools simultaneously. - ›Adds
model_namefield toModelResponse, exposing which model produced each response. - ›Adds support for Cohere models as a new model provider integration.
- ›Adds
'deepseek-r1'to the recognized Ollama model name list, enabling typed use of DeepSeek-R1 via Ollama. - ›Adds Anthropic streaming support, enabling streamed responses from Anthropic models.
+2 moreshow less
- ›Adds support for
user-rolesystem prompts foro1-preview-2024-09-12to work around that model's system-prompt restrictions. - ›Adds direction control for Mermaid state diagram generation.
└──▷ BREAKING ON UPGRADE- !Removes
from_textandfrom_tool_callutilities, which will break any code that imports or calls these methods.
- ›Adds
- v0.0.19
PydanticAI v0.0.19 adds graph support, tool docstring controls, streaming refactor, and phi4 on Ollama.
└──▷ GET THIS VERSION$ git clone --branch v0.0.19 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.19
- ›Adds
docstring_formatandrequire_parameter_descriptionsparameters to tool definitions, giving callers explicit control over how tool schemas are generated from Python docstrings. - ›Introduces graph support via
pydantic_ai.graph, enabling stateful, multi-step agent workflows modelled as explicit graphs. - ›Adds
phi4model support to the Ollama provider. - ›Refactors streaming internals, improving the reliability and composability of streamed agent responses.
- ›Adds
- v0.0.18
PydanticAI v0.0.18 adds dynamic system prompts, per-run custom result types, and provider-prefixed model names.
└──▷ GET THIS VERSION$ git clone --branch v0.0.18 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.18
└──▷ USE ITRe-evaluate a system prompt on every run to inject fresh context such as the current user or timestamp.@agent.system_prompt(dynamic=True) def my_prompt(ctx: RunContext) -> str: return f"Today is {date.today()}. User: {ctx.deps.username}"Override the expected result type for a single run without redefining the agent — useful for multi-step pipelines with varying output schemas.result = await agent.run("Summarise this", result_type=MySummaryModel)- ›Adds
dynamicparameter to thesystem_promptdecorator, enabling system prompts to be re-evaluated on each agent run rather than computed once at definition time. - ›Supports custom
result_typeoverrides on individual .run() calls, allowing the expected output type to be set per-run without changing the agent definition. - ›All model names are now prefixed with their provider (e.g.
openai:gpt-4o) for consistency across providers.
└──▷ BREAKING ON UPGRADE- !All models are now prefixed with their provider name for consistency — any hardcoded unprefixed model strings passed to agents may need to be updated to the new provider-prefixed format.
- ›Adds
- v0.0.17
PydanticAI v0.0.17 defaults AgentDeps to None and adds formatting examples support
└──▷ GET THIS VERSION$ git clone --branch v0.0.17 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.17
- ›Adds formatting examples support to improve how examples are structured and displayed.
- ›
AgentDepsnow defaults to None, simplifying agent definitions that do not require explicit dependency typing.
- v0.0.16
PydanticAI v0.0.16 adds multi-agent support, extends RunContext, and brings Ollama API key config and nested capture_run_messages.
└──▷ GET THIS VERSION$ git clone --branch v0.0.16 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.16
- ›Adds
capture_run_messagessupport for nested agent calls, enabling message capture across multi-agent workflows. - ›Extends
RunContextwith additional fields/methods to expose more context inside tool and result functions. - ›Adds Ollama API key configuration support for authenticating against Ollama endpoints.
- ›Introduces multi-agent usage patterns, allowing agents to delegate to or call other agents.
- ›Adds support for
X | None = Noneoptional type annotations with the Gemini provider.
- ›Adds
- v0.0.15
PydanticAI v0.0.15 adds
capture_run_messagesfor message capture and optimizes Mistral model support.└──▷ GET THIS VERSION$ git clone --branch v0.0.15 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.15
- ›Adds
capture_run_messagesto replacelast_run_messagesfor capturing run messages. - ›Adds a default to
ResultDataso agents no longer require an explicit result-type argument. - ›Optimizes Mistral model integration for improved performance.
- ›Tool calls are now prioritized over eager text responses when a model returns both.
└──▷ BREAKING ON UPGRADE- !
last_run_messagesis removed; replace all uses withcapture_run_messages.
- ›Adds
- v0.0.14
PydanticAI v0.0.14 adds usage limits, renames Cost to Usage, and supports the openai:o1 model.
└──▷ GET THIS VERSION$ git clone --branch v0.0.14 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.14
- ›Renames Cost to Usage across the library — callers must update any references to the old name.
- ›Adds support for usage limits via the new Usage tracking infrastructure.
- ›Adds
openai:o1model support.
└──▷ BREAKING ON UPGRADE- !Cost is renamed to Usage — any code referencing Cost will break on upgrade.
- v0.0.13
PydanticAI v0.0.13 adds Mistral and Anthropic support, new ModelSettings, Gemini 2.0 Flash, and a reworked message format.
└──▷ GET THIS VERSION$ git clone --branch v0.0.13 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.13
└──▷ USE ITPoint an OpenAI-compatible agent at a local or self-hosted inference server without changing the rest of your agent code.from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel model = OpenAIModel('llama-3', base_url='http://localhost:11434/v1') agent = Agent(model) result = agent.run_sync('Summarize the threat report.') print(result.data)Use the new Mistral provider to run an agent against a Mistral model.from pydantic_ai import Agent from pydantic_ai.models.mistral import MistralModel agent = Agent(MistralModel('mistral-large-latest')) result = agent.run_sync('List the top 5 OWASP API risks.') print(result.data)- ›Adds
base_urlkwarg toOpenAIModelto point the client at any OpenAI-compatible endpoint (e.g. local or self-hosted inference servers). - ›Adds
messagesfield toRunContextso tool functions can inspect the full conversation history mid-run. - ›Adds
ToolReturnPartmessage part topydantic_ai.messages, emitted for every tool call result and included in the message stream. - ›Adds basic
ModelSettingsclass for passing model-level configuration (temperature, etc.) to agent runs. - ›Adds Mistral model support as a new first-class provider.
+6 moreshow less
- ›Adds non-streaming Anthropic model support.
- ›Adds
gemini-2.0-flash-expto the supported Gemini model names. - ›Adds
llama-3.3-70b-versatiletoGroqModelName. - ›Supports tool calling when a structured result type is also provided, allowing both to be used simultaneously.
- ›Reformats message history as a simple
list[ModelRequest | ModelResponse], unifying request and response representations across all providers. - ›Streamed response messages are now captured and included in the message history.
└──▷ BREAKING ON UPGRADE- !The message format has changed significantly; existing stored or serialized messages are incompatible with the new
list[ModelRequest | ModelResponse]structure. - !
ToolReturnPartis now emitted for every tool call, adding more message parts than previous releases — code that iterates or counts message parts will see different results. - !The field
tool_idhas been renamed totool_call_idacross message types.
- ›Adds
- v0.0.12
PydanticAI v0.0.12 adds Ollama support, dynamic tools, and tool-result generation for structured outputs.
└──▷ GET THIS VERSION$ git clone --branch v0.0.12 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.12
- ›Adds Ollama as a supported model provider, enabling local LLM inference within PydanticAI agents.
- ›Introduces dynamic tools, allowing tool definitions to be resolved or modified at runtime rather than statically at agent construction.
- ›Enables tool-result generation when using structured result types, so structured-output workflows now produce proper tool result messages alongside the response.
- v0.0.10
PydanticAI v0.0.10 adds Agent.name for identifying agents in traces and logs.
└──▷ GET THIS VERSION$ git clone --branch v0.0.10 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.10
└──▷ USE ITAssign a name to an agent so it appears identifiably in Logfire traces or logs.from pydantic_ai import Agent agent = Agent('openai:gpt-4o', name='support-agent')- ›Adds
Agent.nameattribute to label agent instances, enabling identification in observability output.
- ›Adds
- v0.0.9
PydanticAI v0.0.9 lets you register tools at Agent construction time and return any type from tool functions.
└──▷ GET THIS VERSION$ git clone --branch v0.0.9 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.9
- ›Adds
toolsparameter to Agent(tools_=[...]) constructor, allowing tools to be registered at instantiation rather than only via decorators. - ›Allows tool functions to return Any type, removing the previous restriction that tool return values had to be a specific type.
- ›Adds
- v0.0.6
PydanticAI v0.0.6 adds Vertex AI and Groq provider support, plus a slim install option.
└──▷ GET THIS VERSION$ git clone --branch v0.0.6 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.6
- ›Adds
VertexAImodel support, including recognition of Vertex AI models ininfer_model. - ›Adds Groq client support as a new LLM provider.
- ›Introduces
pydantic-ai-slimas a minimal install target via uv workspaces, with OpenAI now an optional dependency.
- ›Adds
- v0.0.3
PydanticAI v0.0.3 adds streamed responses, dependency override support, and expanded Gemini model coverage.
└──▷ GET THIS VERSION$ git clone --branch v0.0.3 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.3
- ›Adds streamed response support, enabling agents to consume model output incrementally as it arrives.
- ›Allows overriding dependencies at runtime (e.g. in testing) via the new dependency override mechanism.
- ›Changes Agent initialization to accept a deps type rather than a deps instance, decoupling agent definition from runtime dependencies.
- ›Expands Gemini model coverage with additional test and integration support.
- ›Adds a chat application example with streaming support to the examples library.
└──▷ BREAKING ON UPGRADE- !The Agent constructor now takes a deps type instead of a deps instance — existing code passing a deps object directly will need to be updated.
- !
ToolCallhas been renamed to Structured in most places — code referencingToolCallby name will break.
- v0.0.2
PydanticAI v0.0.2 adds timezone support and
TypeAliasTypeunion handling.└──▷ GET THIS VERSION$ git clone --branch v0.0.2 https://github.com/pydantic/pydantic-ai.git # already have the repo? check out this version: $ git checkout v0.0.2
- ›Supports
TypeAliasTypeunions, allowing type aliases defined with Python'sTypeAliasTypeto be used in agent result schemas and tool signatures. - ›Adds timezone support to datetime handling within agents.
- ›Supports