> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portkey.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Pydantic AI

> Use Prisma AIRS AI Gateway with PydanticAI to take your AI Agents to production

## Introduction

PydanticAI is a Python agent framework designed to make it less painful to build production-grade applications with Generative AI. It brings the same ergonomic design and developer experience to GenAI that FastAPI brought to web development.

The AI Gateway enhances PydanticAI with production-readiness features, turning your experimental agents into robust systems by providing:

* **Complete observability** of every agent step, tool use, and interaction
* **Built-in reliability** with fallbacks, retries, and load balancing
* **Cost tracking and optimization** to manage your AI spend
* **Access to 3,000+ LLMs** through a single integration
* **Guardrails** to keep agent behavior safe and compliant
* **OpenTelemetry integration** for comprehensive monitoring

<Card title="PydanticAI Official Documentation" icon="arrow-up-right-from-square" href="https://ai.pydantic.dev/">
  Learn more about PydanticAI's core concepts and features
</Card>

### Installation & Setup

<Steps>
  <Step title="Install the required packages">
    ```bash theme={"system"}
    pip install -U pydantic-ai openai
    ```
  </Step>

  <Step title="Configure AI Gateway Client">
    Since the AI Gateway is OpenAI SDK compatible, you can use the standard OpenAI client with the AI Gateway URL:

    ```python theme={"system"}
    from openai import AsyncOpenAI
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIModel
    from pydantic_ai.providers.openai import OpenAIProvider

    # Set up the AI Gateway client using OpenAI SDK
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1"
    )
    ```
  </Step>

  <Step title="Connect to PydanticAI">
    After setting up your AI Gateway client, integrate it with PydanticAI:

    ```python theme={"system"}
    # Connect the AI Gateway client to a PydanticAI model
    agent = Agent(
        model=OpenAIModel(
            model_name="@openai-team-1/gpt-4o",  # Use the AI Gateway's model format
            provider=OpenAIProvider(openai_client=gateway_client),
        ),
        system_prompt="You are a helpful assistant."
    )
    ```
  </Step>
</Steps>

## Basic Agent Implementation

Let's create a simple structured output agent with PydanticAI and the AI Gateway. This agent will respond to a query about Formula 1 and return structured data:

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Set up the AI Gateway client
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1"
)

# Define structured output using Pydantic
class F1GrandPrix(BaseModel):
    gp_name: str = Field(description="Grand Prix name, e.g. `Emilia Romagna Grand Prix`")
    year: int = Field(description="The year of the Grand Prix")
    constructor_winner: str = Field(description="The winning constructor of the Grand Prix")
    podium: list[str] = Field(description="Names of the podium drivers (1st, 2nd, 3rd)")

# Create the agent with structured output type
f1_gp_agent = Agent[None, F1GrandPrix](
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    output_type=F1GrandPrix,
    system_prompt="Assist the user by providing data about the specified Formula 1 Grand Prix"
)

# Run the agent
async def main():
    result = await f1_gp_agent.run("Las Vegas 2023")
    print(result.output)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
```

The output will be a structured `F1GrandPrix` object with all fields properly typed and validated:

```json theme={"system"}
gp_name='Las Vegas Grand Prix'
year=2023
constructor_winner='Red Bull Racing'
podium=['Max Verstappen', 'Charles Leclerc', 'Sergio Pérez']
```

You can also use the synchronous API if preferred:

```python theme={"system"}
result = f1_gp_agent.run_sync("Las Vegas 2023")
print(result.output)
```

## Advanced Features

### Using AI Gateway Headers for Enhanced Features

When you need additional AI Gateway features like tracing, metadata, or configs, you can add headers to your client:

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Set up the AI Gateway client with additional features
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={
        "x-portkey-trace-id": "f1-data-request",
        "x-portkey-metadata": '{"app_env": "production", "_user": "user_123"}',
        "x-portkey-config": "your-config-id"
    }
)

# Create agent with enhanced AI Gateway features
agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    system_prompt="You are a helpful assistant."
)
```

