AgentOps is designed for easy integration into your AI agent projects, providing powerful observability with minimal setup. This guide will get you started quickly.

Give us a star on GitHub! Your support helps us grow. ⭐

Installation

First, install the AgentOps SDK. We recommend including python-dotenv for easy API key management.

pip install agentops python-dotenv

Initial Setup (2 Lines of Code)

At its simplest, AgentOps can start monitoring your supported LLM and agent framework calls with just two lines of Python code.

  1. Import AgentOps: Add import agentops to your script.
  2. Initialize AgentOps: Call agentops.init() with your API key.
import agentops
import os
from dotenv import load_dotenv

# Load environment variables (recommended for API keys)
load_dotenv()

# Initialize AgentOps
# The API key can be passed directly or set as an environment variable AGENTOPS_API_KEY
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") 
agentops.init(AGENTOPS_API_KEY) 

# That's it for basic auto-instrumentation!
# If you're using a supported library (like OpenAI, LangChain, CrewAI, etc.),
# AgentOps will now automatically track LLM calls and agent actions.

Setting Your AgentOps API Key

You need an AgentOps API key to send data to your dashboard.

It’s best practice to set your API key as an environment variable.

export AGENTOPS_API_KEY="your_agentops_api_key_here"

If you use a .env file, make sure load_dotenv() is called before agentops.init().

Running Your Agent & Viewing Traces

After adding the two lines and ensuring your API key is set up:

  1. Run your agent application as you normally would.
  2. AgentOps will automatically instrument supported libraries and send trace data.
  3. Visit your AgentOps Dashboard to observe your agent’s operations!

Beyond Automatic Instrumentation: Decorators

While AgentOps automatically instruments many popular libraries, you can gain finer-grained control and track custom parts of your code using our powerful decorators. This allows you to define specific operations, group logic under named agents, track tool usage with costs, and create custom traces.

Tracking Custom Operations with @operation

Instrument any function in your code to create spans that track its execution, parameters, and return values. These operations will appear in your session visualization alongside LLM calls.

from agentops.sdk.decorators import operation

@operation
def process_data(data):
    # Your function logic here
    processed_result = data.upper()
    # agentops.record(Events("Processed Data", result=processed_result)) # Optional: record specific events
    return processed_result

# Example usage:
# my_data = "example input"
# output = process_data(my_data)

Tracking Agent Logic with @agent

If you structure your system with specific named agents (e.g., classes), use the @agent decorator on the class and @operation on its methods to group all downstream operations under that agent’s context.

from agentops.sdk.decorators import agent, operation

@agent(name="MyCustomAgent") # You can provide a name for the agent
class MyAgent:
    def __init__(self, agent_id):
        self.agent_id = agent_id # agent_id is a reserved parameter for AgentOps
        
    @operation
    def perform_task(self, task_description):
        # Agent task logic here
        # This could include LLM calls or calls to other @operation decorated functions
        return f"Agent {self.agent_id} completed: {task_description}"

# Example usage:
# research_agent = MyAgent(agent_id="researcher-001")
# result = research_agent.perform_task("Analyze market trends")

Tracking Tools with @tool

Track the usage of specific tools or functions, and optionally associate costs with them. This data will be aggregated in your dashboard.

from agentops.sdk.decorators import tool

@tool(name="WebSearchTool", cost=0.05) # Cost is optional
def web_search(query: str) -> str:
    # Tool logic here
    return f"Search results for: {query}"
    
@tool # No cost specified
def calculator(expression: str) -> str:
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {e}"

# Example usage:
# search_result = web_search("AgentOps features")
# calculation = calculator("2 + 2")

Grouping with Traces (@trace or manual)

Create custom traces to group a sequence of operations or define logical units of work. You can use the @trace decorator or manage traces manually for more complex scenarios.

If auto_start_session=False in agentops.init(), you must use @trace or agentops.start_trace() for any data to be recorded.

from agentops.sdk.decorators import trace
# Assuming MyAgent and web_search are defined as above

# Option 1: Using the @trace decorator
@trace(name="MyMainWorkflow", tags=["main-flow"])
def my_workflow_decorated(task_to_perform):
    # Your workflow code here
    main_agent = MyAgent(agent_id="workflow-agent") # Assuming MyAgent is defined
    result = main_agent.perform_task(task_to_perform)
    # Example of using a tool within the trace
    tool_result = web_search(f"details for {task_to_perform}") # Assuming web_search is defined
    return result, tool_result
    
# result_decorated = my_workflow_decorated("complex data processing")

# Option 2: Managing traces manually
# import agentops # Already imported

# custom_trace = agentops.start_trace(name="MyManualWorkflow", tags=["manual-flow"])
# try:
#     # Your code here
#     main_agent = MyAgent(agent_id="manual-workflow-agent") # Assuming MyAgent is defined
#     result = main_agent.perform_task("another complex task")
#     tool_result = web_search(f"info for {result}") # Assuming web_search is defined
#     agentops.end_trace(custom_trace, end_state="Success", end_prompt=f"Completed: {result}")
# except Exception as e:
#     if custom_trace: # Ensure trace was started before trying to end it
#         agentops.end_trace(custom_trace, end_state="Fail", error_message=str(e))
#     raise

Complete Example with Decorators

Here’s a consolidated example showcasing how these decorators can work together:

import agentops
from agentops.sdk.decorators import agent, operation, tool, trace
from dotenv import load_dotenv
import os

# Load environment variables
load_dotenv()
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY")

# Initialize AgentOps. 
# Set auto_start_session=False because @trace will manage the session.
agentops.init(AGENTOPS_API_KEY, auto_start_session=False, tags=["quickstart-complete-example"])

# Define a tool
@tool(name="AdvancedSearch", cost=0.02)
def advanced_web_search(query: str) -> str:
    # Simulate a more advanced search
    return f"Advanced search results for '{query}': [Details...]"

# Define an agent class
@agent(name="ResearchSpecialistAgent")
class ResearchAgent:
    def __init__(self, agent_id: str):
        self.agent_id = agent_id # This will be used as the agent_id in AgentOps
        
    @operation(name="ConductResearch")
    def conduct_research(self, research_topic: str) -> str:
        # Use the tool within the agent's operation
        search_results = advanced_web_search(f"Deep dive into {research_topic}")
        # Simulate further processing
        analysis = f"Analysis of '{research_topic}': Based on '{search_results}', the key findings are..."
        return analysis

# Define a workflow using the @trace decorator
@trace(name="FullResearchWorkflow", tags=["research", "analysis", "example"])
def run_full_research_workflow(topic: str) -> str:
    specialist_agent = ResearchAgent(agent_id="researcher-alpha-007")
    research_findings = specialist_agent.conduct_research(topic)
    
    final_report = f"Research Report for '{topic}':\n{research_findings}"
    # agentops.record(Events("ReportGenerated", details=final_report)) # Optional: record a custom event
    return final_report

# Execute the workflow
final_output = run_full_research_workflow("AI in healthcare")
print(final_output)

Next Steps

You’ve seen how to get started with AgentOps! Explore further to leverage its full potential: