页面简介
Build production-grade AI applications with Pydantic AI - a model-agnostic Python framework featuring type safety, structured outputs, validation, and seamless observability. Supports OpenAI, Anthropic, Google, and more.
正文摘录
Pydantic AI Production-grade applications with Generative AI Type-safe Python framework for building agents and LLM applications. Model-agnostic with built-in validation, structured outputs, and seamless observability. Get started uv add pydantic-ai Companies that trust Pydantic AI Akamai, Atlassian, Banorte, Cisco, Duolingo, Elastic, Jane Street, JPMorgan Chase, Meta, Microsoft, NATO, NVIDIA, Roche, Seatlech, TNG Technology Consulting, Walmart, Xero Monitor your AI agents with Logfire Build intelligent AI agents Create agents that can reason, use tools, and interact with external systems. Pydantic AI provides a modular, type-safe platform for building production-ready AI agents with any model provider. Built-in integration with Pydantic Logfire for complete visibility into agent runs. Trace LLM calls, track token costs, debug failures, and understand latency across your entire AI stack. Learn about Logfire from typing import Literal import logfire from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext logfire.configure(service_name="review-sentiment") logfire.instrument_pydantic_ai() class Sentiment(BaseModel): label: Literal["positive", "negative", "neutral"] score: float = Field(ge=-1, le=1) agent = Agent("openai:gpt-6.1-sol", output_type=Sentiment) @agent.tool def recent_reviews(ctx: RunContext, product: str) -> list[str]: """Fetch recent review snippets for a product.""" return ["The new release fixed everything I complained about!"] result = agent.run_sync("How are people feeling about the Extract app?") print(result.output) #> label='positive' score=0.9 Loading Logfire trace… Try it on your stack See your agent runs in Logfire Start free with 10 million spans, logs, and metrics each month. No credit card required. Start free Read the setup guide Model Context Protocol Connect to MCP servers The Model Context Protocol (MCP) is an open standard for connecting AI models to external tools and data sources. Pydantic AI has built-in support for MCP servers, enabling your agents to access file systems, databases, APIs, and more. How Pydantic AI supports MCP Streaming Stream AI agent events to your frontend in real time Stream text, tool calls, and reasoning to your frontend as they happen. Pydantic AI offers out of the box support for AG-UI protocol for standardized agent-to-UI communication and Vercel AI Data Stream Protocol. See UI Event Streams docs Durable Execution Build fault-tolerant agents Build durable agents that preserve their progress across transient API failures and application errors or restarts. Handle long-running, asynchronous, and human-in-the-loop workflows with production-grade reliability. Durable agents have full support for MCP, and for streaming wherever the platform can stream a response back, with the added benefit of fault tolerance. Pydantic AI supports eight durable execution engines, each with a complete example: TemporalDBOSPrefectRestateAWS LambdaAbsurdpgtaskAzure Durable Task Temporal, DBOS, Prefect, Restate, and AWS Lambda are co-maintained with the vendor teams. Absurd, pgtask, and Azure Durable Task ship in Pydantic AI Harness; Restate ships in its own package. Running something else? Build a backend on the public interface. Also works with, as SDK integrations KitaruApache Airflow Realtime Speech-to-speech agents Open a live voice session on the agent you already have. Realtime sessions take the same tools, dependencies, instructions, and message history as a standard run. Audio streams both ways, the person can interrupt, and tool calls run on your server while the conversation continues. Afterward, hand the history to a text run for a structured follow-up. Build a voice agent Provider support Every provider implements the same realtime model interface. What each model can do differs, and the provider pages are canonical for model names, settings, and quirks. Realtime provider support Provider Audio output Image input Text output Browser WebRTC Async tool calls Thinking State-restoring reconnect OpenAI Yes Yes. GPT-Live: backend only Yes. GPT-Live: no Yes Yes gpt-realtime-2* models; GPT-Live’s backend Replays local history. GPT-Live: as text, or forks a stored session Azure OpenAI Yes Yes Yes Yes. Not on Voice Live Yes gpt-realtime-2*, and gpt-5-class models on Voice Live Replays local history Google Gemini Yes Yes Vertex gemini-live-2.5-flash only No Opt-in on native-audio and gemini-3.8-live; always on for extended thinking Native-audio and most 3.x models Yes, with a reconnect policy xAI Yes No No No Yes grok-voice-latest and -think- models Replays local history ElevenLabs Yes No Agents only (toggle-gated) No No No Eleven Realtime replays local history. Agents: no Branch at runtime instead of hard-coding this table: the model profile reports one flag per column, plus the audio sample rates to capture and play at. Model Registry Choose the right model for your agent The Pydantic AI Model Registry lists every model you can use with Pydantic AI: who makes it, where it runs, what it costs, and how well it performs. Prices come from genai-prices. Benchmark results come from Epoch AI, LMArena, Browser Use, and our own Pydantic AI benchmarks. Describe your agent to the model selector and get back up to five ranked models, each with reasons and prices. Your coding agent can ask the same question through the registry's API or MCP server. Browse the model registry Find a model for your agent The dashed line joins the models no cheaper model beats. 43 models, Nov 30, 2026. Why Pydantic AI? Validated structured outputs Leverage the power of Pydantic validation that guarantees type-safety on structured outputs. Trusted by OpenAI, Anthropic, Google, and millions of developers. Integrated AI model routing Built-in cost control and model routing without performance overhead with Pydantic AI Gateway. BYOK or built-in providers for single-key access models. Production observability Built-in integration with Pydantic Logfire for real-time debugging, tracing, and cost tracking with massive AI workloads. Testing & evaluation Test your agents with Pydantic Evals. Create datasets, run evaluations, track model performance and visualise it on your CLI or on Pydantic Logfire. Streaming support Stream responses token-by-token for real-time user feedback. Access structured data as it arrives. Multi-agent workflows Build complex systems with multiple specialized agents. Coordinate with graph-based workflows. Function Tools Give agents access to your code Use @agent.tool or @agent.tool_plain decorators to register tool access to an agent context. Pydantic AI automatically generates JSON schemas from your type hints and docstrings, enabling models to call your functions correctly. import random from pydantic_ai import Agent, RunContext agent = Agent( "gateway/google:gemini-4-hydrogen", deps_type=str, system_prompt=( "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() -> int: """Roll a six-sided die and return the result.""" return 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! Already use Pydantic AI? Try Logfire! Part of The Pydantic Stack Pydantic AI integrates seamlessly with Pydantic Logfire for complete observability, Pydantic AI Gateway for intelligent model routing, and Pydantic Evals for systematic evaluation. Build with AI at scale, without fail. Explore Logfire Explore AI Gateway Ready to build? Open source (under MIT license). Install with uv (or pip) and start building production-grade AI applications today. Get started uv add pydantic-ai Get Pydantic AI enterprise support