### Working with Images

PydanticAI supports multimodal inputs including images. Here's how to use the AI Gateway with a vision model:

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic_ai import Agent, ImageUrl
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Set up the AI Gateway client
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={"x-portkey-trace-id": "vision-request"}
)

# Create a vision-capable agent
vision_agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",  # Vision-capable model
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    system_prompt="Analyze images and provide detailed descriptions."
)

# Process an image
result = vision_agent.run_sync([
    'What company is this logo from?',
    ImageUrl(url='https://iili.io/3Hs4FMg.png'),
])
print(result.output)
```

Visit Strata Cloud Manager to see detailed logs of this image analysis request, including token usage and costs.

### Tools and Tool Calls

PydanticAI provides a powerful tools system that integrates seamlessly with the AI Gateway. Here's how to create an agent with tools:

```python theme={"system"}
import random
from openai import AsyncOpenAI
from pydantic_ai import Agent, RunContext
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Set up the AI Gateway client
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={"x-portkey-trace-id": "dice-game-session"}
)

# Create an agent with dependency injection (player name)
dice_agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    deps_type=str,  # Dependency type (player name as string)
    system_prompt=(
        "You're a dice game host. Roll the die and see if it matches "
        "the user's guess. If so, tell them they're a winner. "
        "Use the player's name in your response."
    ),
)

# Define a plain tool (no context needed)
@dice_agent.tool_plain
def roll_die() -> str:
    """Roll a six-sided die and return the result."""
    return str(random.randint(1, 6))

# Define a tool that uses the dependency
@dice_agent.tool
def get_player_name(ctx: RunContext[str]) -> str:
    """Get the player's name."""
    return ctx.deps

# Run the agent
dice_result = dice_agent.run_sync('My guess is 4', deps='Anne')
print(dice_result.output)
```

<Info>
  AI Gateway logs each tool call separately, allowing you to analyze the full execution path of your agent, including both LLM calls and tool invocations.
</Info>

### Multi-agent Applications

PydanticAI excels at creating multi-agent systems where agents can call each other. Here's how to integrate the AI Gateway with a multi-agent setup:

This multi-agent system uses three specialized agents:
`search_agent` - Orchestrates the flow and validates flight selections
`extraction_agent` - Extracts structured flight data from raw text
`seat_preference_agent` - Interprets user's seat preferences

With AI Gateway integration, you get:

* Unified tracing across all three agents
* Token and cost tracking for the entire workflow
* Ability to set usage limits across the entire system
* Observability of both AI and human interaction points

Here's a diagram of how these agents interact:

```mermaid theme={"system"}
graph TD
  A[START] --> B[search agent]
  B --> C[extraction agent]
  C --> B
  B --> D[human confirm]
  D --> E[find seat function]
  B --> F[FAILED]
  E --> G[human seat choice]
  G --> H[find seat agent]
  H --> E
  E --> I[buy flights]
  I --> J[SUCCESS]
```

```python [expandable] theme={"system"}
import datetime
from dataclasses import dataclass
from typing import Literal

from pydantic import BaseModel, Field
from rich.prompt import Prompt

from pydantic_ai import Agent, ModelRetry, RunContext
from pydantic_ai.messages import ModelMessage
from pydantic_ai.usage import Usage, UsageLimits
from openai import AsyncOpenAI

# Set up the AI Gateway clients with shared trace ID for connected tracing
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={"x-portkey-trace-id": "flight-booking-session"}
)

# Define structured output types
class FlightDetails(BaseModel):
    """Details of the most suitable flight."""
    flight_number: str
    price: int
    origin: str = Field(description='Three-letter airport code')
    destination: str = Field(description='Three-letter airport code')
    date: datetime.date

class NoFlightFound(BaseModel):
    """When no valid flight is found."""

