> ## 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.

# OpenAI Agents SDK (Python)

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

## Introduction

OpenAI Agents SDK enables the development of complex AI agents with tools, planning, and memory capabilities. The AI Gateway enhances OpenAI Agents with observability, reliability, and production-readiness features.

The AI Gateway turns your experimental OpenAI Agents into production-ready 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
* **Version-controlled prompts** for consistent agent performance

<Card title="OpenAI Agents SDK Official Documentation" icon="arrow-up-right-from-square" href="https://openai.github.io/openai-agents-python/">
  Learn more about OpenAI Agents SDK's core concepts
</Card>

### Installation & Setup

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

  <Step title="Generate API Key">
    Create an AI Gateway API key with optional budget/rate limits and attach your Config
  </Step>

  <Step title="Connect to OpenAI Agents">
    There are 3 ways to integrate the AI Gateway with OpenAI Agents:

    1. Set a client that applies to all agents in your application
    2. Use a custom provider for selective AI Gateway integration
    3. Configure each agent individually

    See the [Integration Approaches](#integration-approaches) section for more details.
  </Step>

  <Step title="Configure AI Gateway Client">
    For a simple setup, we'll use the global client approach:

    ```python theme={"system"}
    from agents import (
        set_default_openai_client,
        set_default_openai_api,
        Agent, Runner
    )
    from openai import AsyncOpenAI
    import os

    # Set up the AI Gateway as the global client
    gateway = AsyncOpenAI(
        base_url="https://aigw.portkey.ai/v1",
        api_key=os.environ["PORTKEY_API_KEY"],
        default_headers={"x-portkey-provider": "@YOUR_OPENAI_PROVIDER"}
    )

    # Register as the SDK-wide default
    set_default_openai_client(gateway, use_for_tracing=False)
    set_default_openai_api("chat_completions")  # Responses API → Chat
    ```
  </Step>
</Steps>

### Getting Started

Let's create a simple question-answering agent with OpenAI Agents SDK and the AI Gateway. This agent will respond directly to user messages using a language model:

```python theme={"system"}
from agents import (
    set_default_openai_client,
    set_default_openai_api,
    Agent, Runner
)
from openai import AsyncOpenAI
import os

# Set up the AI Gateway as the global client
gateway = AsyncOpenAI(
    base_url="https://aigw.portkey.ai/v1",
    api_key=os.environ["PORTKEY_API_KEY"]
)

# Register as the SDK-wide default
set_default_openai_client(gateway, use_for_tracing=False)
set_default_openai_api("chat_completions")  # Responses API → Chat

# Create agent with any supported model
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    model="@YOUR_OPENAI_PROVIDER/gpt-4o"  # Using OpenAI GPT-4o through the AI Gateway
)

# Run the agent
result = Runner.run_sync(agent, "Tell me about quantum computing.")
print(result.final_output)
```

In this example:

1. We set up the AI Gateway as the global client for OpenAI Agents SDK
2. We create a simple agent with instructions and a model
3. We run the agent synchronously with a user query
4. We print the final output

Visit Strata Cloud Manager to see detailed logs of this agent's execution!

### Integration Approaches

There are three ways to integrate the AI Gateway with OpenAI Agents SDK, each suited for different scenarios:

<Tabs>
  <Tab title="Global Default Client">
    Set a global client that affects all agents in your application:

    ```python theme={"system"}
    from agents import (
        set_default_openai_client,
        set_default_openai_api,
        set_tracing_disabled,
        Agent, Runner
    )
    from openai import AsyncOpenAI
    import os

    # Set up the AI Gateway as the global client
    gateway = AsyncOpenAI(
        base_url="https://aigw.portkey.ai/v1",
        api_key=os.environ["PORTKEY_API_KEY"]
    )

    # Register it as the SDK-wide default
    set_default_openai_client(gateway, use_for_tracing=False)   # skip OpenAI tracing
    set_default_openai_api("chat_completions")                  # Responses API → Chat
    set_tracing_disabled(True)                                  # optional

    # Regular agent code—just a model name
    agent = Agent(
        name="Haiku Writer",
        instructions="Respond only in haikus.",
        model="@YOUR_OPENAI_PROVIDER/claude-3-7-sonnet-latest"
    )

    print(Runner.run_sync(agent, "Write a haiku on recursion.").final_output)
    ```

    **Best for**: Whole application migration to the AI Gateway with minimal code changes
  </Tab>

  <Tab title="ModelProvider with RunConfig">
    Use a custom ModelProvider to control which runs use the AI Gateway:

    ```python theme={"system"}
    from agents import (
        Model,
        ModelProvider,
        RunConfig,
        Runner,
        Agent
    )
    from agents import OpenAIChatCompletionsModel           # concrete Model
    from openai import AsyncOpenAI
    import os, asyncio

    client = AsyncOpenAI(
        base_url="https://aigw.portkey.ai/v1",
        api_key=os.environ["PORTKEY_API_KEY"],
        default_headers={"x-portkey-provider": "@YOUR_OPENAI_PROVIDER"}
    )

    class PortkeyProvider(ModelProvider):
        def get_model(self, model_name: str | None) -> Model:
            return OpenAIChatCompletionsModel(
                model=model_name or "claude-3-7-sonnet-latest",
                openai_client=client
            )

    PORTKEY = PortkeyProvider()                              # singleton is fine

    async def main():
        agent = Agent(name="Assistant", instructions="Haikus only.")
        run_cfg = RunConfig(model_provider=PORTKEY)

        # Only this call uses the AI Gateway
        out = await Runner.run(agent, "Weather in Tokyo?", run_config=run_cfg)
        print(out.final_output)

    asyncio.run(main())
    ```

    **Best for**: A/B testing, staged rollouts, or toggling between providers at runtime
  </Tab>

  <Tab title="Per-Agent Model Object">
    Attach a specific Model object to each Agent:

    ```python theme={"system"}
    from agents import Agent, Runner, OpenAIChatCompletionsModel
    from openai import AsyncOpenAI
    import os

    gateway_client = AsyncOpenAI(
        base_url="https://aigw.portkey.ai/v1",
        api_key=os.environ["PORTKEY_API_KEY"]
    )

    agent = Agent(
        name="Haiku Writer",
        instructions="Classic Japanese form.",
        model=OpenAIChatCompletionsModel(  # concrete Model
            model="@YOUR_OPENAI_PROVIDER/claude-3-7-sonnet-latest",
            openai_client=gateway_client
        ),
    )

    print(Runner.run_sync(agent, "Recursion haiku.").final_output)
    ```

    **Best for**: Mixed agent environments where different agents need different providers or configurations
  </Tab>
</Tabs>

**Comparing the 3 approaches**

| Strategy                                          | Code Touchpoints                              | Best For                                                  |
| :------------------------------------------------ | :-------------------------------------------- | :-------------------------------------------------------- |
| **Global Client** via `set_default_openai_client` | One-time setup; agents need only model names  | Whole app uses the AI Gateway; simplest migration         |
| **ModelProvider in RunConfig**                    | Add a provider + pass `run_config`            | Toggle the AI Gateway per run; A/B tests, staged rollouts |
| **Explicit Model per Agent**                      | Specify `OpenAIChatCompletionsModel` in agent | Mixed fleet: each agent can talk to a different provider  |

## End-to-End Example

**Research Agent with Tools**: Here's a more comprehensive agent that can use tools to perform tasks.

```python [expandable] theme={"system"}
from agents import Agent, Runner, Tool, set_default_openai_client
from openai import AsyncOpenAI
import os

# Configure the AI Gateway client
gateway = AsyncOpenAI(
    api_key=os.environ.get("PORTKEY_API_KEY"),
    base_url="https://aigw.portkey.ai/v1"
)
set_default_openai_client(gateway)

# Define agent tools
def get_weather(location: str) -> str:
    """Get the current weather for a location."""
    return f"It's 72°F and sunny in {location}."

def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Found information about: {query}"

# Create agent with tools
agent = Agent(
    name="Research Assistant",
    instructions="You are a helpful assistant that can search for information and check the weather.",
    model="@YOUR_OPENAI_PROVIDER/claude-3-opus-20240229",
    tools=[
        Tool(
            name="get_weather",
            description="Get current weather for a location",
            input_schema={
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA"
                }
            },
            callback=get_weather
        ),
        Tool(
            name="search_web",
            description="Search the web for information",
            input_schema={
                "query": {
                    "type": "string",
                    "description": "Search query"
                }
            },
            callback=search_web
        )
    ]
)

# Run the agent
result = Runner.run_sync(
    agent,
    "What's the weather in San Francisco and find information about Golden Gate Bridge?"
)
print(result.final_output)
```

Visit Strata Cloud Manager to see the complete execution flow visualized!

***

## Production Features

### 1. Enhanced Observability

The AI Gateway provides comprehensive observability for your OpenAI 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 tracing to your OpenAI Agents
      gateway = AsyncOpenAI(
          base_url="https://aigw.portkey.ai/v1",
          api_key=os.environ["PORTKEY_API_KEY"],
          default_headers={
              "x-portkey-provider": "@YOUR_OPENAI_PROVIDER",
              # Add unique trace ID
              "x-portkey-trace-id": "unique_execution_trace_id",
          }
      )
      set_default_openai_client(gateway)
    ```
  </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 OpenAI agent calls to enable powerful filtering and segmentation:

    ```python theme={"system"}

      import json
      # Add tracing to your OpenAI Agents
      gateway = AsyncOpenAI(
          base_url="https://aigw.portkey.ai/v1",
          api_key=os.environ["PORTKEY_API_KEY"],
          default_headers={
              "x-portkey-provider": "@YOUR_OPENAI_PROVIDER",
              # Add custom metadata
              "x-portkey-metadata": json.dumps({"agent_type": "research_agent"}),
          }
      )
      set_default_openai_client(gateway)
    ```

    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. 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 this simple to enable fallback in your OpenAI Agents:

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

# Create a config with fallbacks, Prefer creating the Config in Strata Cloud Manager over hard-coding the config JSON
config = {
  "strategy": {
    "mode": "fallback"
  },
  "targets": [
    {
      "provider": "openai",
      "override_params": {"model": "gpt-4o"}
    },
    {
      "provider": "anthropic",
      "override_params": {"model": "claude-3-opus-20240229"}
    }
  ]
}

# Configure the AI Gateway client with fallback config
gateway = AsyncOpenAI(
    base_url="https://aigw.portkey.ai/v1",
    api_key=os.environ["PORTKEY_API_KEY"],
    default_headers={"x-portkey-config": json.dumps(config)}
)
set_default_openai_client(gateway)
```

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>

### 3. Prompting in OpenAI Agents

The AI Gateway's Prompt Engineering Studio helps you create, manage, and optimize the prompts used in your OpenAI Agents. Instead of hardcoding prompts or instructions, use the AI Gateway's prompt rendering API to dynamically fetch and apply your versioned prompts.

<Tabs>
  <Tab title="Prompt Playground">
    Prompt Playground is a place to compare, test and deploy perfect prompts for your AI application. It’s where you experiment with different models, test variables, compare outputs, and refine your prompt engineering strategy before deploying to production. It allows you to:

    1. Iteratively develop prompts before using them in your agents
    2. Test prompts with different variables and models
    3. Compare outputs between different prompt versions
    4. Collaborate with team members on prompt development

    This visual environment makes it easier to craft effective prompts for each step in your OpenAI Agents agent's workflow.
  </Tab>

  <Tab title="Using Prompt Templates">
    The Prompt Render API retrieves your prompt templates with all parameters configured:
  </Tab>

  <Tab title="Prompt Versioning">
    You can:

    * Create multiple versions of the same prompt
    * Compare performance between versions
    * Roll back to previous versions if needed
    * Specify which version to use in your request
  </Tab>

  <Tab title="Mustache Templating for variables">
    AI Gateway prompts use Mustache-style templating for easy variable substitution:

    ```
    You are an AI assistant helping with {{task_type}}.

    User question: {{user_input}}

    Please respond in a {{tone}} tone and include {{required_elements}}.
    ```

    When rendering, simply pass the variables:
  </Tab>
</Tabs>

### 4. Guardrails for Safe Agents

Guardrails ensure your OpenAI Agents operate safely and respond appropriately in all situations.

**Why Use Guardrails?**

OpenAI Agents can experience various failure modes:

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

The AI Gateway's guardrails protect against these issues by validating both inputs and outputs.

**Implementing Guardrails**

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

# Create a config with input and output guardrails, Prefer creating the Config in Strata Cloud Manager and passing the config ID in the client
config = {
    "provider":"@openai-xxx",
    "input_guardrails": ["guardrails-id-xxx", "guardrails-id-yyy"],
    "output_guardrails": ["guardrails-id-xxx"]
}

# Configure OpenAI client with guardrails
gateway = AsyncOpenAI(
    base_url="https://aigw.portkey.ai/v1",
    api_key=os.environ["PORTKEY_API_KEY"],
    default_headers={"x-portkey-provider": "@YOUR_OPENAI_PROVIDER", "x-portkey-config": json.dumps(config)}
)
set_default_openai_client(gateway)
```

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 OpenAI 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.

**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 OpenAI Agents agents more efficient and cost-effective:

<Tabs>
  <Tab title="Simple Caching">
    ```python theme={"system"}
    import json
    gateway_config = {
      "cache": {
        "mode": "simple"
      },
      "provider":"@YOUR_LLM_PROVIDER"
    }

    # Configure OpenAI client with chosen provider
    gateway = AsyncOpenAI(
        base_url="https://aigw.portkey.ai/v1",
        api_key=os.environ["PORTKEY_API_KEY"],
        default_headers={"x-portkey-config": json.dumps(gateway_config)}
    )
    set_default_openai_client(gateway)
    ```

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

  <Tab title="Semantic Caching">
    ```python theme={"system"}
      import json
      gateway_config = {
        "cache": {
          "mode": "semantic"
        },
        "provider":"@YOUR_LLM_PROVIDER"
      }

      # Configure OpenAI client with chosen provider
      gateway = AsyncOpenAI(
          base_url="https://aigw.portkey.ai/v1",
          api_key=os.environ["PORTKEY_API_KEY"],
          default_headers={"x-portkey-config": json.dumps(gateway_config)}
      )
      set_default_openai_client(gateway)
    ```

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

### 7. Model Interoperability

With the AI Gateway, you can easily switch between different LLMs in your OpenAI Agents without changing your core agent logic.

```python theme={"system"}
import json
# Configure the AI Gateway with different LLM providers
from openai import AsyncOpenAI
from agents import set_default_openai_client

# Using OpenAI
openai_config = {
    "provider": "@openai-prod",
    "override_params": {"model": "gpt-4o"}
}

# Using Anthropic
anthropic_config = {
    "provider": "@anthropic-prod",
    "override_params": {"model": "claude-3-5-sonnet-latest"}
}

# Choose which config to use
active_config = openai_config  # or anthropic_config

# Configure OpenAI client with chosen provider
gateway = AsyncOpenAI(
    base_url="https://aigw.portkey.ai/v1",
    api_key=os.environ["PORTKEY_API_KEY"],
    default_headers={"x-portkey-config": json.dumps(active_config)}
)
set_default_openai_client(gateway)

# Create and run agent - no changes needed in agent code
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant.",
    # The model specified here will be used as a reference but the actual model
    # is determined by the active_config
    model="gpt-4o"
)

