Movatterモバイル変換


[0]ホーム

URL:


콘텐츠로 이동

Tracing module

TracingProcessor

Bases:ABC

Interface for processing and monitoring traces and spans in the OpenAI Agents system.

This abstract class defines the interface that all tracing processors must implement.Processors receive notifications when traces and spans start and end, allowing themto collect, process, and export tracing data.

Example
classCustomProcessor(TracingProcessor):def__init__(self):self.active_traces={}self.active_spans={}defon_trace_start(self,trace):self.active_traces[trace.trace_id]=tracedefon_trace_end(self,trace):# Process completed tracedelself.active_traces[trace.trace_id]defon_span_start(self,span):self.active_spans[span.span_id]=spandefon_span_end(self,span):# Process completed spandelself.active_spans[span.span_id]defshutdown(self):# Clean up resourcesself.active_traces.clear()self.active_spans.clear()defforce_flush(self):# Force processing of any queued itemspass
Notes
  • All methods should be thread-safe
  • Methods should not block for long periods
  • Handle errors gracefully to prevent disrupting agent execution
Source code insrc/agents/tracing/processor_interface.py
classTracingProcessor(abc.ABC):"""Interface for processing and monitoring traces and spans in the OpenAI Agents system.    This abstract class defines the interface that all tracing processors must implement.    Processors receive notifications when traces and spans start and end, allowing them    to collect, process, and export tracing data.    Example:        ```python        class CustomProcessor(TracingProcessor):            def __init__(self):                self.active_traces = {}                self.active_spans = {}            def on_trace_start(self, trace):                self.active_traces[trace.trace_id] = trace            def on_trace_end(self, trace):                # Process completed trace                del self.active_traces[trace.trace_id]            def on_span_start(self, span):                self.active_spans[span.span_id] = span            def on_span_end(self, span):                # Process completed span                del self.active_spans[span.span_id]            def shutdown(self):                # Clean up resources                self.active_traces.clear()                self.active_spans.clear()            def force_flush(self):                # Force processing of any queued items                pass        ```    Notes:        - All methods should be thread-safe        - Methods should not block for long periods        - Handle errors gracefully to prevent disrupting agent execution    """@abc.abstractmethoddefon_trace_start(self,trace:"Trace")->None:"""Called when a new trace begins execution.        Args:            trace: The trace that started. Contains workflow name and metadata.        Notes:            - Called synchronously on trace start            - Should return quickly to avoid blocking execution            - Any errors should be caught and handled internally        """pass@abc.abstractmethoddefon_trace_end(self,trace:"Trace")->None:"""Called when a trace completes execution.        Args:            trace: The completed trace containing all spans and results.        Notes:            - Called synchronously when trace finishes            - Good time to export/process the complete trace            - Should handle cleanup of any trace-specific resources        """pass@abc.abstractmethoddefon_span_start(self,span:"Span[Any]")->None:"""Called when a new span begins execution.        Args:            span: The span that started. Contains operation details and context.        Notes:            - Called synchronously on span start            - Should return quickly to avoid blocking execution            - Spans are automatically nested under current trace/span        """pass@abc.abstractmethoddefon_span_end(self,span:"Span[Any]")->None:"""Called when a span completes execution.        Args:            span: The completed span containing execution results.        Notes:            - Called synchronously when span finishes            - Should not block or raise exceptions            - Good time to export/process the individual span        """pass@abc.abstractmethoddefshutdown(self)->None:"""Called when the application stops to clean up resources.        Should perform any necessary cleanup like:        - Flushing queued traces/spans        - Closing connections        - Releasing resources        """pass@abc.abstractmethoddefforce_flush(self)->None:"""Forces immediate processing of any queued traces/spans.        Notes:            - Should process all queued items before returning            - Useful before shutdown or when immediate processing is needed            - May block while processing completes        """pass

on_trace_startabstractmethod

on_trace_start(trace:Trace)->None

Called when a new trace begins execution.

Parameters:

NameTypeDescriptionDefault
traceTrace

The trace that started. Contains workflow name and metadata.

required
Notes
  • Called synchronously on trace start
  • Should return quickly to avoid blocking execution
  • Any errors should be caught and handled internally
Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefon_trace_start(self,trace:"Trace")->None:"""Called when a new trace begins execution.    Args:        trace: The trace that started. Contains workflow name and metadata.    Notes:        - Called synchronously on trace start        - Should return quickly to avoid blocking execution        - Any errors should be caught and handled internally    """pass

on_trace_endabstractmethod

on_trace_end(trace:Trace)->None

Called when a trace completes execution.

Parameters:

NameTypeDescriptionDefault
traceTrace

The completed trace containing all spans and results.

