Decorators
Seemingly magic tools that can be added to functions and classes for easier instrumenting.
Decorators work by wrapping functions or classes that they are placed above. You’ve probably seen this before. Using decorators allows us to add a lot of functionality to your code with minimal work on your part.
python
AgentOps provides a set of decorators that allow you to easily instrument your code for tracing and monitoring AI agent workflows. These decorators create spans (units of work) that are organized hierarchically to track different types of operations.
@session
The @session
decorator creates a session span, which serves as the root for all other spans. No spans can exist without a session at the top.
You can also use the decorator with parameters:
@agent
The @agent
decorator creates an agent span for tracking agent operations. Agent spans are typically children of session spans and parents of operation spans.
You can also specify a custom name for the agent:
@operation
/ @task
The @operation
and @task
decorators are aliases that create operation/task spans for tracking specific operations. These spans are typically children of agent spans.
Operations can also be used outside of agent classes:
@workflow
The @workflow
decorator creates workflow spans for tracking workflows, which can contain multiple operations.
Nesting and Hierarchy
The decorators automatically manage the context propagation, ensuring that spans are properly nested within their parent spans. The typical hierarchy is:
- Session (root)
- Agent
- Operation/Task
- Nested Operations
Example of proper nesting:
Additional Features
The decorators provide several additional features:
-
Input/Output Recording: The decorators automatically record the input arguments and output results of the decorated functions.
-
Exception Handling: If an exception occurs within a decorated function, it’s recorded in the span.
-
Support for Different Function Types: The decorators handle different types of functions:
- Regular synchronous functions
- Asynchronous functions (using
async/await
) - Generator functions (using
yield
) - Asynchronous generator functions (using
async
andyield
)
-
Custom Attributes: You can add custom attributes to spans using the decorator parameters.