Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Traces

Trace

Bases:ABC

A complete end-to-end workflow containing related spans and metadata.

A trace represents a logical workflow or operation (e.g., "Customer Service Query"or "Code Generation") and contains all the spans (individual operations) that occurduring that workflow.

Example
# Basic trace usagewithtrace("Order Processing")ast:validation_result=awaitRunner.run(validator,order_data)ifvalidation_result.approved:awaitRunner.run(processor,order_data)# Trace with metadata and groupingwithtrace("Customer Service",group_id="chat_123",metadata={"customer":"user_456"})ast:result=awaitRunner.run(support_agent,query)
Notes
  • Use descriptive workflow names
  • Group related traces with consistent group_ids
  • Add relevant metadata for filtering/analysis
  • Use context managers for reliable cleanup
  • Consider privacy when adding trace data
Source code insrc/agents/tracing/traces.py
classTrace(abc.ABC):"""A complete end-to-end workflow containing related spans and metadata.    A trace represents a logical workflow or operation (e.g., "Customer Service Query"    or "Code Generation") and contains all the spans (individual operations) that occur    during that workflow.    Example:        ```python        # Basic trace usage        with trace("Order Processing") as t:            validation_result = await Runner.run(validator, order_data)            if validation_result.approved:                await Runner.run(processor, order_data)        # Trace with metadata and grouping        with trace(            "Customer Service",            group_id="chat_123",            metadata={"customer": "user_456"}        ) as t:            result = await Runner.run(support_agent, query)        ```    Notes:        - Use descriptive workflow names        - Group related traces with consistent group_ids        - Add relevant metadata for filtering/analysis        - Use context managers for reliable cleanup        - Consider privacy when adding trace data    """@abc.abstractmethoddef__enter__(self)->Trace:pass@abc.abstractmethoddef__exit__(self,exc_type,exc_val,exc_tb):pass@abc.abstractmethoddefstart(self,mark_as_current:bool=False):"""Start the trace and optionally mark it as the current trace.        Args:            mark_as_current: If true, marks this trace as the current trace                in the execution context.        Notes:            - Must be called before any spans can be added            - Only one trace can be current at a time            - Thread-safe when using mark_as_current        """pass@abc.abstractmethoddeffinish(self,reset_current:bool=False):"""Finish the trace and optionally reset the current trace.        Args:            reset_current: If true, resets the current trace to the previous                trace in the execution context.        Notes:            - Must be called to complete the trace            - Finalizes all open spans            - Thread-safe when using reset_current        """pass@property@abc.abstractmethoddeftrace_id(self)->str:"""Get the unique identifier for this trace.        Returns:            str: The trace's unique ID in the format 'trace_<32_alphanumeric>'        Notes:            - IDs are globally unique            - Used to link spans to their parent trace            - Can be used to look up traces in the dashboard        """pass@property@abc.abstractmethoddefname(self)->str:"""Get the human-readable name of this workflow trace.        Returns:            str: The workflow name (e.g., "Customer Service", "Data Processing")        Notes:            - Should be descriptive and meaningful            - Used for grouping and filtering in the dashboard            - Helps identify the purpose of the trace        """pass@abc.abstractmethoddefexport(self)->dict[str,Any]|None:"""Export the trace data as a serializable dictionary.        Returns:            dict | None: Dictionary containing trace data, or None if tracing is disabled.        Notes:            - Includes all spans and their data            - Used for sending traces to backends            - May include metadata and group ID        """pass

trace_idabstractmethodproperty

trace_id:str

Get the unique identifier for this trace.

Returns:

NameTypeDescription
strstr

The trace's unique ID in the format 'trace_<32_alphanumeric>'

Notes
  • IDs are globally unique
  • Used to link spans to their parent trace
  • Can be used to look up traces in the dashboard

nameabstractmethodproperty

name:str

Get the human-readable name of this workflow trace.

Returns:

NameTypeDescription
strstr

The workflow name (e.g., "Customer Service", "Data Processing")

Notes
  • Should be descriptive and meaningful
  • Used for grouping and filtering in the dashboard
  • Helps identify the purpose of the trace

startabstractmethod

start(mark_as_current:bool=False)

Start the trace and optionally mark it as the current trace.

Parameters:

NameTypeDescriptionDefault
mark_as_currentbool

If true, marks this trace as the current tracein the execution context.

False
Notes
  • Must be called before any spans can be added
  • Only one trace can be current at a time
  • Thread-safe when using mark_as_current
Source code insrc/agents/tracing/traces.py
@abc.abstractmethoddefstart(self,mark_as_current:bool=False):"""Start the trace and optionally mark it as the current trace.    Args:        mark_as_current: If true, marks this trace as the current trace            in the execution context.    Notes:        - Must be called before any spans can be added        - Only one trace can be current at a time        - Thread-safe when using mark_as_current    """pass

finishabstractmethod

finish(reset_current:bool=False)