required
Notes
  • Called synchronously when trace finishes
  • Good time to export/process the complete trace
  • Should handle cleanup of any trace-specific resources
Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefon_trace_end(self,trace:"Trace")->None:"""Called when a trace completes execution.    Args:        trace: The completed trace containing all spans and results.    Notes:        - Called synchronously when trace finishes        - Good time to export/process the complete trace        - Should handle cleanup of any trace-specific resources    """pass

on_span_startabstractmethod

on_span_start(span:Span[Any])->None

Called when a new span begins execution.

Parameters:

NameTypeDescriptionDefault
spanSpan[Any]

The span that started. Contains operation details and context.

required
Notes
  • Called synchronously on span start
  • Should return quickly to avoid blocking execution
  • Spans are automatically nested under current trace/span
Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefon_span_start(self,span:"Span[Any]")->None:"""Called when a new span begins execution.    Args:        span: The span that started. Contains operation details and context.    Notes:        - Called synchronously on span start        - Should return quickly to avoid blocking execution        - Spans are automatically nested under current trace/span    """pass

on_span_endabstractmethod

on_span_end(span:Span[Any])->None

Called when a span completes execution.

Parameters:

NameTypeDescriptionDefault
spanSpan[Any]

The completed span containing execution results.

required
Notes
  • Called synchronously when span finishes
  • Should not block or raise exceptions
  • Good time to export/process the individual span
Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefon_span_end(self,span:"Span[Any]")->None:"""Called when a span completes execution.    Args:        span: The completed span containing execution results.    Notes:        - Called synchronously when span finishes        - Should not block or raise exceptions        - Good time to export/process the individual span    """pass

shutdownabstractmethod

shutdown()->None

Called when the application stops to clean up resources.

Should perform any necessary cleanup like:- Flushing queued traces/spans- Closing connections- Releasing resources

Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefshutdown(self)->None:"""Called when the application stops to clean up resources.    Should perform any necessary cleanup like:    - Flushing queued traces/spans    - Closing connections    - Releasing resources    """pass

force_flushabstractmethod

force_flush()->None

Forces immediate processing of any queued traces/spans.

Notes
  • Should process all queued items before returning
  • Useful before shutdown or when immediate processing is needed
  • May block while processing completes
Source code insrc/agents/tracing/processor_interface.py
@abc.abstractmethoddefforce_flush(self)->None:"""Forces immediate processing of any queued traces/spans.    Notes:        - Should process all queued items before returning        - Useful before shutdown or when immediate processing is needed        - May block while processing completes    """pass

TraceProvider

Bases:ABC

Interface for creating traces and spans.