class SeatPreference(BaseModel):
    row: int = Field(ge=1, le=30)
    seat: Literal['A', 'B', 'C', 'D', 'E', 'F']

class Failed(BaseModel):
    """Unable to extract a seat selection."""

# Dependencies for flight search
@dataclass
class Deps:
    web_page_text: str
    req_origin: str
    req_destination: str
    req_date: datetime.date

# This agent is responsible for controlling the flow of the conversation
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

search_agent = Agent[Deps, FlightDetails | NoFlightFound](
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    output_type=FlightDetails | NoFlightFound,  # type: ignore
    retries=4,
    system_prompt=(
        'Your job is to find the cheapest flight for the user on the given date. '
    ),
    instrument=True,  # Enable instrumentation for better tracing
)

# This agent is responsible for extracting flight details from web page text
extraction_agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    output_type=list[FlightDetails],
    system_prompt='Extract all the flight details from the given text.',
)

# This agent is responsible for extracting the user's seat selection
seat_preference_agent = Agent[None, SeatPreference | Failed](
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    output_type=SeatPreference | Failed,  # type: ignore
    system_prompt=(
        "Extract the user's seat preference. "
        'Seats A and F are window seats. '
        'Row 1 is the front row and has extra leg room. '
        'Rows 14, and 20 also have extra leg room. '
    ),
)

@search_agent.tool
async def extract_flights(ctx: RunContext[Deps]) -> list[FlightDetails]:
    """Get details of all flights."""
    # Pass the usage to track nested agent calls
    result = await extraction_agent.run(ctx.deps.web_page_text, usage=ctx.usage)
    return result.output

@search_agent.output_validator
async def validate_output(
    ctx: RunContext[Deps], output: FlightDetails | NoFlightFound
) -> FlightDetails | NoFlightFound:
    """Procedural validation that the flight meets the constraints."""
    if isinstance(output, NoFlightFound):
        return output

    errors: list[str] = []
    if output.origin != ctx.deps.req_origin:
        errors.append(
            f'Flight should have origin {ctx.deps.req_origin}, not {output.origin}'
        )
    if output.destination != ctx.deps.req_destination:
        errors.append(
            f'Flight should have destination {ctx.deps.req_destination}, not {output.destination}'
        )
    if output.date != ctx.deps.req_date:
        errors.append(f'Flight should be on {ctx.deps.req_date}, not {output.date}')

    if errors:
        raise ModelRetry('\n'.join(errors))
    else:
        return output

# Sample flight data (in a real application, this would be from a web scraper)
flights_web_page = """
1. Flight SFO-AK123
- Price: $350
- Origin: San Francisco International Airport (SFO)
- Destination: Ted Stevens Anchorage International Airport (ANC)
- Date: January 10, 2025

2. Flight SFO-AK456
- Price: $370
- Origin: San Francisco International Airport (SFO)
- Destination: Fairbanks International Airport (FAI)
- Date: January 10, 2025

... more flights ...
"""

# Main application flow
async def main():
    # Restrict how many requests this app can make to the LLM
    usage_limits = UsageLimits(request_limit=15)

    deps = Deps(
        web_page_text=flights_web_page,
        req_origin='SFO',
        req_destination='ANC',
        req_date=datetime.date(2025, 1, 10),
    )
    message_history: list[ModelMessage] | None = None
    usage: Usage = Usage()

    # Run the agent until a satisfactory flight is found
    while True:
        result = await search_agent.run(
            f'Find me a flight from {deps.req_origin} to {deps.req_destination} on {deps.req_date}',
            deps=deps,
            usage=usage,
            message_history=message_history,
            usage_limits=usage_limits,
        )
        if isinstance(result.output, NoFlightFound):
            print('No flight found')
            break
        else:
            flight = result.output
            print(f'Flight found: {flight}')
            answer = Prompt.ask(
                'Do you want to buy this flight, or keep searching? (buy/*search)',
                choices=['buy', 'search', ''],
                show_choices=False,
            )
            if answer == 'buy':
                seat = await find_seat(usage, usage_limits)
                await buy_tickets(flight, seat)
                break
            else:
                message_history = result.all_messages(
                    output_tool_return_content='Please suggest another flight'
                )

