How to use AgentOps with OpenAI
Quick answer
Use
agentops.init() to automatically patch the OpenAI client for observability. Start and end manual sessions with agentops.start_session() and agentops.end_session() to track AI agent interactions seamlessly.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)AgentOps API keypip install openai>=1.0 agentops
Setup
Install the required packages and set environment variables for OPENAI_API_KEY and AGENTOPS_API_KEY. This enables authentication for both OpenAI and AgentOps services.
pip install openai agentops output
Collecting openai Collecting agentops Successfully installed openai-1.x.x agentops-x.x.x
Step by step
Initialize AgentOps to auto-instrument OpenAI calls, then create an OpenAI client and make a chat completion request. Use manual session management to track specific agent interactions.
import os
from openai import OpenAI
import agentops
# Initialize AgentOps with your API key
agentops.init(api_key=os.environ["AGENTOPS_API_KEY"])
# Create OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Start a manual session (optional)
session = agentops.start_session(tags=["example-agent"])
# Make a chat completion request
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello, AgentOps!"}]
)
print("Response:", response.choices[0].message.content)
# End the session
agentops.end_session("Success") output
Response: Hello, AgentOps!
Common variations
- Use
agentops.start_session()andagentops.end_session()to manually control session boundaries for complex workflows. - AgentOps auto-instruments all
OpenAIclient calls afteragentops.init(), so no code changes are needed for basic usage. - Combine with async OpenAI calls by initializing AgentOps before async usage.
Troubleshooting
- If you see no data in AgentOps dashboard, verify
AGENTOPS_API_KEYis set correctly andagentops.init()is called before any OpenAI client usage. - Ensure your OpenAI API key is valid and environment variables are loaded properly.
- For network issues, check firewall or proxy settings that might block telemetry data.
Key Takeaways
- Call
agentops.init()early to auto-instrument OpenAI client calls for observability. - Use manual sessions with
agentops.start_session()andagentops.end_session()to track agent workflows explicitly. - Set environment variables
OPENAI_API_KEYandAGENTOPS_API_KEYsecurely before running your code.