### Install Pydantic AI Examples Source: https://pydantic.dev/docs/ai/overview/install Installs the optional examples package to help with customization and testing. ```bash pip install "pydantic-ai[examples]" ``` ```bash uv add "pydantic-ai[examples]" ``` -------------------------------- ### Install Pydantic skills from marketplace Source: https://pydantic.dev/docs/ai/overview/coding-agent-skills Adds the Pydantic skills marketplace and installs the AI skill bundle. ```bash claude plugin marketplace add pydantic/skills claude plugin install ai@pydantic-skills ``` -------------------------------- ### Install Pydantic AI Source: https://pydantic.dev/docs/ai/overview/install Standard installation command for the full Pydantic AI package. ```bash pip install pydantic-ai ``` ```bash uv add pydantic-ai ``` -------------------------------- ### Install Slim Pydantic AI with OpenAI Source: https://pydantic.dev/docs/ai/overview/install Installs the slim version of the package with only the OpenAI dependency. ```bash pip install "pydantic-ai-slim[openai]" ``` ```bash uv add "pydantic-ai-slim[openai]" ``` -------------------------------- ### Install bundled Pydantic AI skill Source: https://pydantic.dev/docs/ai/overview/coding-agent-skills Installs the skill directly from project dependencies using library-skills.io. ```bash uvx library-skills --all ``` -------------------------------- ### Install Slim Pydantic AI with Multiple Extras Source: https://pydantic.dev/docs/ai/overview/install Installs the slim version with multiple specific integrations enabled. ```bash pip install "pydantic-ai-slim[openai,google,logfire]" ``` ```bash uv add "pydantic-ai-slim[openai,google,logfire]" ``` -------------------------------- ### Install Pydantic AI plugin for Claude Code Source: https://pydantic.dev/docs/ai/overview/coding-agent-skills Installs the official Pydantic AI plugin from the Anthropic marketplace. ```bash claude plugin install pydantic-ai@claude-plugins-official ``` -------------------------------- ### Install Pydantic AI skill via agentskills.io Source: https://pydantic.dev/docs/ai/overview/coding-agent-skills Uses the skills CLI to add the Pydantic AI skill, compatible with over 30 agents. ```bash npx skills add pydantic/skills ``` -------------------------------- ### Install Pydantic AI Source: https://pydantic.dev/docs/ai/overview/gateway Update to version 1.16 or later to ensure compatibility with Gateway features. ```bash uv sync -P pydantic-ai ``` ```bash pip install -U pydantic-ai ``` -------------------------------- ### Instrument Pydantic AI Agent with Logfire Source: https://pydantic.dev/docs/ai/overview Configure Logfire to monitor Pydantic AI agents and database interactions. Requires the logfire SDK to be installed and configured. ```python ...from pydantic_ai import Agent, RunContextfrom bank_database import DatabaseConnimport logfirelogfire.configure() logfire.instrument_pydantic_ai() logfire.instrument_sqlite3() ...support_agent = Agent( 'openai:gpt-5.2', deps_type=SupportDependencies, output_type=SupportOutput, instructions=( 'You are a support agent in our bank, give the ' 'customer support and judge the risk level of their query.' ),) ``` -------------------------------- ### Initialize and run a basic Pydantic AI agent Source: https://pydantic.dev/docs/ai/overview Demonstrates creating an agent with static instructions and executing a synchronous request. ```python from pydantic_ai import Agent agent = Agent( 'anthropic:claude-sonnet-4-6', instructions='Be concise, reply with one sentence.', ) result = agent.run_sync('Where does "hello world" come from?') print(result.output) ``` -------------------------------- ### Initialize Agent with Gateway Model Source: https://pydantic.dev/docs/ai/overview/gateway Use the gateway/ prefix in the model string to route requests through the Pydantic AI Gateway. ```python from pydantic_ai import Agent agent = Agent('gateway/openai:gpt-5.2') 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.""" ``` -------------------------------- ### Pass API Key Directly to Provider Source: https://pydantic.dev/docs/ai/overview/gateway Manually instantiate the gateway provider with an API key instead of using environment variables. ```python from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.gateway import gateway_provider provider = gateway_provider('openai', api_key='pylf_v...') model = OpenAIChatModel('gpt-5.2', provider=provider) agent = Agent(model) 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.""" ``` -------------------------------- ### Configure an agent with thinking and web search capabilities Source: https://pydantic.dev/docs/ai/overview Extends the basic agent by adding Thinking and WebSearch capabilities to handle complex queries. ```python from pydantic_ai import Agent from pydantic_ai.capabilities import Thinking, WebSearch agent = Agent( 'anthropic:claude-sonnet-4-6', instructions='Be concise, reply with one sentence.', capabilities=[Thinking(), WebSearch(local='duckduckgo')], ) result = agent.run_sync('What was the mass of the largest meteorite found this year?') print(result.output) ``` -------------------------------- ### Configure OpenAI SDK for Gateway Source: https://pydantic.dev/docs/ai/overview/gateway Use the appropriate base URL for your Logfire region to route OpenAI requests through the gateway. ```python import openaiclient = openai.Client( base_url='https://gateway-us.pydantic.dev/proxy/chat/', api_key='pylf_v...',)response = client.chat.completions.create( model='gpt-5.2', messages=[{'role': 'user', 'content': 'Hello world'}],)print(response.choices[0].message.content)#> Hello user ``` ```python import openaiclient = openai.Client( base_url='https://gateway-eu.pydantic.dev/proxy/chat/', api_key='pylf_v...',)response = client.chat.completions.create( model='gpt-5.2', messages=[{'role': 'user', 'content': 'Hello world'}],)print(response.choices[0].message.content)#> Hello user ``` -------------------------------- ### Running Agent in Legacy Jupyter Environments Source: https://pydantic.dev/docs/ai/overview/troubleshooting Apply nest_asyncio to resolve event loop conflicts in legacy environments, Google Colab, or Marimo. ```python import nest_asyncio from pydantic_ai import Agent nest_asyncio.apply() agent = Agent('openai:gpt-5.2') result = agent.run_sync('Who let the dogs out?') ``` -------------------------------- ### Configure Vercel AI SDK for Gateway Source: https://pydantic.dev/docs/ai/overview/gateway Point the provider's baseURL to the gateway proxy path to route Vercel AI SDK requests. ```typescript import { createOpenAI } from "@ai-sdk/openai";import { generateText } from "ai";const apiKey = process.env.PYDANTIC_AI_GATEWAY_API_KEY;if (!apiKey) throw new Error("set PYDANTIC_AI_GATEWAY_API_KEY");const openai = createOpenAI({ apiKey, baseURL: "https://gateway-us.pydantic.dev/proxy/openai",});async function main() { const openaiResult = await generateText({ model: openai("gpt-5.2"), prompt: "what color is the sky? reply concisely", }); console.log("openai:", openaiResult.text);}main().catch((err) => { console.error(err); process.exit(1);}); ``` ```typescript import { createOpenAI } from "@ai-sdk/openai";import { generateText } from "ai";const apiKey = process.env.PYDANTIC_AI_GATEWAY_API_KEY;if (!apiKey) throw new Error("set PYDANTIC_AI_GATEWAY_API_KEY");const openai = createOpenAI({ apiKey, baseURL: "https://gateway-eu.pydantic.dev/proxy/openai",});async function main() { const openaiResult = await generateText({ model: openai("gpt-5.2"), prompt: "what color is the sky? reply concisely", }); console.log("openai:", openaiResult.text);}main().catch((err) => { console.error(err); process.exit(1);}); ``` -------------------------------- ### Set Gateway API Key Environment Variable Source: https://pydantic.dev/docs/ai/overview/gateway Configure the required environment variable with your Gateway API key. ```bash export PYDANTIC_AI_GATEWAY_API_KEY="pylf_v..." ``` -------------------------------- ### Configure Codex for Pydantic AI Gateway Source: https://pydantic.dev/docs/ai/overview/gateway Set the gateway API key and update the Codex configuration file to use the gateway. ```bash export PYDANTIC_AI_GATEWAY_API_KEY="YOUR_GATEWAY_API_KEY" ``` ```toml model = "gpt-5.4"model_provider = "pydantic_gateway"[model_providers.pydantic_gateway]name = "Pydantic AI Gateway"base_url = "https://gateway-us.pydantic.dev/proxy/openai-responses"env_key = "PYDANTIC_AI_GATEWAY_API_KEY"env_key_instructions = "Create a Gateway API key in your Logfire organization's Gateway settings."wire_api = "responses" ``` ```toml model = "gpt-5.4"model_provider = "pydantic_gateway"[model_providers.pydantic_gateway]name = "Pydantic AI Gateway"base_url = "https://gateway-eu.pydantic.dev/proxy/openai-responses"env_key = "PYDANTIC_AI_GATEWAY_API_KEY"env_key_instructions = "Create a Gateway API key in your Logfire organization's Gateway settings."wire_api = "responses" ``` -------------------------------- ### Running Agent in Modern Jupyter Source: https://pydantic.dev/docs/ai/overview/troubleshooting Use top-level await in environments that support it natively, such as Jupyter/IPython 7.0+. ```python from pydantic_ai import Agent agent = Agent('openai:gpt-5.2') result = await agent.run('Who let the dogs out?') ``` -------------------------------- ### Set Claude Code Gateway Environment Variables Source: https://pydantic.dev/docs/ai/overview/gateway Configure environment variables to route Claude Code requests through the Pydantic AI Gateway. ```bash export ANTHROPIC_BASE_URL="https://gateway-us.pydantic.dev/proxy/anthropic"export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_API_KEY" ``` ```bash export ANTHROPIC_BASE_URL="https://gateway-eu.pydantic.dev/proxy/anthropic"export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_API_KEY" ``` -------------------------------- ### Build a Bank Support Agent with Pydantic AI Source: https://pydantic.dev/docs/ai/overview Defines a support agent with custom dependencies and tools for handling customer queries. ```python from dataclasses import dataclass from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext from bank_database import DatabaseConn @dataclass class SupportDependencies: customer_id: int db: DatabaseConn class SupportOutput(BaseModel): 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) support_agent = Agent( 'openai:gpt-5.2', deps_type=SupportDependencies, output_type=SupportOutput, instructions=( 'You are a support agent in our bank, give the ' 'customer support and judge the risk level of their query.' ), ) @support_agent.instructions 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}" @support_agent.tool async def customer_balance( ctx: RunContext[SupportDependencies], include_pending: bool) -> float: """Returns the customer's current account balance.""" return await ctx.deps.db.customer_balance( id=ctx.deps.customer_id, include_pending=include_pending, ) ... async def main(): deps = SupportDependencies(customer_id=123, db=DatabaseConn()) result = await support_agent.run('What is my balance?', deps=deps) 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 """ ``` -------------------------------- ### Configure Anthropic SDK for Gateway Source: https://pydantic.dev/docs/ai/overview/gateway Set the base URL to the gateway endpoint corresponding to your region to route Anthropic requests. ```python import anthropicclient = anthropic.Anthropic( base_url='https://gateway-us.pydantic.dev/proxy/anthropic/', auth_token='pylf_v...',)response = client.messages.create( max_tokens=1000, model='claude-sonnet-4-5', messages=[{'role': 'user', 'content': 'Hello world'}],)print(response.content[0].text)#> Hello user ``` ```python import anthropicclient = anthropic.Anthropic( base_url='https://gateway-eu.pydantic.dev/proxy/anthropic/', auth_token='pylf_v...',)response = client.messages.create( max_tokens=1000, model='claude-sonnet-4-5', messages=[{'role': 'user', 'content': 'Hello world'}],)print(response.content[0].text)#> Hello user ``` -------------------------------- ### Configure Gateway Provider in Pydantic AI Source: https://pydantic.dev/docs/ai/overview/gateway Use the gateway_provider to specify an alternate routing group for an agent model. ```python from pydantic_ai import Agentfrom pydantic_ai.models.openai import OpenAIChatModelfrom pydantic_ai.providers.gateway import gateway_providerprovider = gateway_provider( 'openai', api_key='pylf_v...', route='builtin-openai')model = OpenAIChatModel('gpt-5.2', provider=provider)agent = Agent(model)result = agent.run_sync('Where does "hello world" come from?')print(result.output) ``` -------------------------------- ### Use a routing group in Pydantic AI Source: https://pydantic.dev/docs/ai/overview/gateway Configure the gateway provider to use a specific routing group slug to enable failover or load balancing strategies. ```python from pydantic_ai import Agent from pydantic_ai.models.anthropic import AnthropicModel from pydantic_ai.providers.gateway import gateway_provider provider = gateway_provider( 'anthropic', api_key='pylf_v...', route='anthropic-routing', ) model = AnthropicModel('claude-sonnet-4-6', provider=provider) agent = Agent(model) result = agent.run_sync('Where does "hello world" come from?') print(result.output) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.