async def find_seat(usage: Usage, usage_limits: UsageLimits) -> SeatPreference:
    message_history: list[ModelMessage] | None = None
    while True:
        answer = Prompt.ask('What seat would you like?')
        result = await seat_preference_agent.run(
            answer,
            message_history=message_history,
            usage=usage,
            usage_limits=usage_limits,
        )
        if isinstance(result.output, SeatPreference):
            return result.output
        else:
            print('Could not understand seat preference. Please try again.')
            message_history = result.all_messages()

async def buy_tickets(flight_details: FlightDetails, seat: SeatPreference):
    print(f'Purchasing flight {flight_details=!r} {seat=!r}...')
```

The AI Gateway preserves all the type safety of PydanticAI while adding production monitoring and reliability.

## Production Features

### 1. Enhanced Observability

The AI Gateway provides comprehensive observability for your PydanticAI agents, helping you understand exactly what's happening during each execution.

<Tabs>
  <Tab title="Traces">
    Traces provide a hierarchical view of your agent's execution, showing the sequence of LLM calls, tool invocations, and state transitions.

    ```python theme={"system"}
    # Add trace_id to enable hierarchical tracing in the AI Gateway
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1",
        default_headers={"x-portkey-trace-id": "unique-session-id"}
    )
    ```
  </Tab>

  <Tab title="Logs">
    AI Gateway logs every interaction with LLMs, including:

    * Complete request and response payloads
    * Latency and token usage metrics
    * Cost calculations
    * Tool calls and function executions

    All logs can be filtered by metadata, trace IDs, models, and more, making it easy to debug specific agent runs.
  </Tab>

  <Tab title="Metrics & Dashboards">
    The AI Gateway provides built-in dashboards that help you:

    * Track cost and token usage across all agent runs
    * Analyze performance metrics like latency and success rates
    * Identify bottlenecks in your agent workflows
    * Compare different agent configurations and LLMs

    You can filter and segment all metrics by custom metadata to analyze specific agent types, user groups, or use cases.
  </Tab>

  <Tab title="Metadata Filtering">
    Add custom metadata to your PydanticAI agent calls to enable powerful filtering and segmentation:

    ```python theme={"system"}
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1",
        default_headers={
            "x-portkey-metadata": '{"agent_type": "weather_agent", "environment": "production", "_user": "user_123", "request_source": "mobile_app"}'
        }
    )
    ```

    This metadata can be used to filter logs, traces, and metrics on Strata Cloud Manager, allowing you to analyze specific agent runs, users, or environments.
  </Tab>
</Tabs>

### 2. OpenTelemetry Integration

For comprehensive monitoring and observability, the AI Gateway supports OpenTelemetry integration through various libraries:

```python theme={"system"}
import openlit

# Initialize OpenLit with the AI Gateway's OTel endpoint
openlit.init(
    otlp_endpoint="https://aigw.portkey.ai/v1/otel",
    otlp_headers={
        "Authorization": "Bearer YOUR_PORTKEY_API_KEY"
    }
)

# Your PydanticAI agents will now send telemetry data to the AI Gateway
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1"
)

agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    system_prompt="You are a helpful assistant."
)
```

<Card title="OpenTelemetry Documentation" icon="chart-line" href="/docs/aigw/product/observability/opentelemetry">
  Learn more about the AI Gateway's OpenTelemetry integration and supported libraries
</Card>

### 3. Reliability - Keep Your Agents Running Smoothly

When running agents in production, things can go wrong - API rate limits, network issues, or provider outages. The AI Gateway's reliability features ensure your agents keep running smoothly even when problems occur.

It's simple to enable fallback in your PydanticAI agents by using an AI Gateway Config:

```python theme={"system"}
from openai import AsyncOpenAI

