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

# OpenAI Agents SDK (Python)

> Use Obiguard 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.
Obiguard enhances OpenAI Agents with observability, reliability, and production-readiness features.

Obiguard turns your experimental OpenAI Agents into production-ready systems by providing:

* **Complete observability** of every agent step, tool use, and interaction
* **Cost tracking and optimization** to manage your AI spend
* **Access to 200+ LLMs** through a single integration
* **Guardrails** to keep agent behavior safe and compliant

<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={null}
    pip install -U openai-agents obiguard
    ```
  </Step>

  <Step title="Generate API Key">
    Create a Obiguard API key
  </Step>

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

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

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

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

    ```python theme={null}
    from agents import (
      set_default_openai_client,
      set_default_openai_api,
      Agent, Runner
    )
    from openai import AsyncOpenAI
    from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
    import os

    # Set up Obiguard as the global client
    client = AsyncOpenAI(
      base_url=OBIGUARD_GATEWAY_URL,
      obiguard_api_key=os.environ["OBIGUARD_API_KEY"],
      default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
      )
    )

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

    <Info>
      **What are Virtual Keys?** Virtual keys in Obiguard securely store your LLM provider API keys (OpenAI, Anthropic,
      etc.) in an encrypted vault. They allow for easier key rotation and budget management. [Learn more about virtual
      keys here](/virtual-keys).
    </Info>
  </Step>
</Steps>

### Getting Started

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

```python theme={null}
from agents import (
    set_default_openai_client,
    set_default_openai_api,
    Agent, Runner
)
from openai import AsyncOpenAI
from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
import os

# Set up Obiguard as the global client
client = AsyncOpenAI(
    base_url=OBIGUARD_GATEWAY_URL,
    default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
    )
)

# Register as the SDK-wide default
set_default_openai_client(client, 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="gpt-4o"  # Using Anthropic Claude through Obiguard
)

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

In this example:

1. We set up Obiguard 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 your Obiguard dashboard to see detailed logs of this agent's execution!

### Integration Approaches

There are three ways to integrate Obiguard 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={null}
    from agents import (
      set_default_openai_client,
      set_default_openai_api,
      set_tracing_disabled,
      Agent, Runner
    )
    from openai import AsyncOpenAI
    from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
    import os

    # Set up Obiguard as the global client
    client = AsyncOpenAI(
      base_url=OBIGUARD_GATEWAY_URL,
      obiguard_api_key=os.environ["OBIGUARD_API_KEY"],
      default_headers=createHeaders(
        virtual_key="YOUR_OPENAI_VIRTUAL_KEY"
      )
    )

    # Register it as the SDK-wide default
    set_default_openai_client(client, 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="claude-3-7-sonnet-latest"
    )

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

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

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

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


    client = AsyncOpenAI(
      base_url=OBIGUARD_GATEWAY_URL,
      default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
      )
    )

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

    provider = ObiguardProvider() # singleton is fine

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

      # Only this call uses Obiguard
      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={null}
    from agents import Agent, Runner, OpenAIChatCompletionsModel
    from openai import AsyncOpenAI
    from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
    import os

    client = AsyncOpenAI(
      base_url=OBIGUARD_GATEWAY_URL,
      default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
      )
    )


    agent = Agent(
      name="Haiku Writer",
      instructions="Classic Japanese form.",
      model=OpenAIChatCompletionsModel( # concrete Model
        model="claude-3-7-sonnet-latest",
        openai_client=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 Obiguard; simplest migration              |
| **ModelProvider in RunConfig**                    | Add a provider + pass `run_config`            | Toggle Obiguard 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={null}
from agents import Agent, Runner, Tool, set_default_openai_client
from openai import AsyncOpenAI
from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
import os

# Configure Obiguard client
client = AsyncOpenAI(
    base_url=OBIGUARD_GATEWAY_URL,
    default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
    )
)
set_default_openai_client(client)

# 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="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 your Obiguard dashboard to see the complete execution flow visualized!

***

## Production Features

### 1. Enhanced Observability

Obiguard 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={null}
    # Add tracing to your OpenAI Agents
    client = AsyncOpenAI(
      base_url=OBIGUARD_GATEWAY_URL,
      default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
      )
    )
    set_default_openai_client(client)
    ```
  </Tab>

  <Tab title="Logs">
    Obiguard 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">
    Obiguard 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>
</Tabs>

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

Obiguard's guardrails protect against these issues by validating both inputs and outputs.

