Skip to content

OpenAI Agents SDK

Use Gateway with the Agents SDK

OpenAI Agents SDK relies on OpenAI's Python client, which makes it very easy to integrate Gateway, similar to the standard OpenAI integration.

Getting the Invariant API Key

Visit the Explorer Documentation to learn how to obtain your own API key.

SDK Integration

You can then use Gateway with the Agents SDK by re-configuring the OpenAI client's base URL:

from agents import Agent, OpenAIChatCompletionsModel, Runner, function_tool
from openai import AsyncOpenAI
import os

external_client = AsyncOpenAI(
    base_url="https://explorer.invariantlabs.ai/api/v1/gateway/weather-agent/openai",
    default_headers={
        "Invariant-Authorization": "Bearer " + os.getenv("INVARIANT_API_KEY"),
    },
)


@function_tool
async def fetch_weather(location: str) -> str:
    return "sunny"


agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant",
    model=OpenAIChatCompletionsModel(
        model="gpt-4o",
        openai_client=external_client,
    ),
    tools=[fetch_weather],
)

result = Runner.run_sync(
    agent,
    "What is the weather like in Paris?",
)
print(result.final_output)

This will automatically trace your agent interactions in Invariant Explorer.

Explore Other Integrations