result = Runner.run_sync(agent, "Tell me about quantum computing.")
print(result.final_output)
```

The AI Gateway provides access to over 200 LLMs through a unified interface, 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>

### 8. Tracing

The AI Gateway provides an opentelemetry compatible backend to store and query your traces.

You can trace your OpenAI Agents using any OpenTelemetry compatible tracing library.

Here is an example of how to trace your OpenAI Agents using the [`logfire`](/docs/aigw/integrations/tracing-providers/logfire) library from Pydantic:

```python Python theme={"system"}
import logfire
from pydantic import BaseModel
from agents import Agent, Runner, function_tool
import asyncio
import os

os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] =  "https://api.portkey.com/v1/logs/otel"
os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Bearer {YOUR_PORTKEY_API_KEY}"

class Weather(BaseModel):
    city: str
    temperature_range: str
    conditions: str

@function_tool
def get_weather(city: str) -> Weather:
    return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")

agent = Agent(
    name="Hello world",
    instructions="You are a helpful agent.",
    tools=[get_weather]
)

async def main():
    logfire.configure(
        service_name='my_agent_service',
        send_to_logfire=False,
    )
    logfire.instrument_openai_agents()
    result = await Runner.run(agent, input="What's the weather in Tokyo?")
    print(result.final_output)

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

