Concurrent Traces Example
Managing multiple concurrent traces and sessions
View Notebook on Github
Multiple Concurrent Traces
This example demonstrates how to run multiple traces (sessions) concurrently using both the modern trace-based API and the legacy session API for backwards compatibility.
First let’s install the required packages:
Then import them:
Next, we’ll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this example. It accounts for both users who use environment variables and those who just want to set the API Key here.
-
Create an environment variable in a .env file or other method. By default, the AgentOps
init()
function will look for an environment variable namedAGENTOPS_API_KEY
. Or… -
Replace
<your_agentops_key>
below and pass in the optionalapi_key
parameter to the AgentOpsinit(api_key=...)
function. Remember not to commit your API key to a public repo!
Initialize AgentOps. We’ll disable auto-start to manually create our traces:
Modern Trace-Based Approach
The recommended approach uses start_trace()
and end_trace()
:
LLM Calls with Automatic Tracking
With the modern implementation, LLM calls are automatically tracked without needing special session assignment:
Using Context Managers
You can also use traces as context managers for automatic cleanup:
Using Decorators
For even cleaner code, use decorators:
Legacy Session API (Backwards Compatibility)
For backwards compatibility, the legacy session API is still available:
Ending Traces
End traces individually or all at once:
Key Differences from Legacy Multi-Session Mode
- No mode switching: You can create multiple traces without entering a special “multi-session mode”
- Automatic LLM tracking: LLM calls are automatically associated with the current execution context
- No exceptions: No
MultiSessionException
or similar restrictions - Cleaner API: Use decorators and context managers for better code organization
- Backwards compatibility: Legacy session functions still work for existing code
If you look in the AgentOps dashboard, you will see multiple unique traces, each with their respective LLM calls and events properly tracked.