Building Pydantic AI Agents
docling-project/docling
Patterns and tested examples for building agents with Pydantic AI: tools, capabilities, structured output, dependency injection, hooks, YAML specs, streaming and testing.
Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns.
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agents --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .claude/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .claude/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .claude/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agentsType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agents --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .agents/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .agents/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .agents/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agents --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .cursor/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .cursor/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/pydantic/pydantic-ai.git --path pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agents --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .gemini/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .gemini/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agentsInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .github/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .github/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .github/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install pydantic/pydantic-ai building-pydantic-ai-agents --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/pydantic/pydantic-ai.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents .opencode/skills/building-pydantic-ai-agents && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "building-pydantic-ai-agents" agent skill from https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents into .opencode/skills/building-pydantic-ai-agents/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "building-pydantic-ai-agents", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
building-pydantic-ai-agentsBuild AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns.
Building Pydantic AI Agents is an agent skill from pydantic/pydantic-ai, published by the product's own GitHub organization. Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns. Use when the user mentions Pydantic AI, imports pydanticai, or asks to build an AI agent, add tools/capabilities, attach a workspace, defer capability loading, stream output, define agents from YAML, or test agent behavior.
Its SKILL.md is about 8.2k tokens, which your agent loads only when the skill is triggered. The skill folder holds 13 other files, including reference files (for example `references/AGENTS-CORE.md`, `references/ARCHITECTURE.md` and `references/CAPABILITIES-AND-HOOKS.md`). Compatibility notes: Requires Python 3.11+
It sits in AI & LLM Engineering, covering Structured output and tool calling and Building AI agents. It works with Pydantic AI and Pydantic. The repository describes itself as: How Python does AI. Agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end. The licence is MIT.
Read from SKILL.md and the folder at commit 69ea1e5. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Shell commands in SKILL.md call:
uvxFrom the folder's file list and the shell code blocks in SKILL.md.
Links to these hosts (documentation or services it may open):
pydantic.devFrom URLs in SKILL.md, links to its own repository left out.
Names these keys or tokens, usually read from environment variables:
LOGFIRE_TOKENPYDANTIC_AI_GATEWAY_API_KEYFrom names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Requires Python 3.11+
From compatibility in the SKILL.md frontmatter.
Building Pydantic AI Agents loads about 8.2k tokens when it runs, and up to ~40k if it reads all its reference files. Until then it costs about 104 tokens; SKILL.md has 3,201 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check found no risky patterns in SKILL.md.
Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.
The full file from pydantic/pydantic-ai at commit 69ea1e5, republished under its MIT licence (© pydantic). 3,201 words, ~8,189 tokens.
.claude/skills/building-pydantic-ai-agents/SKILL.md (or your agent's skills folder). This skill also uses 12 other files; get the full folder from GitHub.Pydantic AI is a Python agent framework for building production-grade Generative AI applications. This skill provides patterns, architecture guidance, and tested code examples for building applications with Pydantic AI.
Invoke this skill when:
pydantic_ai or references Pydantic AI classes (Agent, RunContext, Tool)Do not use this skill for:
pydantic/BaseModel without agents)Start new applications with Logfire instrumentation and prompt caching in place, so the first run is already visible and repeated prompt prefixes are read from the cache (see Set Up Observability and Model Access for credentials and alternatives):
import logfire
from pydantic_ai import Agent
from pydantic_ai.capabilities import Caching
logfire.configure()
logfire.instrument_pydantic_ai()
agent = Agent(
'anthropic:claude-fable-5-1',
name='hello_world_agent',
instructions='Be concise, reply with one sentence.',
capabilities=[Caching()],
)
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""When you create a new Pydantic AI application, set up observability as part of the first working version, as in the starter above, so the user can see every agent run, model request, tool call, and its token cost. Default to Pydantic Logfire: the logfire SDK is included with pydantic-ai (with pydantic-ai-slim, add the logfire extra), and Logfire has a free tier that needs no credit card; the user can sign up with just a GitHub account.
uvx logfire auth once (it opens a browser), then uvx logfire projects new (or uvx logfire projects use for an existing project), which writes a .logfire/ directory that logfire.configure() reads. In CI, containers, and deployments, set LOGFIRE_TOKEN to a project write token instead. Never print, log, or commit a token. Without either, logfire.configure() raises an error (or prompts, in a terminal), so before the first run check for .logfire/ or LOGFIRE_TOKEN, and if neither exists ask the user to run uvx logfire auth and uvx logfire projects new. Do not silence it with send_to_logfire=False or 'if-token-present' unless the user chose not to use Logfire: once instrumentation is configured, Pydantic AI no longer prints its first-run hint about observability, so nothing would tell the user their runs are not being recorded.gateway/anthropic:claude-fable-5-1. The Pydantic AI Gateway is one API key for models from OpenAI, Anthropic, Google Cloud, Groq, and AWS Bedrock, with spending limits and cost monitoring, managed in Logfire. Use gateway/<api_format>:<model> model strings and set PYDANTIC_AI_GATEWAY_API_KEY; the key is created in the organization's Gateway settings in Logfire. Suggest it when the user has no provider key yet or wants to compare providers. If the user already has a provider key, the direct provider:model string (for example openai:gpt-6-sol) works with no Gateway.import random
from pydantic_ai import Agent, RunContext
agent = Agent(
'google:gemini-3-flash-preview',
name='dice_game_agent',
deps_type=str,
instructions=(
"You're a dice game, you should roll the die and see if the number "
"you get back matches the user's guess. If so, tell them they're a winner. "
"Use the player's name in the response."
),
)
@agent.tool_plain
def roll_dice() -> str:
"""Roll a six-sided die and return the result."""
return str(random.randint(1, 6))
@agent.tool
def get_player_name(ctx: RunContext[str]) -> str:
"""Get the player's name."""
return ctx.deps
dice_result = agent.run_sync('My guess is 4', deps='Anne')
print(dice_result.output)
#> Congratulations Anne, you guessed correctly! You're a winner!from pydantic import BaseModel
from pydantic_ai import Agent
class CityLocation(BaseModel):
city: str
country: str
agent = Agent('google:gemini-3-flash-preview', name='city_location_agent', output_type=CityLocation)
result = agent.run_sync('Where were the olympics held in 2012?')
print(result.output)
#> city='London' country='United Kingdom'
print(result.usage)
#> RunUsage(cost=Decimal('0.0000525'), input_tokens=57, output_tokens=8, requests=1)from datetime import UTC, datetime
from pydantic_ai import Agent, RunContext
agent = Agent(
'openai:gpt-5.2',
name='greeting_agent',
deps_type=str,
instructions="Use the customer's name while replying to them.",
)
@agent.instructions
def add_the_users_name(ctx: RunContext[str]) -> str:
return f"The user's name is {ctx.deps}."
@agent.instructions
def add_the_date() -> str:
return f'The date is {datetime.now(UTC).date()}.'
result = agent.run_sync('What is the date?', deps='Frank')
print(result.output)
#> Hello Frank, the date today is 2032-01-02.from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
my_agent = Agent('openai:gpt-5.2', name='my_agent', instructions='...')
async def test_my_agent():
"""Unit test for my_agent, to be run by pytest."""
m = TestModel()
with my_agent.override(model=m):
result = await my_agent.run('Testing my agent...')
assert result.output == 'success (no tool calls)'
assert m.last_model_request_parameters.function_tools == []Capabilities are reusable, composable units of agent behavior — bundling tools, hooks, instructions, and model settings.
from pydantic_ai import Agent
from pydantic_ai.capabilities import Thinking, WebSearch
agent = Agent(
'anthropic:claude-opus-4-6',
name='research_assistant_agent',
instructions='You are a research assistant. Be thorough and cite sources.',
capabilities=[
Thinking(effort='high'),
WebSearch(),
],
)Use Hooks to intercept model requests, tool calls, and runs with decorators — no subclassing needed.
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities.hooks import Hooks
from pydantic_ai.models import ModelRequestContext
hooks = Hooks()
@hooks.on.before_model_request
async def log_request(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext:
print(f'Sending {len(request_context.messages)} messages')
return request_context
agent = Agent('openai:gpt-5.2', name='hooks_agent', capabilities=[hooks])For a custom capability hook that performs I/O under Temporal, DBOS, or Prefect, mark a fixed method with @durable_operation(name='...'). The required name becomes part of persisted durable-unit names, so keep it stable even if the Python method is renamed. For dynamically contributed handlers, return them from get_durable_operations() and invoke a typed handle with ctx.durable_operation(self, name, handler). Always set a stable capability id; without a durability capability both forms call the original async handler directly. Arguments and results must be serializable like durable tool inputs and outputs.
Use Agent.from_file to load agents from YAML or JSON — no Python agent construction code needed.
from pydantic_ai import Agent
# agent.yaml:
# model: anthropic:claude-opus-4-6
# instructions: You are a helpful research assistant.
# capabilities:
# - WebSearch
# - Thinking:
# effort: high
agent = Agent.from_file('agent.yaml')For voice models that stream audio over a persistent connection (OpenAI Realtime, Azure OpenAI,
Gemini Live, or xAI Grok Voice), use
agent.realtime().session() instead of run(). It reuses the agent's tools and instructions and runs
the tool loop for you. Stream input with send_audio/send, and iterate the
session to consume the same part/event vocabulary as a streamed run — PartStartEvent /
PartDeltaEvent / PartEndEvent carrying SpeechParts and ToolCallParts, plus
FunctionToolCallEvent / FunctionToolResultEvent, plus realtime control events (RealtimeInputSpeechStartEvent,
RealtimeInputSpeechEndEvent, RealtimeResponseInterruptedEvent, ...). Use RealtimeTurnCompleteEvent as the exchange
boundary, when generation and tool work are complete. This is not always the end of audible speech:
on WebRTC sidebands, track playback with RealtimeOutputSpeechStartEvent and RealtimeOutputSpeechEndEvent. Before
passing raw microphone bytes to send_audio, convert them to mono PCM16 at session.audio_input_sample_rate; raw
chunks carry no sample-rate metadata.
After RealtimeTurnCompleteEvent (or a greeting's finalized SpeechPart), await
session.wait_for_playback() before closing the session or opening the microphone. It waits for the single
device-paced stream_audio() view to account for all audio emitted so far — played, discarded on a barge-in or a
full buffer, or emitted before the view subscribed; it requires exactly one audio view.
import anyio
from pydantic_ai import Agent
from pydantic_ai.messages import (
PartDeltaEvent,
PartEndEvent,
SpeechPart,
SpeechPartDelta,
)
from pydantic_ai.realtime import RealtimeSessionErrorEvent, RealtimeTurnCompleteEvent
from pydantic_ai.realtime.openai import OpenAIRealtimeModelSettings
agent = Agent(instructions='You are a helpful voice assistant.')
async def main(microphone_chunk: bytes):
settings = OpenAIRealtimeModelSettings(openai_voice='alloy', turn_detection=False)
async with agent.realtime(
'openai:gpt-realtime', model_settings=settings
).session() as session:
# The chunk must already be mono PCM16 at `session.audio_input_sample_rate`.
await session.send_audio(microphone_chunk)
await session.commit_audio()
await session.create_response()
# Input transcription can finish after the model exchange. Give it a
# bounded grace period so a missing transcript cannot hang the session.
turn_complete = user_turn_complete = False
with anyio.move_on_after(None) as transcript_wait:
async for event in session:
match event:
case PartDeltaEvent(delta=SpeechPartDelta(audio_chunk=chunk)) if chunk:
... # play audio out
case PartEndEvent(part=SpeechPart(speaker='user', transcript=t)):
if t is not None:
print('user said:', t)
user_turn_complete = True
case RealtimeTurnCompleteEvent():
turn_complete = True
transcript_wait.deadline = anyio.current_time() + 1
case RealtimeSessionErrorEvent(message=message, recoverable=True):
# The connection remains usable, but this turn may not complete.
raise RuntimeError(message)
if turn_complete and user_turn_complete:
break
# A session builds ordinary ModelMessage history: hand it off to a text agent.
notes = Agent('openai:gpt-5.2', instructions='Summarize.')
await notes.run(message_history=session.all_messages())Key facts for building realtime agents:
session.send() solicits a response: use respond=False to add passive
text context. Images are context-only by default; use respond=True to ask for a response to an
image. Never pair session.send('...') with session.create_response(), because that asks twice.
A string sent during a reply queues on OpenAI/Azure/xAI and Gemini 2.5, but interrupts the active
reply on Gemini 3.1. On OpenAI GPT-Live a string is never a user turn at all: it is context the model
relays or answers (even with respond=False, which only doesn't request speech), it only lands
while audio is flowing (set openai_live_idle_audio=True for a session with no microphone), and text over 500 tokens raises UserError. Gemini speech models reject text output before connect, except the Vertex
gemini-live-2.5-flash half-cascade, which answers in text.session.all_messages() / session.new_messages()
return real ModelMessages; seed with realtime(model, message_history=...).session(), or with
conversation=result.conversation to carry the running usage and conversation_id too. Transcripts
stay attached to the user turn they describe even when they arrive after its response, and a turn
started while the model is still answering (barge-in) is recorded after that answer. A reported
speech segment whose transcript never arrives remains represented by retained audio or a content-less
SpeechPart when the session closes. Transcripts are what carry over; a model whose profile sets
supports_seeding_audio can also replay retained transcript-less user audio recorded at its input
rate, and assistant audio is never replayed. Streamed images all reach the provider, but
history keeps a sampled (retain_images_every_n) and bounded (retain_images_max, default 100,
oldest evicted first) record. Audio kept by audio_retention is bounded too (retain_audio_max_seconds,
default 1800, oldest evicted first, transcripts kept).ModelResponse carries its response usage, while session.usage
is cumulative; priced models get a genai-prices cost and enforce UsageLimits.cost_limit.session.context_window_used (and ctx.context_window_used in a session's tools)
is the fraction in use: reported by OpenAI GPT-Live, computed from the latest response's tokens on
OpenAI/Azure/Gemini, and None on xAI. It can drop after server-side compaction or truncation, which
no provider announces; tune it with openai_truncation (OpenAI Realtime and Azure, not GPT-Live) or
google_context_compression (Gemini).output_type: realtime models don't do structured output. Delegate hard work to a text
agent behind a tool, or hand off history afterwards.model.profile (a
RealtimeModelProfile, the realtime counterpart to ModelProfile) reports
supports_manual_turn_control, supports_interruption, supports_image_input,
supports_output_truncation, and supports_session_seeding. OpenAI Realtime and Azure OpenAI
support all of these; OpenAI GPT-Live supports only supports_session_seeding (from text) and
supports_image_input with image_input_requires_response (an image goes to its backend, sent with
respond=True), since it owns turn-taking; Gemini Live lacks supports_manual_turn_control,
supports_interruption, and supports_output_truncation (automatic VAD only). Calling an unsupported method raises UserError up front.TurnDetection setting for sensitivity, prefix padding, and
silence duration across providers. Use openai_turn_detection, xai_turn_detection, or
google_vad only for finer provider-specific control; when present, they fully override the shared
setting. Automatic detection is on by default (True); set turn_detection=False for push-to-talk
(OpenAI/Azure/xAI only — Gemini has no manual turn controls and raises).handle_barge_in=True to .session() and
the session owns the local half — flushing the audio the user will never hear, truncating the
provider's transcript to what was played, and adding a client cancel only on providers whose own
turn detection isn't already cancelling. Off by default, and it needs playback to drain a single
device-paced stream_audio() iterator (the position it tracks); with none or several it stands
down. To keep the trigger yourself, session.interrupt(played_bytes=session.played_audio_bytes)
gets the same treatment on your own signal. A playback layer that buffers ahead of the device
makes played_audio_bytes read too far: count real device consumption and pass played_ms.clear_audio() instead.async_tool_call_mode:
'always' (OpenAI, Azure, GPT-Live, xAI, gemini-3.8-live-extended-thinking), 'optional'
(Gemini native-audio and gemini-3.8-live, on only with the shared async_tool_calls=True
setting, which the other models ignore), or 'never' (other Gemini Live models). Don't use the
deprecated google_async_tool_calls setting or supports_async_tool_calls profile flag.
gemini-3.8-live-extended-thinking has no blocking mode and reasons in the background —
it speaks a filler, runs the tool, and speaks again inside one exchange, so read
RealtimeTurnCompleteEvent or await session.wait_for_reply() rather than watching each response
to know it's done. An unhandled tool
exception is raised from session iteration while it is active; otherwise it ends stream_audio() and
stream_transcripts() and is raised when the session context closes. The next outbound method
raises an already-ended receive side's failure instead, and every failure is delivered only once.
Its call is recorded with outcome='failed', leaving history valid for a standard-agent handoff.
An on_tool_execute_error capability can return a replacement result or raise ModelRetry to keep
the session running. To end the call from a tool, await ctx.realtime_session.hang_up() for a clean
hang-up (the tool does not resume, its call is recorded as interrupted, and a concurrent
send_audio() async iterable returns cleanly at its next chunk), or call ctx.cancel() to make
the session context raise RunCancelled. A watchdog can also await session.close() safely:
cancelling the watchdog does not interrupt teardown, and the session context waits for teardown
before exiting. While iteration is running the loop ends cleanly and session.result is settled.HandleDeferredToolCalls
handler (and refused without one); as in a run, DeferredToolRequestsEvent is emitted before the
handler runs, and DeferredToolResultsEvent once it has resolved the call.PartDeltaEvents and the most recent 512 structural events, so a long call that
nobody iterates cannot grow without bound. Parts are dropped whole, so a late iterator never sees a
delta without its PartStartEvent. A parked failure is always retained. An active
async for event in session remains lossless.agent.realtime(model).answer_webrtc_offer(sdp_offer) — the agent's
resolved instructions and tools are baked in and the API key stays on the server — then attach a
control-plane sideband with .session(provider_session=answer.session). The browser owns the
audio; the sideband session runs tools and builds history (its audio methods raise, and
audio_retention must stay 'transcript_only'). Closing the sideband only detaches it: call
session.hang_up() (or agent.realtime(model).hang_up(answer.session)) to end the browser's call (OpenAI only).handle_barge_in=True cannot know browser playback position because
forwarded chunks count as played. Have the browser report real playback and pass it to
interrupt(played_bytes=...); played_ms= does not flush session-queued audio.See the Realtime guide for the full walkthrough.
Load only the most relevant reference first. Read additional references only if the task spans multiple areas.
| I want to... | Reference |
|---|---|
| Create/configure agents, choose output types, use deps, define specs, or pick run methods | Agents Core |
| Bundle reusable behavior or intercept lifecycle events | Capabilities and Hooks |
Decide what should load eagerly vs on demand, apply progressive disclosure, defer capability loading, or explain load_capability | Capabilities on Demand |
| Add function tools, toolsets, MCP servers, or explicit search tools | Tools Core |
| Attach a workspace, expose workspace-backed tools, or manage workspace lifecycle and durable references | Workspaces |
| Use provider-native web search, web fetch, or code execution | Native Tools |
Use advanced tool features such as approval, retries, failed tool results, ToolReturn, validators, timeouts, or tool search | Tools Advanced |
Work with multimodal input, message history, run_id / conversation_id, or context trimming | Input and History |
| Test or debug agent behavior | Testing and Debugging |
| Set up observability with Logfire, or reach every model with one Gateway key | Set Up Observability and Model Access, then Testing and Debugging |
| Coordinate multiple agents or build graph workflows | Orchestration and Integrations |
| Call the model directly, expose A2A, use durable execution, embeddings, image generation, evals, or third-party integrations | Orchestration and Integrations |
| Compare abstractions, output modes, decorators, or model-string patterns | Architecture and Decision Guide |
Follow an older link into COMMON-TASKS.md | Task Reference Map |
Load Architecture and Decision Guide only when the user is choosing between abstractions or wants comparison tables and decision trees:
| Topic | What it covers |
|---|---|
| Decision Trees | Tool registration, output modes, multi-agent patterns, capabilities, testing approaches, extensibility |
| Comparison Tables | Output modes, model provider prefixes, tool decorators, built-in capabilities, agent methods |
| Architecture Overview | Execution flow, generic types, construction patterns, lifecycle hooks, model string format |
Quick reference (model string format): "provider:model-name" (e.g., "openai:gpt-6-sol", "anthropic:claude-fable-5-1", "google:gemini-3-pro-preview"), or "gateway/provider:model-name" through the Pydantic AI Gateway (e.g., "gateway/openai:gpt-6-sol")
Quick reference (key agent methods): run(), run_sync(), run_stream(), run_stream_sync(), run_stream_events(), iter()
defer_loading=True would benefit the agent before choosing eager loading. Do not eagerly load specialist instructions, rarely used tool schemas, or domain context unless the model needs them on most turns. Prefer capabilities on demand for named instruction+tool bundles, and tool search for large flat tool catalogs.capabilities=[Caching()] to every agent you build. Anthropic, Bedrock and OpenRouter's Anthropic routes cache nothing unless asked, so an agent without it pays full price for its instructions, tools and history on every request. Caching isn't on by default only because cache writes cost more than uncached input; for agents that make many one-off requests sharing long instructions or tools, use Caching(messages=False). See Configure Prompt Caching Across Providers.logfire.configure() and logfire.instrument_pydantic_ai() (see Set Up Observability and Model Access), unless the user uses another OpenTelemetry backend. Use logfire.instrument_httpx(capture_all=True) only for targeted debugging because it captures exact provider payloads, including prompts, tool data, user content, and possibly secrets. Pass an explicit name= to each Agent (e.g. Agent(..., name='research_agent')): it labels the agent's run span in Logfire. When omitted, the name is inferred from the variable the agent is assigned to and falls back to 'agent' when it can't be (e.g. agents kept in a list or dict), which makes traces hard to tell apart when several agents run in one app.TestModel for deterministic tests, FunctionModel for custom logicWorkspace only carries an execution environment; applications choose which tools expose it. A second LocalWorkspace with the default id replaces the first (its settings do not carry over); several different workspace capabilities may be attached, and the first that returns a workspace wins. LocalWorkspace / LocalWorkspaceBackend isolate nothing and are only for trusted workloads; use a sandbox provider for untrusted code.These are mistakes agents commonly make with Pydantic AI. Getting these wrong produces silent failures or confusing errors.
@agent.tool requires RunContext as first param; @agent.tool_plain must not have it. Mixing these up causes runtime errors. Use tool_plain when you don't need deps, usage, or messages.'openai:gpt-5.2' not 'gpt-5.2'. Without the prefix, Pydantic AI can't resolve the provider.TestModel requires agent.override(): Don't set agent.model directly. Always use the context manager: with agent.override(model=TestModel()):.str in output_type allows plain text to end the run: If your union includes str (or no output_type is set), the model can return plain text instead of structured output. Omit str from the union to force tool-based output..on don't repeat on_: Use hooks.on.run_error and hooks.on.model_request_error — not hooks.on.on_run_error.history_processors is deprecated; use capabilities=[ProcessHistory(p), ...], or hook before_model_request directly via capabilities=[Hooks(before_model_request=fn)]. ProcessHistory is a thin wrapper around that hook — the hook itself is the underlying primitive. The kwarg still works in 1.x but emits a PydanticAIDeprecationWarning and will be removed in v2.async with agent: closes and recreates its provider's HTTP client after every run, so no connections are reused, and a model name passed as agent.run(..., model='provider:name') creates a new provider and client per run. Enter the agent at startup and pass entered Model instances to switch models. To tune timeouts or connection pool limits, pass http_client=create_async_httpx2_client(timeout=..., limits=...) (from pydantic_ai.models) to the provider (Groq, Cohere and GitHub take a legacy httpx.AsyncClient instead); a client you pass in is yours to close.Load exactly one of these unless the task clearly spans multiple families:
| Task family | Reference |
|---|---|
| Core agent setup, output, deps, specs, models, run methods | Agents Core |
| Capabilities, hooks, and reusable behavior | Capabilities and Hooks |
Progressive disclosure, deferred capabilities, capabilities on demand, and load_capability semantics | Capabilities on Demand |
| Function tools, toolsets, MCP, explicit search tools | Tools Core |
| Workspaces, workspace-backed tools, lifecycle ownership, and durable references | Workspaces |
| Provider-native tools | Native Tools |
| Approval, retries, failed tool results, validators, timeouts, rich tool returns, tool search, and tool-level deferred loading | Tools Advanced |
Multimodal input, message history, run_id / conversation_id, history processors | Input and History |
| Testing, request inspection, and Logfire debugging | Testing and Debugging |
| Multi-agent patterns, graphs, direct API, A2A, durable execution, embeddings, image generation, evals, third-party integrations | Orchestration and Integrations |
Use Task Reference Map only for compatibility with older links or when you need a pointer from an old section name to the new file.
© pydantic, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
SKILL.md and 12 other files (references) in pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents of pydantic/pydantic-ai.
Open the folder on GitHubat commit 69ea1e5
Building Pydantic AI Agents next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Building Pydantic AI Agents this skillpydantic/pydantic-ai | 21k | — | ~8.2k | Automated safety check: Pass | MIT | |
| Building Pydantic AI Agentsdocling-project/docling | 69k | — | ~2.8k | Automated safety check: Pass | MIT | |
| Building Pydantic AI Agentspydantic/skills | 140 | — | ~5.4k | Automated safety check: Pass | MIT | |
| Logfire Instrumentationpydantic/skills | 140 | — | ~6.1k | Automated safety check: Pass | MIT | |
| Pydantic AIdavila7/claude-code-templates | 33k | 3 repos | ~2.9k | Automated safety check: Pass | MIT | |
| Langchain Middlewarelangchain-ai/langchain-skills | 1.3k | — | ~2.7k | Automated safety check: Pass | MIT |
docling-project/docling
Patterns and tested examples for building agents with Pydantic AI: tools, capabilities, structured output, dependency injection, hooks, YAML specs, streaming and testing.
pydantic/skills
Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), structured output, streaming, testing, and multi-agent patterns.
pydantic/skills
Add Pydantic Logfire observability to application code — traces, logs, metrics, and AI/agent spans.
davila7/claude-code-templates
Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.
langchain-ai/langchain-skills
INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output.
vercel-labs/ai-facts
Answer questions about the AI SDK and help build AI-powered features.
pydantic/pydantic-ai
Adds optional capabilities to Pydantic AI agents from pydantic-ai-harness, led by Code Mode, which runs many tool calls as one sandboxed Python script.
pydantic/pydantic-ai
Evaluate and complete an issue or PR where the submitted patch fixes only a narrow symptom of the reported pain point.
pydantic/pydantic-ai
Record, rewrite, and debug VCR cassettes for HTTP recordings.
pydantic/pydantic-ai
Migrate Python Agno applications to Pydantic AI and, only when needed, Pydantic AI Harness.
pydantic/pydantic-ai
Migrate Python applications from the Claude Agent SDK to Pydantic AI and, only when needed, Pydantic AI Harness.
pydantic/pydantic-ai
Migrates Python LangChain Deep Agents applications to Pydantic AI and Pydantic AI Harness while preserving the application's observed behavior.
Works with
Categories
Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns. Building Pydantic AI Agents is an agent skill from pydantic/pydantic-ai, published by the product's own GitHub organization. Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), workspaces, structured output, streaming, testing, and multi-agent patterns.
Building Pydantic AI Agents fits situations like: the user mentions Pydantic AI; imports pydanticai; asks to build an AI agent; add tools/capabilities.
Run `npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a claude-code`. Or copy the skill folder (pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents in pydantic/pydantic-ai) into .claude/skills/building-pydantic-ai-agents in your project. Claude Code loads it when a task matches its description.
Run `npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a codex`. Or copy the skill folder (pydantic_ai_slim/pydantic_ai/.agents/skills/building-pydantic-ai-agents in pydantic/pydantic-ai) into .agents/skills/building-pydantic-ai-agents in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add pydantic/pydantic-ai --skill building-pydantic-ai-agents -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/building-pydantic-ai-agents, .gemini/skills/building-pydantic-ai-agents, .github/skills/building-pydantic-ai-agents and .opencode/skills/building-pydantic-ai-agents in your project.
Going by SKILL.md and its folder, Building Pydantic AI Agents needs the command-line tools its instructions call (uvx) and credentials named LOGFIRE_TOKEN and PYDANTIC_AI_GATEWAY_API_KEY. Our summary lists: Python 3; A credential in LOGFIRE_TOKEN; A credential in PYDANTIC_AI_GATEWAY_API_KEY. Compatibility (from SKILL.md): Requires Python 3.11+.
SKILL.md names 1 domain. As links in the text: pydantic.dev. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.
Building Pydantic AI Agents is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.
About 8.2k tokens (SKILL.md is roughly 33k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 32k tokens, read only when the agent opens those files.
Skills that share tags, products or a category with Building Pydantic AI Agents: Building Pydantic AI Agents (docling-project/docling, 69k stars), Building Pydantic AI Agents (pydantic/skills, 140 stars), Logfire Instrumentation (pydantic/skills, 140 stars) and Pydantic AI (davila7/claude-code-templates, 33k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
pydantic (a GitHub organization, an official publisher) maintains it in pydantic/pydantic-ai, which has 20,537 GitHub stars. The repository holds 20 skills in this directory. The repository was last updated on October 11, 2026.
Source: pydantic/pydantic-ai on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.