Skip to main content

Context Managers

AgentOps provides native context manager support for traces, allowing you to use Python’s with statement for automatic trace lifecycle management. This approach ensures traces are properly started and ended, even when exceptions occur.

Basic Usage

The simplest way to use context managers is with the start_trace() function:
The trace will automatically:
  • Start when entering the with block
  • End with “Success” status when exiting normally
  • End with “Error” status if an exception occurs
  • Clean up resources properly in all cases

Advanced Usage

Traces with Tags

You can add tags to traces for better organization and filtering:

Parallel Traces

Context managers create independent parallel traces, not parent-child relationships:

Exception Handling

Context managers automatically handle exceptions and set appropriate trace states:

Concurrent Execution

Context managers work seamlessly with threading and asyncio:

Production Patterns

API Endpoint Monitoring

Batch Processing

Retry Logic

Backward Compatibility

Context managers are fully backward compatible with existing AgentOps code patterns:

Examples

For complete working examples, see the following files in the AgentOps repository:

Basic Usage

Simple context manager patterns and error handling

Parallel Traces

Sequential, nested, and concurrent trace patterns

Error Handling

Exception handling, retry patterns, and graceful degradation

Production Patterns

API endpoints, batch processing, microservices, and monitoring
These examples demonstrate real-world usage patterns and best practices for using AgentOps context managers in production applications.

API Reference

For detailed API information, see the SDK Reference documentation.