AgentOps seamlessly integrates with OpenAI’s Python SDK, allowing you to track and analyze all your OpenAI API calls automatically.

Installation

pip install agentops openai

Setting Up API Keys

Before using OpenAI with AgentOps, you need to set up your API keys. You can obtain:

Then to set them up, you can either export them as environment variables or set them in a .env file.

export OPENAI_API_KEY="your_openai_api_key_here"
export AGENTOPS_API_KEY="your_agentops_api_key_here"

Then load the environment variables in your Python code:

from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()

# Set up environment variables with fallback values
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")

Usage

Initialize AgentOps at the beginning of your application to automatically track all OpenAI API calls:

import agentops
from openai import OpenAI
      
# Initialize AgentOps
agentops.init()

# Create OpenAI client
client = OpenAI()

# Make API calls as usual - AgentOps will track them automatically
response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

print(response.choices[0].message.content)

Examples

import agentops
from openai import OpenAI

# Initialize AgentOps
agentops.init()

# Create OpenAI client
client = OpenAI()

# Make a streaming API call
stream = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a short poem about AI."}
    ],
    stream=True
)

# Process the streaming response
for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")

More Examples