# Create the AI Gateway client with fallback config
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={
        "x-portkey-config": "your-fallback-config-id"
    }
)
```

This configuration will automatically try Claude if the GPT-4o request fails, ensuring your agent can continue operating.

<CardGroup cols="2">
  <Card title="Automatic Retries" icon="rotate" href="../../product/ai-gateway/automatic-retries">
    Handles temporary failures automatically. If an LLM call fails, the AI Gateway will retry the same request for the specified number of times - perfect for rate limits or network blips.
  </Card>

  <Card title="Request Timeouts" icon="clock" href="../../product/ai-gateway/request-timeouts">
    Prevent your agents from hanging. Set timeouts to ensure you get responses (or can fail gracefully) within your required timeframes.
  </Card>

  <Card title="Conditional Routing" icon="route" href="../../product/ai-gateway/conditional-routing">
    Send different requests to different providers. Route complex reasoning to GPT-4, creative tasks to Claude, and quick responses to Gemini based on your needs.
  </Card>

  <Card title="Fallbacks" icon="shield" href="../../product/ai-gateway/fallbacks">
    Keep running even if your primary provider fails. Automatically switch to backup providers to maintain availability.
  </Card>

  <Card title="Load Balancing" icon="scale-balanced" href="../../product/ai-gateway/load-balancing">
    Spread requests across multiple API keys or providers. Great for high-volume agent operations and staying within rate limits.
  </Card>
</CardGroup>

### 4. Guardrails for Safe Agents

Guardrails ensure your PydanticAI agents operate safely and respond appropriately in all situations.

**Why Use Guardrails?**

PydanticAI agents can experience various failure modes:

* Generating harmful or inappropriate content
* Leaking sensitive information like PII
* Hallucinating incorrect information
* Generating outputs in incorrect formats

While PydanticAI provides type safety for outputs, the AI Gateway's guardrails add additional protections for both inputs and outputs.

**Implementing Guardrails**

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Create the AI Gateway client with guardrails
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={
        "x-portkey-config": "your-guardrails-config-id"
    }
)

# Create agent with Portkey-enabled client
agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    system_prompt="You are a helpful assistant."
)
```

The AI Gateway's guardrails can:

* Detect and redact PII in both inputs and outputs
* Filter harmful or inappropriate content
* Validate response formats against schemas
* Check for hallucinations against ground truth
* Apply custom business logic and rules

<Card title="Learn More About Guardrails" icon="shield-check" href="/docs/aigw/product/guardrails">
  Explore the AI Gateway's guardrail features to enhance agent safety
</Card>

### 5. User Tracking with Metadata

Track individual users through your PydanticAI agents using the AI Gateway's metadata system.

**What is Metadata in the AI Gateway?**

Metadata allows you to associate custom data with each request, enabling filtering, segmentation, and analytics. The special `_user` field is specifically designed for user tracking.

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# Configure client with user tracking
gateway_client = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1",
    default_headers={
        "x-portkey-metadata": '{"_user": "user_123", "user_tier": "premium", "user_company": "Acme Corp", "session_id": "abc-123"}'
    }
)

