翻篇收录说明
翻篇网页快照

Pydantic AI | Pydantic Docs

https://pydantic.dev/docs/ai/overview/

最近抓取:2026-12-03 06:46:18(北京时间)

最近内容变化:2026-12-03 06:46:18(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

How Python does AI: agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.

正文摘录

Pydantic AI How Python does AI Agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end. Pydantic AI is the Python AI SDK: a typed, extensible agent loop with every model a string swap away, and another one to fall back to when a provider fails. The same agent runs everywhere you need it: behind a web frontend, in the terminal, on a voice call, on a durable background queue, in GitHub Actions, or as a plain object you call run() on. Image generation and embeddings come in the same box. Pydantic AI Harness has everything an agent needs for complex, long-running work, snapped on as capabilities, from memory, guardrails, and sub-agents to planning, context management, and persistence, up to a complete coding agent. Pydantic Evals grades an agent’s final outputs and tool-call trajectories, on datasets or live production traffic, and Pydantic Graph gives you typed control flow when one agent loop is not enough. Both are separate open-source packages, and so are genai-prices, which keeps model pricing current, and Monty, the sandboxed Python interpreter that runs model-written code. Pydantic Logfire is the AI engineering platform that sees your whole app, not just the LLM calls, and the Pydantic AI Gateway is one key for every model with real-time cost monitoring and budget control; our instrumentation is plain OpenTelemetry, so any backend you already run works. What are you building? From simple typed data extraction to complex, long-running multi-agent collaboration, Pydantic AI and Pydantic AI Harness have got you covered. Coding agent Data extraction Durable workflow Realtime voice Image gen A complete coding agent in your terminal: workspace-rooted file access, allowlisted shell, repo orientation, planning, and context management that survives long sessions. Here with web search and a second-opinion advisor snapped on alongside: pip uv Terminalpip install pydantic-ai "pydantic-ai-harness[coder]" from pydantic_ai import Agent from pydantic_ai.capabilities import WebSearch from pydantic_ai_harness import Advisor, Coder agent = Agent( 'anthropic:claude-fable-5-2', capabilities=[ Coder(), # files, shell, repo context, sub-agents, context management WebSearch(), # look up docs and error messages on the web Advisor('openai:gpt-6.1-sol'), # a second opinion from another model when stuck ], ) agent.to_cli_sync() Coder is a regular combined capability, not a black box: use it whole, or use the blocks it bundles directly; the two are equivalent:capabilities = [ FileSystem('.'), Shell(cwd='.'), RepoContext(), SubAgents(...), ClearToolResults(), ToolOutputLimits(), RepairToolArguments(), ] Run the file and you’re chatting with the agent in your terminal. To use a coding agent rather than build one, run Pax, the coding-agent TUI built on the Harness. It runs Coder by default, and your own agent with --agent:Terminaluv tool install pydantic-ai-pax pax Build this → Coder, from the HarnessRun it on GitHub → GitHub Agentic Workflows, on issues, pull requests or a schedule Why Pydantic AI Any model, one Python API. Virtually every model and provider (OpenAI, Anthropic, Google, Bedrock, Azure AI Foundry, Groq, Mistral, xAI, Ollama, and dozens more), swappable with a string, or through the Pydantic AI Gateway: one key for all of them, with failover and cost monitoring built in. No flagship feature is locked to one vendor. Typed end to end. Structured outputs, typed dependency injection, typed tools: your IDE, type checker, and coding agent all know what your agent returns, moving whole classes of errors from runtime to write-time. When plain control flow isn’t enough, Pydantic Graph brings the same typing to graph-based workflows. Measured, not vibes. OpenTelemetry-native instrumentation works with any OTel backend; run uvx logfire-cli wizard --task pydantic-ai once to light up Pydantic Logfire for real-time debugging, tracing, and cost tracking backed by genai-prices. Pydantic Evals grades final outputs and tool-call trajectories, against datasets in code or, with online evaluation, a sample of live production traffic. Batteries, composably. One primitive, the capability, bundles tools, instructions, hooks, and model settings into reusable units. Core ships fundamentals like MCP and web search, the Harness ships everything else, and complete agents like Coder and Researcher are just capabilities composed: they come apart the way they went together. Or skip code entirely with YAML/JSON agent specs. Every interface. One agent definition runs in Pax, the terminal TUI that also has a headless mode (pax -p "..."), a built-in web chat, or realtime speech; UI event streams (AG-UI, Vercel AI) connect it to your own frontend or anything else; ACP serves it as an editor agent; and GitHub Agentic Workflows runs it headless on issues, pull requests or a schedule. Durable execution. Durable execution on ten engines: Temporal, DBOS, Prefect, Restate, AWS Lambda, Hatchet, Airflow, Absurd, pgtask, and Azure Durable Task, the first five co-maintained with the vendor teams. Agents survive restarts and run for days on the engine you already operate, with human-in-the-loop approval built in. Coming from another framework? The comparisons show where Pydantic AI differs from LangChain, Google ADK, Microsoft Agent Framework, the Claude Agent SDK and the other frameworks people ask us about, and the migration skills let your coding agent port an existing application over. Built by the Pydantic team: Pydantic Validation is the validation layer of the OpenAI SDK, the Anthropic SDK, the Google ADK, LangChain, and most of the AI ecosystem (and the foundation FastAPI was built on). Pydantic AI brings that same feeling to agents. Built with Pydantic AI lists open source projects and organizations that run on it. Sign up for our newsletter, The Pydantic Stack, with updates & tutorials on Pydantic AI, Logfire, and Pydantic: Putting it together: a bank support agent Here’s a support agent for a bank, showing several features working together: dependency injection carrying a database connection into instructions and tools, function tools the model calls, structured output validated on every run, a reusable capability bundling the customer context, and an on-demand capability the model loads only when the conversation calls for it: bank_support.py from dataclasses import dataclass from pydantic import BaseModel, Field from pydantic_ai import Agent, Capability, RunContext from bank_database import DatabaseConn @dataclass class SupportDependencies: # (1) customer_id: int db: DatabaseConn # (2) class SupportOutput(BaseModel): # (3) support_advice: str = Field(description='Advice returned to the customer') block_card: bool = Field(description="Whether to block the customer's card") risk: int = Field(description='Risk level of query', ge=0, le=10) customer_context = Capability[SupportDependencies]( # (4) id='customer-context', description="Who the customer is and what's on their account.", ) @customer_context.instructions # (5) async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str: customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id) return f"The customer's name is {customer_name!r}" @customer_context.tool # (6) async def customer_balance( ctx: RunContext[SupportDependencies], include_pending: bool ) -> float: """Returns the customer's current account balance.""" # (7) return await ctx.deps.db.customer_balance( id=ctx.deps.customer_id, include_pending=include_pending, ) refunds = Capability[SupportDependencies]( # (8) id='refunds', description='Refund eligibility and refund status.', defer_loading=True, ) @refunds.tool async def refund_status(ctx: RunContext[SupportDependencies]) -> str: """Look up the refund status for the customer's most recent charge.""" return await ctx.deps.db.refund_status(id=ctx.deps.customer_id) support_agent = Agent( # (9) 'openai:gpt-6.1-sol', # (10) deps_type=SupportDependencies, output_type=SupportOutput, # (11) instructions=( 'You are a support agent in our bank, give the ' 'customer support and judge the risk level of their query.' ), capabilities=[customer_context, refunds], # (12) ) ... # (13) async def main(): deps = SupportDependencies(customer_id=123, db=DatabaseConn()) result = await support_agent.run('What is my balance?', deps=deps) # (14) print(result.output) """ support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1 """ result = await support_agent.run('I just lost my card!', deps=deps) print(result.output) """ support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8 """ result = await support_agent.run( # (15) 'Was I refunded for the duplicate charge on my last statement?', deps=deps ) print(result.output) """ support_advice='Good news, John: the duplicate charge on your last statement was refunded on 2026-05-01.' block_card=False risk=1 """ The SupportDependencies dataclass is used to pass data, connections, and logic into the model that will be needed when running instructions and tool functions. Pydantic AI's system of dependency injection provides a type-safe way to customise the behavior of your agents, and can be especially useful when running unit tests and evals. This is a simple sketch of a database connection, used to keep the example short and readable. In reality, you'd be connecting to an external database (e.g. PostgreSQL) to get information about customers. This Pydantic model is used to constrain the structured data returned by the agent. From this simple definition, Pydantic builds the JSON Schema that tells the LLM how to return the data, and performs validation to guarantee the data is correct at the end of the run. A Capability bundles related instructions and tools into one reusable unit: the same primitive behind built-in capabilities like web search and everything