Then load the environment variables in your Python code:
Copy
from dotenv import load_dotenvimport os# Load environment variables from .env fileload_dotenv()# Set up environment variables with fallback valuesos.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
Initialize AgentOps at the beginning of your application to automatically track all OpenAI API calls:
Copy
import agentopsfrom openai import OpenAI# Initialize AgentOpsagentops.init()# Create OpenAI clientclient = OpenAI()# Make API calls as usual - AgentOps will track them automaticallyresponse = 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)
import agentopsfrom openai import OpenAI# Initialize AgentOpsagentops.init()# Create OpenAI clientclient = OpenAI()# Make a streaming API callstream = 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 responsefor chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="")