Skip to content

OpenAI Swarm Integration

Use Gateway with OpenAI Swarm

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

Code

You can now use the Invariant Gateway with your OpenAI Swarm client as follows:

from swarm import Swarm, Agent
from openai import OpenAI
from httpx import Client
import os

client = Swarm(
    client=OpenAI(
        http_client=Client(headers={"Invariant-Authorization": "Bearer " + os.getenv("INVARIANT_API_KEY", "")}),
        base_url="https://explorer.invariantlabs.ai/api/v1/gateway/weather-swarm-agent/openai",
    )
)


def get_weather():
    return "It's sunny."


agent = Agent(
    name="Agent A",
    instructions="You are a helpful agent.",
    functions=[get_weather],
)

response = client.run(
    agent=agent,
    messages=[{"role": "user", "content": "What's the weather?"}],
)

print(response.messages[-1]["content"])
# Output: "It seems to be sunny."

This will automatically trace your agent interactions in Invariant Explorer.

Explore Other Integrations