Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Spans

Span

Bases:ABC,Generic[TSpanData]

Base class for representing traceable operations with timing and context.

A span represents a single operation within a trace (e.g., an LLM call, tool execution,or agent run). Spans track timing, relationships between operations, and operation-specificdata.

Example
# Creating a custom spanwithcustom_span("database_query",{"operation":"SELECT","table":"users"})asspan:results=awaitdb.query("SELECT * FROM users")span.set_output({"count":len(results)})# Handling errors in spanswithcustom_span("risky_operation")asspan:try:result=perform_risky_operation()exceptExceptionase:span.set_error({"message":str(e),"data":{"operation":"risky_operation"}})raise

Notes:- Spans automatically nest under the current trace- Use context managers for reliable start/finish- Include relevant data but avoid sensitive information- Handle errors properly using set_error()

Source code insrc/agents/tracing/spans.py
classSpan(abc.ABC,Generic[TSpanData]):"""Base class for representing traceable operations with timing and context.    A span represents a single operation within a trace (e.g., an LLM call, tool execution,    or agent run). Spans track timing, relationships between operations, and operation-specific    data.    Type Args:        TSpanData: The type of span-specific data this span contains.    Example:        ```python        # Creating a custom span        with custom_span("database_query", {            "operation": "SELECT",            "table": "users"        }) as span:            results = await db.query("SELECT * FROM users")            span.set_output({"count": len(results)})        # Handling errors in spans        with custom_span("risky_operation") as span:            try:                result = perform_risky_operation()            except Exception as e:                span.set_error({                    "message": str(e),                    "data": {"operation": "risky_operation"}                })                raise        ```        Notes:        - Spans automatically nest under the current trace        - Use context managers for reliable start/finish        - Include relevant data but avoid sensitive information        - Handle errors properly using set_error()    """@property@abc.abstractmethoddeftrace_id(self)->str:"""The ID of the trace this span belongs to.        Returns:            str: Unique identifier of the parent trace.        """pass@property@abc.abstractmethoddefspan_id(self)->str:"""Unique identifier for this span.        Returns:            str: The span's unique ID within its trace.        """pass@property@abc.abstractmethoddefspan_data(self)->TSpanData:"""Operation-specific data for this span.        Returns:            TSpanData: Data specific to this type of span (e.g., LLM generation data).        """pass@abc.abstractmethoddefstart(self,mark_as_current:bool=False):"""        Start the span.        Args:            mark_as_current: If true, the span will be marked as the current span.        """pass@abc.abstractmethoddeffinish(self,reset_current:bool=False)->None:"""        Finish the span.        Args:            reset_current: If true, the span will be reset as the current span.        """pass@abc.abstractmethoddef__enter__(self)->Span[TSpanData]:pass@abc.abstractmethoddef__exit__(self,exc_type,exc_val,exc_tb):pass@property@abc.abstractmethoddefparent_id(self)->str|None:"""ID of the parent span, if any.        Returns:            str | None: The parent span's ID, or None if this is a root span.        """pass@abc.abstractmethoddefset_error(self,error:SpanError)->None:pass@property@abc.abstractmethoddeferror(self)->SpanError|None:"""Any error that occurred during span execution.        Returns:            SpanError | None: Error details if an error occurred, None otherwise.        """pass@abc.abstractmethoddefexport(self)->dict[str,Any]|None:pass@property@abc.abstractmethoddefstarted_at(self)->str|None:"""When the span started execution.        Returns:            str | None: ISO format timestamp of span start, None if not started.        """pass@property@abc.abstractmethoddefended_at(self)->str|None:"""When the span finished execution.        Returns:            str | None: ISO format timestamp of span end, None if not finished.        """pass

trace_idabstractmethodproperty

trace_id:str

The ID of the trace this span belongs to.

Returns:

NameTypeDescription
strstr

Unique identifier of the parent trace.

span_idabstractmethodproperty

span_id:str

Unique identifier for this span.

Returns:

NameTypeDescription
strstr

The span's unique ID within its trace.

span_dataabstractmethodproperty

span_data:TSpanData

Operation-specific data for this span.

Returns:

NameTypeDescription
TSpanDataTSpanData

Data specific to this type of span (e.g., LLM generation data).

parent_idabstractmethodproperty

parent_id:str|None

ID of the parent span, if any.

Returns:

TypeDescription
str | None

str | None: The parent span's ID, or None if this is a root span.

errorabstractmethodproperty

error:SpanError|None

Any error that occurred during span execution.

Returns:

TypeDescription
SpanError | None

SpanError | None: Error details if an error occurred, None otherwise.

started_atabstractmethodproperty

started_at:str|None

When the span started execution.

Returns:

TypeDescription
str | None

str | None: ISO format timestamp of span start, None if not started.

ended_atabstractmethodproperty

ended_at:str|None

When the span finished execution.

Returns:

TypeDescription
str | None

str | None: ISO format timestamp of span end, None if not finished.

startabstractmethod

start(mark_as_current:bool=False)

Start the span.

Parameters:

