Sessions and users help you understand how people interact with your AI system across multiple requests. In the monitoring mode of an Openlayer project, you can group traces by sessions and analyze user behavior patterns. This allows you to track user journeys, identify problematic interaction patterns, and understand how different users engage with your AI system. Sessions and users

What are sessions and users

A session represents a series of related interactions between a user and your AI system. The typical example is a multi-turn conversation thread in a chatbot. A user is the individual behind one or more sessions, identified by an ID. All traces with the same session_id can be grouped together, allowing you to see the complete interaction flow. You can also group traces by user_id, allowing you to see the different journeys taken by a given user.

How to set up sessions and users

With minimal additional instrumentation, you can add session and user context to your traces. You can do this in two ways:

1. Set default context

Set default user and session context once, typically in middleware or at the start of a request. This context will automatically be applied to all traces within that execution context.
from openlayer.lib import set_user_session_context, clear_user_session_context

# In your middleware or request handler
def handle_request(request): # Extract user and session from your authentication system
    user_id = get_user_id_from_request(request)
    session_id = get_session_id_from_request(request)

    # Set default context for all traces in this request
    set_user_session_context(user_id=user_id, session_id=session_id)

    try:
        # Your application logic with traced functions
        result = process_user_request(request.data)
        return result
    finally:
        # Clean up context when request is complete
        clear_user_session_context()

2. Override context for specific traces

You can override or set user and session context for specific traces using update_trace_user_session().
from openlayer.lib import update_trace_user_session

@trace()
def process_request():
    update_trace_user_session(
        user_id="different_user_123",
        session_id="different_session_123"
    )
    return "result"