# Create agent with the AI Gateway client
agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=gateway_client),
    ),
    system_prompt="You are a helpful assistant."
)
```

**Filter Analytics by User**

With metadata in place, you can filter analytics by user and analyze performance metrics on a per-user basis:

This enables:

* Per-user cost tracking and budgeting
* Personalized user analytics
* Team or organisation-level metrics
* Environment-specific monitoring (staging vs. production)

<Card title="Learn More About Metadata" icon="tags" href="/docs/aigw/product/observability/metadata">
  Explore how to use custom metadata to enhance your analytics
</Card>

### 6. Caching for Efficient Agents

Implement caching to make your PydanticAI agents more efficient and cost-effective:

<Tabs>
  <Tab title="Simple Caching">
    ```python theme={"system"}
    from openai import AsyncOpenAI
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIModel
    from pydantic_ai.providers.openai import OpenAIProvider

    # Configure the AI Gateway client with simple caching
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1",
        default_headers={
            "x-portkey-config": "your-simple-cache-config-id"
        }
    )

    # Create agent with cached LLM calls
    agent = Agent(
        model=OpenAIModel(
            model_name="@openai-team-1/gpt-4o",
            provider=OpenAIProvider(openai_client=gateway_client),
        ),
        system_prompt="You are a helpful assistant."
    )
    ```

    Simple caching performs exact matches on input prompts, caching identical requests to avoid redundant model executions.
  </Tab>

  <Tab title="Semantic Caching">
    ```python theme={"system"}
    from openai import AsyncOpenAI
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIModel
    from pydantic_ai.providers.openai import OpenAIProvider

    # Configure the AI Gateway client with semantic caching
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1",
        default_headers={
            "x-portkey-config": "your-semantic-cache-config-id"
        }
    )

    # Create agent with semantically cached LLM calls
    agent = Agent(
        model=OpenAIModel(
            model_name="@openai-team-1/gpt-4o",
            provider=OpenAIProvider(openai_client=gateway_client),
        ),
        system_prompt="You are a helpful assistant."
    )
    ```

    Semantic caching considers the contextual similarity between input requests, caching responses for semantically similar inputs.
  </Tab>
</Tabs>

### 7. Model Interoperability

PydanticAI supports multiple LLM providers, and the AI Gateway extends this capability by providing access to over 200 LLMs through a unified interface. You can easily switch between different models without changing your core agent logic:

```python theme={"system"}
from openai import AsyncOpenAI
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider

# OpenAI with the AI Gateway
portkey_openai = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1"
)

# Anthropic with the AI Gateway
portkey_anthropic = AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY",
    base_url="https://aigw.portkey.ai/v1"
)

# Create agents with different models
openai_agent = Agent(
    model=OpenAIModel(
        model_name="@openai-team-1/gpt-4o",
        provider=OpenAIProvider(openai_client=portkey_openai),
    ),
    system_prompt="You are a helpful assistant."
)

anthropic_agent = Agent(
    model=OpenAIModel(
        model_name="@anthropic-team-1/claude-3-5-sonnet-20241022",
        provider=OpenAIProvider(openai_client=portkey_anthropic),
    ),
    system_prompt="You are a helpful assistant."
)

# Choose which agent to use based on your needs
active_agent = openai_agent  # or anthropic_agent