Obiguard'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="/guardrail-AI/guardrail-validators">
  Explore Obiguard's guardrail features to enhance agent safety
</Card>

### 3. Tracing

Obiguard provides an opentelemetry compatible backend to store and query your traces.

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

## Tool Use in OpenAI Agents

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

```python [expandable] theme={null}
from agents import Agent, Runner, Tool, set_default_openai_client
from openai import AsyncOpenAI
from obiguard import OBIGUARD_GATEWAY_URL, createHeaders
import os

# Configure Obiguard client with tracing
client = AsyncOpenAI(
    base_url=OBIGUARD_GATEWAY_URL,
    default_headers=createHeaders(
        obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
        trace_id="tools_example",
        metadata={"agent_type": "research"}
    )
)
set_default_openai_client(client)

# Define tools
def get_weather(location: str, unit: str = "fahrenheit") -> str:
    """Get the current weather in a given location"""
    return f"The weather in {location} is 72 degrees {unit}"

def get_population(city: str, country: str) -> str:
    """Get the population of a city"""
    return f"The population of {city}, {country} is 1,000,000"

# Create agent with tools
agent = Agent(
    name="Research Assistant",
    instructions="You are a helpful assistant that can look up weather and population information.",
    model="gpt-4o-mini",
    tools=[
        Tool(
            name="get_weather",
            description="Get the current weather in a given location",
            input_schema={
                "location": {
                    "type": "string",
                    "description": "City and state, e.g. San Francisco, CA"
                },
                "unit": {
                    "type": "string",
                    "description": "Temperature unit (celsius or fahrenheit)",
                    "default": "fahrenheit"
                }
            },
            callback=get_weather
        ),
        Tool(
            name="get_population",
            description="Get the population of a city",
            input_schema={
                "city": {
                    "type": "string",
                    "description": "City name"
                },
                "country": {
                    "type": "string",
                    "description": "Country name"
                }
            },
            callback=get_population
        )
    ]
)

# Run the agent
result = Runner.run_sync(
    agent,
    "What's the weather in San Francisco and what's the population of Tokyo, Japan?"
)
print(result.final_output)
```

## 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 organization
* **Security & Compliance**: Maintaining enterprise security standards
* **Reliability**: Ensuring consistent service across all users

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

**Enterprise Implementation Guide**

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

<Steps>
  <Step title="Create guardrail policy">
    You can choose to create a guardrail policy to protect your data and ensure compliance with organizational policies.
    Add guardrail validators on your LLM inputs and output to govern your LLM usage.
  </Step>

  <Step title="Create Virtual Key">
    Virtual Keys are Obiguard's secure way to manage your LLM provider API keys.
    Think of them like disposable credit cards for your LLM API keys.

    To create a virtual key:
    Go to [Virtual Keys](/virtual-keys) in the Obiguard dashboard. Select the guardrail policy and your LLM provider.
    Save and copy the virtual key ID

    <Note>
      Save your virtual key ID - you'll need it for the next step.
    </Note>
  </Step>

  <Step>
    Once you have created 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={null}
    from obiguard import createHeaders, OBIGUARD_GATEWAY_URL
    from openai import AsyncOpenAI

    client=AsyncOpenAI(
      obiguard_api_key="vk-obg***",  # Your Obiguard virtual key
      base_url="OBIGUARD_GATEWAY_URL"
    )

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

<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 Obiguard enhance OpenAI Agents?">
    Obiguard adds production-readiness to OpenAI Agents through comprehensive observability (traces, logs, metrics),
    reliability features (fallbacks, retries, caching), and access to 200+ LLMs through a unified interface. This makes
    it easier to debug, optimize, and scale your agent applications.
  </Accordion>

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

  <Accordion title="Does Obiguard work with all OpenAI Agents features?">
    Obiguard 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 Obiguard handle streaming in OpenAI Agents?">
    Obiguard fully supports streaming responses in OpenAI Agents. You can enable streaming by using the appropriate
    methods in the OpenAI Agents SDK, and Obiguard will properly track and log the streaming interactions.
  </Accordion>

  <Accordion title="How do I filter logs and traces for specific agent runs?">
    Obiguard 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 Obiguard?">
    Yes! Obiguard uses your own API keys for the various LLM providers. It securely stores them as virtual keys,
    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>

  <Card title="Book a Demo" href="https://Obiguard.sh/openai-agents">
    <p>Get personalized guidance on implementing this integration</p>
  </Card>
</CardGroup>