Source code insrc/agents/tracing/provider.py
classTraceProvider(ABC):"""Interface for creating traces and spans."""@abstractmethoddefregister_processor(self,processor:TracingProcessor)->None:"""Add a processor that will receive all traces and spans."""@abstractmethoddefset_processors(self,processors:list[TracingProcessor])->None:"""Replace the list of processors with ``processors``."""@abstractmethoddefget_current_trace(self)->Trace|None:"""Return the currently active trace, if any."""@abstractmethoddefget_current_span(self)->Span[Any]|None:"""Return the currently active span, if any."""@abstractmethoddefset_disabled(self,disabled:bool)->None:"""Enable or disable tracing globally."""@abstractmethoddeftime_iso(self)->str:"""Return the current time in ISO 8601 format."""@abstractmethoddefgen_trace_id(self)->str:"""Generate a new trace identifier."""@abstractmethoddefgen_span_id(self)->str:"""Generate a new span identifier."""@abstractmethoddefgen_group_id(self)->str:"""Generate a new group identifier."""@abstractmethoddefcreate_trace(self,name:str,trace_id:str|None=None,group_id:str|None=None,metadata:dict[str,Any]|None=None,disabled:bool=False,)->Trace:"""Create a new trace."""@abstractmethoddefcreate_span(self,span_data:TSpanData,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[TSpanData]:"""Create a new span."""@abstractmethoddefshutdown(self)->None:"""Clean up any resources used by the provider."""

register_processorabstractmethod

register_processor(processor:TracingProcessor)->None

Add a processor that will receive all traces and spans.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefregister_processor(self,processor:TracingProcessor)->None:"""Add a processor that will receive all traces and spans."""

set_processorsabstractmethod

set_processors(processors:list[TracingProcessor])->None

Replace the list of processors withprocessors.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefset_processors(self,processors:list[TracingProcessor])->None:"""Replace the list of processors with ``processors``."""

get_current_traceabstractmethod

get_current_trace()->Trace|None

Return the currently active trace, if any.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefget_current_trace(self)->Trace|None:"""Return the currently active trace, if any."""

get_current_spanabstractmethod

get_current_span()->Span[Any]|None

Return the currently active span, if any.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefget_current_span(self)->Span[Any]|None:"""Return the currently active span, if any."""

set_disabledabstractmethod

set_disabled(disabled:bool)->None

Enable or disable tracing globally.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefset_disabled(self,disabled:bool)->None:"""Enable or disable tracing globally."""

time_isoabstractmethod

time_iso()->str

Return the current time in ISO 8601 format.

Source code insrc/agents/tracing/provider.py
@abstractmethoddeftime_iso(self)->str:"""Return the current time in ISO 8601 format."""

gen_trace_idabstractmethod

gen_trace_id()->str

Generate a new trace identifier.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefgen_trace_id(self)->str:"""Generate a new trace identifier."""

gen_span_idabstractmethod

gen_span_id()->str

Generate a new span identifier.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefgen_span_id(self)->str:"""Generate a new span identifier."""

gen_group_idabstractmethod

gen_group_id()->str

Generate a new group identifier.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefgen_group_id(self)->str:"""Generate a new group identifier."""

create_traceabstractmethod

create_trace(name:str,trace_id:str|None=None,group_id:str|None=None,metadata:dict[str,Any]|None=None,disabled:bool=False,)->Trace

Create a new trace.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefcreate_trace(self,name:str,trace_id:str|None=None,group_id:str|None=None,metadata:dict[str,Any]|None=None,disabled:bool=False,)->Trace:"""Create a new trace."""

create_spanabstractmethod

create_span(span_data:TSpanData,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[TSpanData]

Create a new span.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefcreate_span(self,span_data:TSpanData,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[TSpanData]:"""Create a new span."""

shutdownabstractmethod

shutdown()->None

Clean up any resources used by the provider.

Source code insrc/agents/tracing/provider.py
@abstractmethoddefshutdown(self)->None:"""Clean up any resources used by the provider."""

AgentSpanData

Bases:SpanData

Represents an Agent Span in the trace.Includes name, handoffs, tools, and output type.

Source code insrc/agents/tracing/span_data.py
classAgentSpanData(SpanData):"""    Represents an Agent Span in the trace.    Includes name, handoffs, tools, and output type.    """__slots__=("name","handoffs","tools","output_type")def__init__(self,name:str,handoffs:list[str]|None=None,tools:list[str]|None=None,output_type:str|None=None,):self.name=nameself.handoffs:list[str]|None=handoffsself.tools:list[str]|None=toolsself.output_type:str|None=output_type@propertydeftype(self)->str:return"agent"defexport(self)->dict[str,Any]:return{"type":self.type,"name":self.name,"handoffs":self.handoffs,"tools":self.tools,"output_type":self.output_type,}

CustomSpanData

Bases:SpanData

Represents a Custom Span in the trace.Includes name and data property bag.

Source code insrc/agents/tracing/span_data.py
classCustomSpanData(SpanData):"""    Represents a Custom Span in the trace.    Includes name and data property bag.    """__slots__=("name","data")def__init__(self,name:str,data:dict[str,Any]):self.name=nameself.data=data@propertydeftype(self)->str:return"custom"defexport(self)->dict[str,Any]:return{"type":self.type,"name":self.name,"data":self.data,}

FunctionSpanData

Bases:SpanData

Represents a Function Span in the trace.Includes input, output and MCP data (if applicable).

Source code insrc/agents/tracing/span_data.py
classFunctionSpanData(SpanData):"""    Represents a Function Span in the trace.    Includes input, output and MCP data (if applicable).    """__slots__=("name","input","output","mcp_data")def__init__(self,name:str,input:str|None,output:Any|None,mcp_data:dict[str,Any]|None=None,):self.name=nameself.input=inputself.output=outputself.mcp_data=mcp_data@propertydeftype(self)->str:return"function"defexport(self)->dict[str,Any]:return{"type":self.type,"name":self.name,"input":self.input,"output":str(self.output)ifself.outputelseNone,"mcp_data":self.mcp_data,}

GenerationSpanData

Bases:SpanData

Represents a Generation Span in the trace.Includes input, output, model, model configuration, and usage.

Source code insrc/agents/tracing/span_data.py
classGenerationSpanData(SpanData):"""    Represents a Generation Span in the trace.    Includes input, output, model, model configuration, and usage.    """__slots__=("input","output","model","model_config","usage",)def__init__(self,input:Sequence[Mapping[str,Any]]|None=None,output:Sequence[Mapping[str,Any]]|None=None,model:str|None=None,model_config:Mapping[str,Any]|None=None,usage:dict[str,Any]|None=None,):self.input=inputself.output=outputself.model=modelself.model_config=model_configself.usage=usage@propertydeftype(self)->str:return"generation"defexport(self)->dict[str,Any]:return{"type":self.type,"input":self.input,"output":self.output,"model":self.model,"model_config":self.model_config,"usage":self.usage,}

GuardrailSpanData

Bases:SpanData

Represents a Guardrail Span in the trace.Includes name and triggered status.

Source code insrc/agents/tracing/span_data.py
classGuardrailSpanData(SpanData):"""    Represents a Guardrail Span in the trace.    Includes name and triggered status.    """__slots__=("name","triggered")def__init__(self,name:str,triggered:bool=False):self.name=nameself.triggered=triggered@propertydeftype(self)->str:return"guardrail"defexport(self)->dict[str,Any]:return{"type":self.type,"name":self.name,"triggered":self.triggered,}

HandoffSpanData

Bases:SpanData

Represents a Handoff Span in the trace.Includes source and destination agents.

Source code insrc/agents/tracing/span_data.py
classHandoffSpanData(SpanData):"""    Represents a Handoff Span in the trace.    Includes source and destination agents.    """__slots__=("from_agent","to_agent")def__init__(self,from_agent:str|None,to_agent:str|None):self.from_agent=from_agentself.to_agent=to_agent@propertydeftype(self)->str:return"handoff"defexport(self)->dict[str,Any]:return{"type":self.type,"from_agent":self.from_agent,"to_agent":self.to_agent,}

MCPListToolsSpanData

Bases:SpanData

Represents an MCP List Tools Span in the trace.Includes server and result.

Source code insrc/agents/tracing/span_data.py
classMCPListToolsSpanData(SpanData):"""    Represents an MCP List Tools Span in the trace.    Includes server and result.    """__slots__=("server","result",)def__init__(self,server:str|None=None,result:list[str]|None=None):self.server=serverself.result=result@propertydeftype(self)->str:return"mcp_tools"defexport(self)->dict[str,Any]:return{"type":self.type,"server":self.server,"result":self.result,}

ResponseSpanData

Bases:SpanData

Represents a Response Span in the trace.Includes response and input.

Source code insrc/agents/tracing/span_data.py
classResponseSpanData(SpanData):"""    Represents a Response Span in the trace.    Includes response and input.    """__slots__=("response","input")def__init__(self,response:Response|None=None,input:str|list[ResponseInputItemParam]|None=None,)->None:self.response=response# This is not used by the OpenAI trace processors, but is useful for other tracing# processor implementationsself.input=input@propertydeftype(self)->str:return"response"defexport(self)->dict[str,Any]:return{"type":self.type,"response_id":self.response.idifself.responseelseNone,}

SpanData

Bases:ABC

Represents span data in the trace.

Source code insrc/agents/tracing/span_data.py
classSpanData(abc.ABC):"""    Represents span data in the trace.    """@abc.abstractmethoddefexport(self)->dict[str,Any]:"""Export the span data as a dictionary."""pass@property@abc.abstractmethoddeftype(self)->str:"""Return the type of the span."""pass

typeabstractmethodproperty

type:str

Return the type of the span.

exportabstractmethod

export()->dict[str,Any]

Export the span data as a dictionary.

Source code insrc/agents/tracing/span_data.py
@abc.abstractmethoddefexport(self)->dict[str,Any]:"""Export the span data as a dictionary."""pass

SpeechGroupSpanData

Bases:SpanData

Represents a Speech Group Span in the trace.

Source code insrc/agents/tracing/span_data.py
classSpeechGroupSpanData(SpanData):"""    Represents a Speech Group Span in the trace.    """__slots__="input"def__init__(self,input:str|None=None,):self.input=input@propertydeftype(self)->str:return"speech_group"defexport(self)->dict[str,Any]:return{"type":self.type,"input":self.input,}

SpeechSpanData

Bases:SpanData

Represents a Speech Span in the trace.Includes input, output, model, model configuration, and first content timestamp.

Source code insrc/agents/tracing/span_data.py
classSpeechSpanData(SpanData):"""    Represents a Speech Span in the trace.    Includes input, output, model, model configuration, and first content timestamp.    """__slots__=("input","output","model","model_config","first_content_at")def__init__(self,input:str|None=None,output:str|None=None,output_format:str|None="pcm",model:str|None=None,model_config:Mapping[str,Any]|None=None,first_content_at:str|None=None,):self.input=inputself.output=outputself.output_format=output_formatself.model=modelself.model_config=model_configself.first_content_at=first_content_at@propertydeftype(self)->str:return"speech"defexport(self)->dict[str,Any]:return{"type":self.type,"input":self.input,"output":{"data":self.outputor"","format":self.output_format,},"model":self.model,"model_config":self.model_config,"first_content_at":self.first_content_at,}

TranscriptionSpanData

Bases:SpanData

Represents a Transcription Span in the trace.Includes input, output, model, and model configuration.

Source code insrc/agents/tracing/span_data.py
classTranscriptionSpanData(SpanData):"""    Represents a Transcription Span in the trace.    Includes input, output, model, and model configuration.    """__slots__=("input","output","model","model_config",)def__init__(self,input:str|None=None,input_format:str|None="pcm",output:str|None=None,model:str|None=None,model_config:Mapping[str,Any]|None=None,):self.input=inputself.input_format=input_formatself.output=outputself.model=modelself.model_config=model_config@propertydeftype(self)->str:return"transcription"defexport(self)->dict[str,Any]:return{"type":self.type,"input":{"data":self.inputor"","format":self.input_format,},"output":self.output,"model":self.model,"model_config":self.model_config,}

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

SpanError

Bases:TypedDict

Represents an error that occurred during span execution.

Attributes:

NameTypeDescription
messagestr

A human-readable error description

datadict[str,Any] | None

Optional dictionary containing additional error context

Source code insrc/agents/tracing/spans.py
classSpanError(TypedDict):"""Represents an error that occurred during span execution.    Attributes:        message: A human-readable error description        data: Optional dictionary containing additional error context    """message:strdata:dict[str,Any]|None

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

agent_span

agent_span(name:str,handoffs:list[str]|None=None,tools:list[str]|None=None,output_type:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[AgentSpanData]

Create a new agent span. The span will not be started automatically, you should either dowith agent_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the agent.

required
handoffslist[str] | None

Optional list of agent names to which this agent could hand off control.

None
toolslist[str] | None

Optional list of tool names available to this agent.

None
output_typestr | None

Optional name of the output type produced by the agent.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[AgentSpanData]

The newly created agent span.

Source code insrc/agents/tracing/create.py
defagent_span(name:str,handoffs:list[str]|None=None,tools:list[str]|None=None,output_type:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[AgentSpanData]:"""Create a new agent span. The span will not be started automatically, you should either do    `with agent_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        name: The name of the agent.        handoffs: Optional list of agent names to which this agent could hand off control.        tools: Optional list of tool names available to this agent.        output_type: Optional name of the output type produced by the agent.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created agent span.    """returnget_trace_provider().create_span(span_data=AgentSpanData(name=name,handoffs=handoffs,tools=tools,output_type=output_type),span_id=span_id,parent=parent,disabled=disabled,)

custom_span

custom_span(name:str,data:dict[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[CustomSpanData]

Create a new custom span, to which you can add your own metadata. The span will not bestarted automatically, you should either dowith custom_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the custom span.

required
datadict[str,Any] | None

Arbitrary structured data to associate with the span.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[CustomSpanData]

The newly created custom span.

Source code insrc/agents/tracing/create.py
defcustom_span(name:str,data:dict[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[CustomSpanData]:"""Create a new custom span, to which you can add your own metadata. The span will not be    started automatically, you should either do `with custom_span() ...` or call    `span.start()` + `span.finish()` manually.    Args:        name: The name of the custom span.        data: Arbitrary structured data to associate with the span.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created custom span.    """returnget_trace_provider().create_span(span_data=CustomSpanData(name=name,data=dataor{}),span_id=span_id,parent=parent,disabled=disabled,)

function_span

function_span(name:str,input:str|None=None,output:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[FunctionSpanData]

Create a new function span. The span will not be started automatically, you should either dowith function_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the function.

required
inputstr | None

The input to the function.

None
outputstr | None

The output of the function.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[FunctionSpanData]

The newly created function span.

Source code insrc/agents/tracing/create.py
deffunction_span(name:str,input:str|None=None,output:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[FunctionSpanData]:"""Create a new function span. The span will not be started automatically, you should either do    `with function_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        name: The name of the function.        input: The input to the function.        output: The output of the function.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created function span.    """returnget_trace_provider().create_span(span_data=FunctionSpanData(name=name,input=input,output=output),span_id=span_id,parent=parent,disabled=disabled,)

generation_span

generation_span(input:Sequence[Mapping[str,Any]]|None=None,output:Sequence[Mapping[str,Any]]|None=None,model:str|None=None,model_config:Mapping[str,Any]|None=None,usage:dict[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[GenerationSpanData]

Create a new generation span. The span will not be started automatically, you should eitherdowith generation_span() ... or callspan.start() +span.finish() manually.

This span captures the details of a model generation, including theinput message sequence, any generated outputs, the model name andconfiguration, and usage data. If you only need to capture a modelresponse identifier, useresponse_span() instead.

Parameters:

NameTypeDescriptionDefault
inputSequence[Mapping[str,Any]] | None

The sequence of input messages sent to the model.

None
outputSequence[Mapping[str,Any]] | None

The sequence of output messages received from the model.

None
modelstr | None

The model identifier used for the generation.

None
model_configMapping[str,Any] | None

The model configuration (hyperparameters) used.

None
usagedict[str,Any] | None

A dictionary of usage information (input tokens, output tokens, etc.).

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[GenerationSpanData]

The newly created generation span.

Source code insrc/agents/tracing/create.py
defgeneration_span(input:Sequence[Mapping[str,Any]]|None=None,output:Sequence[Mapping[str,Any]]|None=None,model:str|None=None,model_config:Mapping[str,Any]|None=None,usage:dict[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[GenerationSpanData]:"""Create a new generation span. The span will not be started automatically, you should either    do `with generation_span() ...` or call `span.start()` + `span.finish()` manually.    This span captures the details of a model generation, including the    input message sequence, any generated outputs, the model name and    configuration, and usage data. If you only need to capture a model    response identifier, use `response_span()` instead.    Args:        input: The sequence of input messages sent to the model.        output: The sequence of output messages received from the model.        model: The model identifier used for the generation.        model_config: The model configuration (hyperparameters) used.        usage: A dictionary of usage information (input tokens, output tokens, etc.).        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created generation span.    """returnget_trace_provider().create_span(span_data=GenerationSpanData(input=input,output=output,model=model,model_config=model_config,usage=usage,),span_id=span_id,parent=parent,disabled=disabled,)

get_current_span

get_current_span()->Span[Any]|None

Returns the currently active span, if present.

Source code insrc/agents/tracing/create.py
defget_current_span()->Span[Any]|None:"""Returns the currently active span, if present."""returnget_trace_provider().get_current_span()

get_current_trace

get_current_trace()->Trace|None

Returns the currently active trace, if present.

Source code insrc/agents/tracing/create.py
defget_current_trace()->Trace|None:"""Returns the currently active trace, if present."""returnget_trace_provider().get_current_trace()

guardrail_span

guardrail_span(name:str,triggered:bool=False,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[GuardrailSpanData]

Create a new guardrail span. The span will not be started automatically, you should eitherdowith guardrail_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the guardrail.

required
triggeredbool

Whether the guardrail was triggered.

False
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False
Source code insrc/agents/tracing/create.py
defguardrail_span(name:str,triggered:bool=False,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[GuardrailSpanData]:"""Create a new guardrail span. The span will not be started automatically, you should either    do `with guardrail_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        name: The name of the guardrail.        triggered: Whether the guardrail was triggered.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    """returnget_trace_provider().create_span(span_data=GuardrailSpanData(name=name,triggered=triggered),span_id=span_id,parent=parent,disabled=disabled,)

handoff_span

handoff_span(from_agent:str|None=None,to_agent:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[HandoffSpanData]

Create a new handoff span. The span will not be started automatically, you should either dowith handoff_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
from_agentstr | None

The name of the agent that is handing off.

None
to_agentstr | None

The name of the agent that is receiving the handoff.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[HandoffSpanData]

The newly created handoff span.

Source code insrc/agents/tracing/create.py
defhandoff_span(from_agent:str|None=None,to_agent:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[HandoffSpanData]:"""Create a new handoff span. The span will not be started automatically, you should either do    `with handoff_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        from_agent: The name of the agent that is handing off.        to_agent: The name of the agent that is receiving the handoff.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created handoff span.    """returnget_trace_provider().create_span(span_data=HandoffSpanData(from_agent=from_agent,to_agent=to_agent),span_id=span_id,parent=parent,disabled=disabled,)

mcp_tools_span

mcp_tools_span(server:str|None=None,result:list[str]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[MCPListToolsSpanData]

Create a new MCP list tools span. The span will not be started automatically, you shouldeither dowith mcp_tools_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
serverstr | None

The name of the MCP server.

None
resultlist[str] | None

The result of the MCP list tools call.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False
Source code insrc/agents/tracing/create.py
defmcp_tools_span(server:str|None=None,result:list[str]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[MCPListToolsSpanData]:"""Create a new MCP list tools span. The span will not be started automatically, you should    either do `with mcp_tools_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        server: The name of the MCP server.        result: The result of the MCP list tools call.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    """returnget_trace_provider().create_span(span_data=MCPListToolsSpanData(server=server,result=result),span_id=span_id,parent=parent,disabled=disabled,)

response_span

response_span(response:Response|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[ResponseSpanData]

Create a new response span. The span will not be started automatically, you should either dowith response_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
responseResponse | None

The OpenAI Response object.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False
Source code insrc/agents/tracing/create.py
defresponse_span(response:Response|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[ResponseSpanData]:"""Create a new response span. The span will not be started automatically, you should either do    `with response_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        response: The OpenAI Response object.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    """returnget_trace_provider().create_span(span_data=ResponseSpanData(response=response),span_id=span_id,parent=parent,disabled=disabled,)

speech_group_span

speech_group_span(input:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[SpeechGroupSpanData]

Create a new speech group span. The span will not be started automatically, you shouldeither dowith speech_group_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
inputstr | None

The input text used for the speech request.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False
Source code insrc/agents/tracing/create.py
defspeech_group_span(input:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[SpeechGroupSpanData]:"""Create a new speech group span. The span will not be started automatically, you should    either do `with speech_group_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        input: The input text used for the speech request.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    """returnget_trace_provider().create_span(span_data=SpeechGroupSpanData(input=input),span_id=span_id,parent=parent,disabled=disabled,)

speech_span

speech_span(model:str|None=None,input:str|None=None,output:str|None=None,output_format:str|None="pcm",model_config:Mapping[str,Any]|None=None,first_content_at:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[SpeechSpanData]

Create a new speech span. The span will not be started automatically, you should either dowith speech_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
modelstr | None

The name of the model used for the text-to-speech.

None
inputstr | None

The text input of the text-to-speech.

None
outputstr | None

The audio output of the text-to-speech as base64 encoded string of PCM audio bytes.

None
output_formatstr | None

The format of the audio output (defaults to "pcm").

'pcm'
model_configMapping[str,Any] | None

The model configuration (hyperparameters) used.

None
first_content_atstr | None

The time of the first byte of the audio output.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False
Source code insrc/agents/tracing/create.py
defspeech_span(model:str|None=None,input:str|None=None,output:str|None=None,output_format:str|None="pcm",model_config:Mapping[str,Any]|None=None,first_content_at:str|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[SpeechSpanData]:"""Create a new speech span. The span will not be started automatically, you should either do    `with speech_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        model: The name of the model used for the text-to-speech.        input: The text input of the text-to-speech.        output: The audio output of the text-to-speech as base64 encoded string of PCM audio bytes.        output_format: The format of the audio output (defaults to "pcm").        model_config: The model configuration (hyperparameters) used.        first_content_at: The time of the first byte of the audio output.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    """returnget_trace_provider().create_span(span_data=SpeechSpanData(model=model,input=input,output=output,output_format=output_format,model_config=model_config,first_content_at=first_content_at,),span_id=span_id,parent=parent,disabled=disabled,)

trace

trace(workflow_name:str,trace_id:str|None=None,group_id:str|None=None,metadata:dict[str,Any]|None=None,disabled:bool=False,)->Trace

Create a new trace. The trace will not be started automatically; you should either useit as a context manager (with trace(...):) or calltrace.start() +trace.finish()manually.

In addition to the workflow name and optional grouping identifier, you can providean arbitrary metadata dictionary to attach additional user-defined information tothe trace.

Parameters:

NameTypeDescriptionDefault
workflow_namestr

The name of the logical app or workflow. For example, you might provide"code_bot" for a coding agent, or "customer_support_agent" for a customer support agent.

required
trace_idstr | None

The ID of the trace. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_trace_id() to generate a trace ID, to guarantee that IDs arecorrectly formatted.

None
group_idstr | None

Optional grouping identifier to link multiple traces from the same conversationor process. For instance, you might use a chat thread ID.

None
metadatadict[str,Any] | None

Optional dictionary of additional metadata to attach to the trace.

None
disabledbool

If True, we will return a Trace but the Trace will not be recorded.

False

Returns:

TypeDescription
Trace

The newly created trace object.

Source code insrc/agents/tracing/create.py
deftrace(workflow_name:str,trace_id:str|None=None,group_id:str|None=None,metadata:dict[str,Any]|None=None,disabled:bool=False,)->Trace:"""    Create a new trace. The trace will not be started automatically; you should either use    it as a context manager (`with trace(...):`) or call `trace.start()` + `trace.finish()`    manually.    In addition to the workflow name and optional grouping identifier, you can provide    an arbitrary metadata dictionary to attach additional user-defined information to    the trace.    Args:        workflow_name: The name of the logical app or workflow. For example, you might provide            "code_bot" for a coding agent, or "customer_support_agent" for a customer support agent.        trace_id: The ID of the trace. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_trace_id()` to generate a trace ID, to guarantee that IDs are            correctly formatted.        group_id: Optional grouping identifier to link multiple traces from the same conversation            or process. For instance, you might use a chat thread ID.        metadata: Optional dictionary of additional metadata to attach to the trace.        disabled: If True, we will return a Trace but the Trace will not be recorded.    Returns:        The newly created trace object.    """current_trace=get_trace_provider().get_current_trace()ifcurrent_trace:logger.warning("Trace already exists. Creating a new trace, but this is probably a mistake.")returnget_trace_provider().create_trace(name=workflow_name,trace_id=trace_id,group_id=group_id,metadata=metadata,disabled=disabled,)

transcription_span

transcription_span(model:str|None=None,input:str|None=None,input_format:str|None="pcm",output:str|None=None,model_config:Mapping[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[TranscriptionSpanData]

Create a new transcription span. The span will not be started automatically, you shouldeither dowith transcription_span() ... or callspan.start() +span.finish() manually.

Parameters:

NameTypeDescriptionDefault
modelstr | None

The name of the model used for the speech-to-text.

None
inputstr | None

The audio input of the speech-to-text transcription, as a base64 encoded string ofaudio bytes.

None
input_formatstr | None

The format of the audio input (defaults to "pcm").

'pcm'
outputstr | None

The output of the speech-to-text transcription.

None
model_configMapping[str,Any] | None

The model configuration (hyperparameters) used.

None
span_idstr | None

The ID of the span. Optional. If not provided, we will generate an ID. Werecommend usingutil.gen_span_id() to generate a span ID, to guarantee that IDs arecorrectly formatted.

None
parentTrace |Span[Any] | None

The parent span or trace. If not provided, we will automatically use the currenttrace/span as the parent.

None
disabledbool

If True, we will return a Span but the Span will not be recorded.

False

Returns:

TypeDescription
Span[TranscriptionSpanData]

The newly created speech-to-text span.

Source code insrc/agents/tracing/create.py
deftranscription_span(model:str|None=None,input:str|None=None,input_format:str|None="pcm",output:str|None=None,model_config:Mapping[str,Any]|None=None,span_id:str|None=None,parent:Trace|Span[Any]|None=None,disabled:bool=False,)->Span[TranscriptionSpanData]:"""Create a new transcription span. The span will not be started automatically, you should    either do `with transcription_span() ...` or call `span.start()` + `span.finish()` manually.    Args:        model: The name of the model used for the speech-to-text.        input: The audio input of the speech-to-text transcription, as a base64 encoded string of            audio bytes.        input_format: The format of the audio input (defaults to "pcm").        output: The output of the speech-to-text transcription.        model_config: The model configuration (hyperparameters) used.        span_id: The ID of the span. Optional. If not provided, we will generate an ID. We            recommend using `util.gen_span_id()` to generate a span ID, to guarantee that IDs are            correctly formatted.        parent: The parent span or trace. If not provided, we will automatically use the current            trace/span as the parent.        disabled: If True, we will return a Span but the Span will not be recorded.    Returns:        The newly created speech-to-text span.    """returnget_trace_provider().create_span(span_data=TranscriptionSpanData(input=input,input_format=input_format,output=output,model=model,model_config=model_config,),span_id=span_id,parent=parent,disabled=disabled,)

get_trace_provider

get_trace_provider()->TraceProvider

Get the global trace provider used by tracing utilities.

Source code insrc/agents/tracing/setup.py
defget_trace_provider()->TraceProvider:"""Get the global trace provider used by tracing utilities."""ifGLOBAL_TRACE_PROVIDERisNone:raiseRuntimeError("Trace provider not set")returnGLOBAL_TRACE_PROVIDER

set_trace_provider

set_trace_provider(provider:TraceProvider)->None

Set the global trace provider used by tracing utilities.

Source code insrc/agents/tracing/setup.py
defset_trace_provider(provider:TraceProvider)->None:"""Set the global trace provider used by tracing utilities."""globalGLOBAL_TRACE_PROVIDERGLOBAL_TRACE_PROVIDER=provider

gen_span_id

gen_span_id()->str

Generate a new span ID.

Source code insrc/agents/tracing/util.py
defgen_span_id()->str:"""Generate a new span ID."""returnget_trace_provider().gen_span_id()

gen_trace_id

gen_trace_id()->str

Generate a new trace ID.

Source code insrc/agents/tracing/util.py
defgen_trace_id()->str:"""Generate a new trace ID."""returnget_trace_provider().gen_trace_id()

add_trace_processor

add_trace_processor(span_processor:TracingProcessor,)->None

Adds a new trace processor. This processor will receive all traces/spans.

Source code insrc/agents/tracing/__init__.py
defadd_trace_processor(span_processor:TracingProcessor)->None:"""    Adds a new trace processor. This processor will receive all traces/spans.    """get_trace_provider().register_processor(span_processor)

set_trace_processors

set_trace_processors(processors:list[TracingProcessor],)->None

Set the list of trace processors. This will replace the current list of processors.

Source code insrc/agents/tracing/__init__.py
defset_trace_processors(processors:list[TracingProcessor])->None:"""    Set the list of trace processors. This will replace the current list of processors.    """get_trace_provider().set_processors(processors)

set_tracing_disabled

set_tracing_disabled(disabled:bool)->None

Set whether tracing is globally disabled.

Source code insrc/agents/tracing/__init__.py
defset_tracing_disabled(disabled:bool)->None:"""    Set whether tracing is globally disabled.    """get_trace_provider().set_disabled(disabled)

set_tracing_export_api_key

set_tracing_export_api_key(api_key:str)->None

Set the OpenAI API key for the backend exporter.

Source code insrc/agents/tracing/__init__.py
defset_tracing_export_api_key(api_key:str)->None:"""    Set the OpenAI API key for the backend exporter.    """default_exporter().set_api_key(api_key)

[8]ページ先頭

©2009-2025 Movatter.jp