result = active_agent.run_sync("Tell me about quantum computing.")
print(result.output)
```

The AI Gateway provides access to LLMs from providers including:

* OpenAI (GPT-4o, GPT-4 Turbo, etc.)
* Anthropic (Claude 3.5 Sonnet, Claude 3 Opus, etc.)
* Mistral AI (Mistral Large, Mistral Medium, etc.)
* Google Vertex AI (Gemini 1.5 Pro, etc.)
* Cohere (Command, Command-R, etc.)
* AWS Bedrock (Claude, Titan, etc.)
* Local/Private Models

<Card title="Supported Providers" icon="server" href="/docs/aigw/integrations/llms">
  See the full list of LLM providers supported by the AI Gateway
</Card>

## Set Up Enterprise Governance for PydanticAI

**Why Enterprise Governance?**
If you are using PydanticAI inside your organisation, you need to consider several governance aspects:

* **Cost Management**: Controlling and tracking AI spending across teams
* **Access Control**: Managing which teams can use specific models
* **Usage Analytics**: Understanding how AI is being used across the organisation
* **Security & Compliance**: Maintaining enterprise security standards
* **Reliability**: Ensuring consistent service across all users

The AI Gateway adds a comprehensive governance layer to address these enterprise needs. Let's implement these controls step by step.

<Steps>
  <Step title="Create API Key with Config">
    Since the AI Gateway uses the model format `@provider-slug/model-name`, you can specify your AI Provider and model directly. Create an AI Gateway API key with an attached config:

    1. Go to [API Keys](https://stratacloudmanager.paloaltonetworks.com/) in the AI Gateway and Create new API key
    2. Optionally attach a config for advanced routing, fallbacks, and reliability features
    3. Generate and save your API key
  </Step>

  <Step title="Configure Model Access">
    Use the AI Gateway's model naming format to specify which team/provider can access which models:

    ```python theme={"system"}
    from openai import AsyncOpenAI
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIModel
    from pydantic_ai.providers.openai import OpenAIProvider

    # Configure the AI Gateway client with team-specific model access
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1"
    )

    # Create agent with team-specific model
    agent = Agent(
        model=OpenAIModel(
            model_name="@engineering-team/gpt-4o",  # Team-specific model access
            provider=OpenAIProvider(openai_client=gateway_client),
        ),
        system_prompt="You are a helpful assistant."
    )
    ```
  </Step>

  <Step title="Add Enhanced Features with Headers">
    For additional governance features like tracing, metadata, and configs, add headers as needed:

    ```python theme={"system"}
    from openai import AsyncOpenAI
    from pydantic_ai import Agent
    from pydantic_ai.models.openai import OpenAIModel
    from pydantic_ai.providers.openai import OpenAIProvider

    # Configure the AI Gateway client with governance features
    gateway_client = AsyncOpenAI(
        api_key="YOUR_PORTKEY_API_KEY",
        base_url="https://aigw.portkey.ai/v1",
        default_headers={
            "x-portkey-trace-id": "engineering-session",
            "x-portkey-metadata": '{"department": "engineering", "environment": "production"}',
            "x-portkey-config": "your-governance-config-id"
        }
    )

    # Create agent with governance controls
    agent = Agent(
        model=OpenAIModel(
            model_name="@engineering-team/gpt-4o",
            provider=OpenAIProvider(openai_client=gateway_client),
        ),
        system_prompt="You are a helpful assistant."
    )
    ```
  </Step>
</Steps>

<AccordionGroup>
  <Accordion title="Step 1: Implement Budget Controls & Rate Limits">
    ### Step 1: Implement Budget Controls & Rate Limits

    Create configs that enable granular control over LLM access at the team/department level. This helps you:

    * Set up budget limits through usage tracking
    * Prevent unexpected usage spikes using rate limits
    * Track departmental spending

    #### Setting Up Department-Specific Controls:

    1. Navigate to [Configs](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager
    2. Create new config for each department with appropriate controls
    3. Configure department-specific limits and routing
  </Accordion>

  <Accordion title="Step 2: Define Model Access Rules">
    ### Step 2: Define Model Access Rules

    As your AI usage scales, controlling which teams can access specific models becomes crucial. The AI Gateway's model naming format and configs provide this control layer with features like:

    #### Access Control Features:

    * **Model Restrictions**: Limit access to specific models using team prefixes
    * **Data Protection**: Implement guardrails for sensitive data
    * **Reliability Controls**: Add fallbacks and retry logic

    #### Example Configuration:

    Here's a basic configuration to route requests to OpenAI, specifically using GPT-4o for the engineering team:

    ```json theme={"system"}
    {
      "override_params": { "model": "@openai-prod/gpt-4o" }
    }
    ```

    Create your config on the [Configs page](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager.

    <Note>
      Configs can be updated anytime to adjust controls without affecting running applications.
    </Note>
  </Accordion>

  <Accordion title="Step 3: Implement Access Controls">
    ### Step 3: Implement Access Controls

    Create team-specific API keys that automatically:

    * Track usage per user/team with metadata
    * Apply appropriate configs to route requests
    * Collect relevant metadata to filter logs
    * Enforce access permissions

    Create API keys through:

    * [Strata Cloud Manager](https://stratacloudmanager.paloaltonetworks.com/)
    * [API Key Management API](/docs/api-reference/admin-api/control-plane/api-keys/create-api-key)

    Example using Python SDK:

    For detailed key management instructions, see our [API Keys documentation](/docs/api-reference/admin-api/control-plane/api-keys/create-api-key).
  </Accordion>

  <Accordion title="Step 4: Deploy & Monitor">
    ### Step 4: Deploy & Monitor

    After distributing API keys to your team members, your enterprise-ready PydanticAI setup is ready to go. Each team member can now use their designated API keys with appropriate access levels and governance controls.

    Monitor usage in Strata Cloud Manager:

    * Cost tracking by department
    * Model usage patterns
    * Request volumes
    * Error rates
  </Accordion>
</AccordionGroup>

<Note>
  ### Enterprise Features Now Available

  **Your PydanticAI integration now has:**

  * Team-based model access controls
  * Usage tracking & attribution
  * Governance through configs
  * Security guardrails
  * Reliability features
</Note>

## Frequently Asked Questions

<AccordionGroup>
  <Accordion title="How does the AI Gateway enhance PydanticAI?">
    The AI Gateway adds production-readiness to PydanticAI through comprehensive observability (traces, logs, metrics), reliability features (fallbacks, retries, caching), and access to 3,000+ LLMs through a unified interface. This makes it easier to debug, optimize, and scale your agent applications, all while preserving PydanticAI's strong type safety.
  </Accordion>

  <Accordion title="Can I use the AI Gateway with existing PydanticAI applications?">
    Yes! The AI Gateway integrates seamlessly with existing PydanticAI applications. You just need to replace your OpenAI client initialization with the gateway-enabled version using our gateway URL. The rest of your agent code remains unchanged and continues to benefit from PydanticAI's strong typing.
  </Accordion>

  <Accordion title="Does the AI Gateway work with all PydanticAI features?">
    The AI Gateway supports all PydanticAI features, including structured outputs, tool use, multi-agent systems, and more. It adds observability and reliability without limiting any of the framework's functionality.
  </Accordion>

  <Accordion title="Can I track usage across multiple agents in a workflow?">
    Yes, the AI Gateway allows you to use a consistent `x-portkey-trace-id` header across multiple agents and requests to track the entire workflow. This is especially useful for multi-agent systems where you want to understand the full execution path.
  </Accordion>

  <Accordion title="How do I filter logs and traces for specific agent runs?">
    The AI Gateway allows you to add custom metadata through the `x-portkey-metadata` header to your agent runs, which you can then use for filtering. Add fields like `agent_name`, `agent_type`, or `session_id` to easily find and analyze specific agent executions.
  </Accordion>

  <Accordion title="Can I use my own API keys with the AI Gateway?">
    Yes! The AI Gateway uses your own API keys for the various LLM providers. Add them to Model Catalog to manage, rotate, and set limits without changing your code.
  </Accordion>
</AccordionGroup>

## Resources

<CardGroup cols="3">
  <Card title="PydanticAI Docs" icon="book" href="https://ai.pydantic.dev/">
    <p>Official PydanticAI documentation</p>
  </Card>

  <Card title="AI Gateway Docs" icon="book" href="/docs/aigw/introduction/welcome">
    <p>Official AI Gateway documentation</p>
  </Card>
</CardGroup>


## Related topics

- [Overview](/docs/aigw/integrations/agents.md)
- [AWS AgentCore](/docs/aigw/integrations/agents/agentcore.md)
- [Pydantic Logfire](/docs/aigw/integrations/tracing-providers/logfire.md)
- [Controlled Generations](/docs/aigw/integrations/llms/vertex-ai/controlled-generations.md)
- [Anthropic](/docs/aigw/integrations/llms/anthropic.md)