NameTypeDescriptionDefault
mark_as_currentbool

If true, the span will be marked as the current span.

False
Source code insrc/agents/tracing/spans.py
@abc.abstractmethoddefstart(self,mark_as_current:bool=False):"""    Start the span.    Args:        mark_as_current: If true, the span will be marked as the current span.    """pass

finishabstractmethod

finish(reset_current:bool=False)->None

Finish the span.

Parameters:

NameTypeDescriptionDefault
reset_currentbool

If true, the span will be reset as the current span.

False
Source code insrc/agents/tracing/spans.py
@abc.abstractmethoddeffinish(self,reset_current:bool=False)->None:"""    Finish the span.    Args:        reset_current: If true, the span will be reset as the current span.    """pass

NoOpSpan

Bases:Span[TSpanData]

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

Used when tracing is disabled but span operations still need to work.

Parameters:

NameTypeDescriptionDefault
span_dataTSpanData

The operation-specific data for this span.

required
Source code insrc/agents/tracing/spans.py
classNoOpSpan(Span[TSpanData]):"""A no-op implementation of Span that doesn't record any data.    Used when tracing is disabled but span operations still need to work.    Args:        span_data: The operation-specific data for this span.    """__slots__=("_span_data","_prev_span_token")def__init__(self,span_data:TSpanData):self._span_data=span_dataself._prev_span_token:contextvars.Token[Span[TSpanData]|None]|None=None@propertydeftrace_id(self)->str:return"no-op"@propertydefspan_id(self)->str:return"no-op"@propertydefspan_data(self)->TSpanData:returnself._span_data@propertydefparent_id(self)->str|None:returnNonedefstart(self,mark_as_current:bool=False):ifmark_as_current:self._prev_span_token=Scope.set_current_span(self)deffinish(self,reset_current:bool=False)->None:ifreset_currentandself._prev_span_tokenisnotNone:Scope.reset_current_span(self._prev_span_token)self._prev_span_token=Nonedef__enter__(self)->Span[TSpanData]:self.start(mark_as_current=True)returnselfdef__exit__(self,exc_type,exc_val,exc_tb):reset_current=Trueifexc_typeisGeneratorExit:logger.debug("GeneratorExit, skipping span reset")reset_current=Falseself.finish(reset_current=reset_current)defset_error(self,error:SpanError)->None:pass@propertydeferror(self)->SpanError|None:returnNonedefexport(self)->dict[str,Any]|None:returnNone@propertydefstarted_at(self)->str|None:returnNone@propertydefended_at(self)->str|None:returnNone

SpanImpl

Bases:Span[TSpanData]

Source code insrc/agents/tracing/spans.py
classSpanImpl(Span[TSpanData]):__slots__=("_trace_id","_span_id","_parent_id","_started_at","_ended_at","_error","_prev_span_token","_processor","_span_data",)def__init__(self,trace_id:str,span_id:str|None,parent_id:str|None,processor:TracingProcessor,span_data:TSpanData,):self._trace_id=trace_idself._span_id=span_idorutil.gen_span_id()self._parent_id=parent_idself._started_at:str|None=Noneself._ended_at:str|None=Noneself._processor=processorself._error:SpanError|None=Noneself._prev_span_token:contextvars.Token[Span[TSpanData]|None]|None=Noneself._span_data=span_data@propertydeftrace_id(self)->str:returnself._trace_id@propertydefspan_id(self)->str:returnself._span_id@propertydefspan_data(self)->TSpanData:returnself._span_data@propertydefparent_id(self)->str|None:returnself._parent_iddefstart(self,mark_as_current:bool=False):ifself.started_atisnotNone:logger.warning("Span already started")returnself._started_at=util.time_iso()self._processor.on_span_start(self)ifmark_as_current:self._prev_span_token=Scope.set_current_span(self)deffinish(self,reset_current:bool=False)->None:ifself.ended_atisnotNone:logger.warning("Span already finished")returnself._ended_at=util.time_iso()self._processor.on_span_end(self)ifreset_currentandself._prev_span_tokenisnotNone:Scope.reset_current_span(self._prev_span_token)self._prev_span_token=Nonedef__enter__(self)->Span[TSpanData]:self.start(mark_as_current=True)returnselfdef__exit__(self,exc_type,exc_val,exc_tb):reset_current=Trueifexc_typeisGeneratorExit:logger.debug("GeneratorExit, skipping span reset")reset_current=Falseself.finish(reset_current=reset_current)defset_error(self,error:SpanError)->None:self._error=error@propertydeferror(self)->SpanError|None:returnself._error@propertydefstarted_at(self)->str|None:returnself._started_at@propertydefended_at(self)->str|None:returnself._ended_atdefexport(self)->dict[str,Any]|None:return{"object":"trace.span","id":self.span_id,"trace_id":self.trace_id,"parent_id":self._parent_id,"started_at":self._started_at,"ended_at":self._ended_at,"span_data":self.span_data.export(),"error":self._error,}

[8]ページ先頭

©2009-2025 Movatter.jp