## Tool Use in OpenAI Agents

OpenAI Agents SDK natively supports tools that enable your agents to interact with external systems and APIs. The AI Gateway provides full observability for tool usage in your agents:

## Set Up Enterprise Governance for OpenAI Agents

**Why Enterprise Governance?**
If you are using OpenAI Agents inside your orgnaization, 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.

**Enterprise Implementation Guide**

The AI Gateway allows you to use 3,000+ LLMs with your OpenAI Agents setup, with minimal configuration required. Let's set up the core components in the AI Gateway that you'll need for integration.

<Steps>
  <Step title="Add an AI Provider">
    Add your LLM provider credentials to Model Catalog. This gives you centralized control with:

    * Budget limits per provider
    * Rate limiting capabilities
    * Secure credential storage

    Go to [Model Catalog](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager and add your provider. Copy the AI Provider slug — you'll need it for the next step.
  </Step>

  <Step title="Create Default Config">
    Configs in the AI Gateway are JSON objects that define how your requests are routed. They help with implementing features like advanced routing, fallbacks, and retries.

    We need to create a default config to route our requests to the AI Provider added in Step 1.

    To create your config:

    1. Go to [Configs](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager
    2. Create new config with:
       ```json theme={"system"}
       {
           "provider":"@YOUR_PROVIDER_FROM_STEP1",
          	"override_params": {
             "model": "gpt-4o" // Your preferred model name
           }
       }

       ```
    3. Save and note the Config name for the next step

    <Note>
      This basic config connects to your AI Provider. You can add more advanced AI Gateway features later.
    </Note>
  </Step>

  <Step title="Configure AI Gateway API Key">
    Now create AI Gateway API key access point and attach the config you created in Step 2:

    1. Go to [API Keys](https://stratacloudmanager.paloaltonetworks.com/) in the AI Gateway and Create new API key
    2. Select your config from `Step 2`
    3. Generate and save your API key

    <Note>
      Save your API key securely - you'll need it for OpenAI Agents integration.
    </Note>
  </Step>

  <Step>
    Once you have creted your API Key after attaching default config, you can directly pass the API key + base URL in the AsyncOpenAI client. Here's how:

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

    client=AsyncOpenAI(
    api_key="YOUR_PORTKEY_API_KEY", # Your AI Gateway API key from Step 3
    base_url="https://aigw.portkey.ai/v1"
    )

    # your rest of the code remains same
    ```
  </Step>
</Steps>

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

    AI Providers in Model Catalog enable granular control over LLM access at the team/department level. This helps you:

    * Set up [budget limits](/docs/aigw/product/policies/budget-limits)
    * Prevent unexpected usage spikes using rate limits
    * Track departmental spending

    #### Setting Up Department-Specific Controls:

    1. Navigate to [Model Catalog](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager
    2. Add an AI Provider for each department with budget limits and rate limits
    3. Configure department-specific limits
  </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. AI Gateway Configs provide this control layer with features like:

    #### Access Control Features:

    * **Model Restrictions**: Limit access to specific models
    * **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:

    ```json theme={"system"}
    {
    	"strategy": {
    		"mode": "single"
    	},
    	"targets": [
    		{
    			"provider":"@YOUR_OPENAI_PROVIDER",
    			"override_params": {
    				"model": "gpt-4o"
    			}
    		}
    	]
    }
    ```

    Create your config on the [Configs page](https://stratacloudmanager.paloaltonetworks.com/) in Strata Cloud Manager. You'll need the config ID for connecting to OpenAI Agents's setup.

    <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 User-specific API keys that automatically:

    * Track usage per user/team with the help of 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 OpenAI Agents setup is ready to go. Each team member can now use their designated API keys with appropriate access levels and budget controls.
    Apply your governance setup using the integration steps from earlier sections
    Monitor usage in Strata Cloud Manager:

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

<Check>
  ### Enterprise Features Now Available

  **OpenAI Agents now has:**

  * Departmental budget controls
  * Model access governance
  * Usage tracking & attribution
  * Security guardrails
  * Reliability features
</Check>

## Frequently Asked Questions

<AccordionGroup>
  <Accordion title="How does the AI Gateway enhance OpenAI Agents?">
    The AI Gateway adds production-readiness to OpenAI Agents 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.
  </Accordion>

  <Accordion title="Can I use the AI Gateway with existing OpenAI Agents?">
    Yes! The AI Gateway integrates seamlessly with existing OpenAI Agents. You only need to replace your client initialization code with the gateway-enabled version. The rest of your agent code remains unchanged.
  </Accordion>

  <Accordion title="Does the AI Gateway work with all OpenAI Agents features?">
    The AI Gateway supports all OpenAI Agents SDK features, including tool use, memory, planning, and more. It adds observability and reliability without limiting any of the SDK's functionality.
  </Accordion>

  <Accordion title="How does the AI Gateway handle streaming in OpenAI Agents?">
    The AI Gateway fully supports streaming responses in OpenAI Agents. You can enable streaming by using the appropriate methods in the OpenAI Agents SDK, and the AI Gateway will properly track and log the streaming interactions.
  </Accordion>

  <Accordion title="How do I filter logs and traces for specific agent runs?">
    The AI Gateway allows you to add custom metadata 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. It securely stores them, allowing you to easily manage and rotate keys without changing your code.
  </Accordion>
</AccordionGroup>

## Resources

<CardGroup cols="3">
  <Card title="OpenAI Agents Docs" href="https://openai.github.io/openai-agents-python/">
    <p>Official OpenAI Agents SDK documentation</p>
  </Card>

  <Card title="Agent Examples" href="https://github.com/openai/openai-agents-python/tree/main/examples">
    <p>Example implementations for various use cases</p>
  </Card>
</CardGroup>


## Related topics

- [AWS AgentCore](/docs/aigw/integrations/agents/agentcore.md)
- [OpenAI Agent Builder (Python)](/docs/aigw/integrations/libraries/openai-agent-builder-python.md)
- [OpenTelemetry Python SDK](/docs/aigw/integrations/tracing-providers/opentelemetry-python-sdk.md)
- [OpenAI Agents SDK (TypeScript)](/docs/aigw/integrations/agents/openai-agents-ts.md)
- [OpenAI Agent Builder (TypeScript)](/docs/aigw/integrations/libraries/openai-agent-builder.md)