Finish the trace and optionally reset the current trace.

Parameters:

NameTypeDescriptionDefault
reset_currentbool

If true, resets the current trace to the previoustrace in the execution context.

False
Notes
  • Must be called to complete the trace
  • Finalizes all open spans
  • Thread-safe when using reset_current
Source code insrc/agents/tracing/traces.py
@abc.abstractmethoddeffinish(self,reset_current:bool=False):"""Finish the trace and optionally reset the current trace.    Args:        reset_current: If true, resets the current trace to the previous            trace in the execution context.    Notes:        - Must be called to complete the trace        - Finalizes all open spans        - Thread-safe when using reset_current    """pass

exportabstractmethod

export()->dict[str,Any]|None

Export the trace data as a serializable dictionary.

Returns:

TypeDescription
dict[str,Any] | None

dict | None: Dictionary containing trace data, or None if tracing is disabled.

Notes
  • Includes all spans and their data
  • Used for sending traces to backends
  • May include metadata and group ID
Source code insrc/agents/tracing/traces.py
@abc.abstractmethoddefexport(self)->dict[str,Any]|None:"""Export the trace data as a serializable dictionary.    Returns:        dict | None: Dictionary containing trace data, or None if tracing is disabled.    Notes:        - Includes all spans and their data        - Used for sending traces to backends        - May include metadata and group ID    """pass

NoOpTrace

Bases:Trace

A no-op implementation of Trace that doesn't record any data.

Used when tracing is disabled but trace operations still need to work.Maintains proper context management but doesn't store or export any data.

Example
# When tracing is disabled, traces become NoOpTracewithtrace("Disabled Workflow")ast:# Operations still work but nothing is recordedawaitRunner.run(agent,"query")
Source code insrc/agents/tracing/traces.py
classNoOpTrace(Trace):"""A no-op implementation of Trace that doesn't record any data.    Used when tracing is disabled but trace operations still need to work.    Maintains proper context management but doesn't store or export any data.    Example:        ```python        # When tracing is disabled, traces become NoOpTrace        with trace("Disabled Workflow") as t:            # Operations still work but nothing is recorded            await Runner.run(agent, "query")        ```    """def__init__(self):self._started=Falseself._prev_context_token:contextvars.Token[Trace|None]|None=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)defstart(self,mark_as_current:bool=False):ifmark_as_current:self._prev_context_token=Scope.set_current_trace(self)deffinish(self,reset_current:bool=False):ifreset_currentandself._prev_context_tokenisnotNone:Scope.reset_current_trace(self._prev_context_token)self._prev_context_token=None@propertydeftrace_id(self)->str:"""The trace's unique identifier.        Returns:            str: A unique ID for this trace.        """return"no-op"@propertydefname(self)->str:"""The workflow name for this trace.        Returns:            str: Human-readable name describing this workflow.        """return"no-op"defexport(self)->dict[str,Any]|None:"""Export the trace data as a dictionary.        Returns:            dict | None: Trace data in exportable format, or None if no data.        """returnNone

trace_idproperty

trace_id:str

The trace's unique identifier.

Returns:

NameTypeDescription
strstr

A unique ID for this trace.

nameproperty

name:str

The workflow name for this trace.

Returns:

NameTypeDescription
strstr

Human-readable name describing this workflow.

export

export()->dict[str,Any]|None

Export the trace data as a dictionary.

Returns:

TypeDescription
dict[str,Any] | None

dict | None: Trace data in exportable format, or None if no data.

Source code insrc/agents/tracing/traces.py
defexport(self)->dict[str,Any]|None:"""Export the trace data as a dictionary.    Returns:        dict | None: Trace data in exportable format, or None if no data.    """returnNone

TraceImpl

Bases:Trace

A trace that will be recorded by the tracing library.

Source code insrc/agents/tracing/traces.py
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:str|None,group_id:str|None,metadata:dict[str,Any]|None,processor:TracingProcessor,):self._name=nameself._trace_id=trace_idorutil.gen_trace_id()self.group_id=group_idself.metadata=metadataself._prev_context_token:contextvars.Token[Trace|None]|None=Noneself._processor=processorself._started=False@propertydeftrace_id(self)->str:returnself._trace_id@propertydefname(self)->str:returnself._namedefstart(self,mark_as_current:bool=False):ifself._started:returnself._started=Trueself._processor.on_trace_start(self)ifmark_as_current:self._prev_context_token=Scope.set_current_trace(self)deffinish(self,reset_current:bool=False):ifnotself._started:returnself._processor.on_trace_end(self)ifreset_currentandself._prev_context_tokenisnotNone:Scope.reset_current_trace(self._prev_context_token)self._prev_context_token=Nonedef__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)defexport(self)->dict[str,Any]|None:return{"object":"trace","id":self.trace_id,"workflow_name":self.name,"group_id":self.group_id,"metadata":self.metadata,}

[8]ページ先頭

©2009-2025 Movatter.jp