"""AdalFlow tracing scope management module with OpenAI Agents SDK compatibility.This module provides context management for traces and spans, maintaining currentexecution context following OpenAI Agents SDK patterns.References:- OpenAI Agents SDK: https://github.com/openai/openai-agents-python/blob/main/src/agents/tracing/scope.py"""# Holds the current active spanimportcontextvarsimportloggingimportuuidfromtypingimportAny,Optionalfrom.tracesimportTracefrom.spansimportSpanlogger=logging.getLogger(__name__)_current_span:contextvars.ContextVar[Optional["Span[Any]"]]=contextvars.ContextVar("current_span",default=None)_current_trace:contextvars.ContextVar[Optional["Trace"]]=contextvars.ContextVar("current_trace",default=None)
[docs]classScope:""" Manages the current span and trace in the context. """
[docs]@classmethoddefset_current_trace(cls,trace:Optional["Trace"])->"contextvars.Token[Optional[Trace]]":logger.debug(f"Setting current trace: {trace.trace_idiftraceelseNone}")return_current_trace.set(trace)
[docs]@classmethoddefreset_current_trace(cls,token:"contextvars.Token[Optional[Trace]]")->None:logger.debug("Resetting current trace")_current_trace.reset(token)
# Utility functions for standalone use
[docs]defget_current_span()->Optional["Span[Any]"]:"""Get the current span from context."""returnScope.get_current_span()
[docs]defset_current_span(span:Optional["Span[Any]"],)->"contextvars.Token[Optional[Span[Any]]]":"""Set the current span in context."""returnScope.set_current_span(span)
[docs]defget_current_trace()->Optional["Trace"]:"""Get the current trace from context."""returnScope.get_current_trace()
[docs]defset_current_trace(trace:Optional["Trace"])->"contextvars.Token[Optional[Trace]]":"""Set the current trace in context."""returnScope.set_current_trace(trace)
[docs]defgen_span_id()->str:"""Generate a unique span ID."""returnstr(uuid.uuid4())
[docs]defgen_trace_id()->str:"""Generate a unique trace ID."""returnstr(uuid.uuid4())