"""AdalFlow traces module with OpenAI Agents SDK compatible interface.This module provides trace implementations for AdalFlow tracing that followthe OpenAI Agents SDK patterns for maximum compatibility with existingobservability backends.References:- OpenAI Agents SDK: https://github.com/openai/openai-agents-python/blob/main/src/agents/tracing/traces.py"""from__future__importannotationsimportabcimportcontextvarsimportloggingfromtypingimportAny,Optional,Dictlogger=logging.getLogger(__name__)from.importutilfrom.processor_interfaceimportTracingProcessor
[docs]classTrace:""" A trace is the root level object that tracing creates. It represents a logical "workflow". """@abc.abstractmethoddef__enter__(self)->Trace:pass@abc.abstractmethoddef__exit__(self,exc_type,exc_val,exc_tb):pass
[docs]@abc.abstractmethoddefstart(self,mark_as_current:bool=False):""" Start the trace. Args: mark_as_current: If true, the trace will be marked as the current trace. """pass
[docs]@abc.abstractmethoddeffinish(self,reset_current:bool=False):""" Finish the trace. Args: reset_current: If true, the trace will be reset as the current trace. """pass
@property@abc.abstractmethoddeftrace_id(self)->str:""" The trace ID. """pass@property@abc.abstractmethoddefname(self)->str:""" The name of the workflow being traced. """pass
[docs]@abc.abstractmethoddefexport(self)->Optional[Dict[str,Any]]:""" Export the trace as a dictionary. """pass
[docs]classNoOpTrace(Trace):""" A no-op trace that will not be recorded. """def__init__(self):self._started=Falseself._prev_context_token:Optional[contextvars.Token[Optional[Trace]]]=Nonedef__enter__(self)->Trace:ifself._started:ifnotself._prev_context_token:logger.error("Trace already started but no context token set")returnselfself._started=Trueself.start(mark_as_current=True)returnselfdef__exit__(self,exc_type,exc_val,exc_tb):self.finish(reset_current=True)
[docs]classTraceImpl(Trace):""" A trace that will be recorded by the tracing library. """__slots__=("_name","_trace_id","group_id","metadata","_prev_context_token","_processor","_started",)def__init__(self,name:str,trace_id:Optional[str],group_id:Optional[str],metadata:Optional[Dict[str,Any]],processor:TracingProcessor,):self._name=nameself._trace_id=trace_idorutil.gen_trace_id()self.group_id=group_idself.metadata=metadataself._prev_context_token:Optional[contextvars.Token[Optional[Trace]]]=Noneself._processor=processorself._started=False@propertydeftrace_id(self)->str:returnself._trace_id@propertydefname(self)->str:returnself._name
def__enter__(self)->Trace:ifself._started:ifnotself._prev_context_token:logger.error("Trace already started but no context token set")returnselfself.start(mark_as_current=True)returnselfdef__exit__(self,exc_type,exc_val,exc_tb):self.finish(reset_current=exc_typeisnotGeneratorExit)