跳过内容

追踪模块

TracingConfig

基础: TypedDict

Tracing 导出配置。

源代码在 src/agents/tracing/config.py
6
7
8
9
class TracingConfig(TypedDict, total=False):
    """Configuration for tracing export."""

    api_key: str

TracingProcessor

基础: ABC

OpenAI Agents 系统中处理和监控跟踪和跨度的接口。

这个抽象类定义了所有跟踪处理器必须实现接口。处理器在跟踪和跨度开始和结束时接收通知,允许它们收集、处理和导出跟踪数据。

示例
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
注意事项
  • 所有方法都应该是线程安全的
  • 方法不应长时间阻塞
  • 优雅地处理错误以防止干扰代理执行
源代码在 src/agents/tracing/processor_interface.py
class TracingProcessor(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.abstractmethod
    def on_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.abstractmethod
    def on_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.abstractmethod
    def on_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.abstractmethod
    def on_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.abstractmethod
    def shutdown(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.abstractmethod
    def force_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_start abstractmethod

on_trace_start(trace: Trace) -> None

当新的跟踪开始执行时调用。

参数

名称 类型 描述 默认
trace Trace

开始的跟踪。包含工作流名称和元数据。

required
注意事项
  • 在跟踪开始时同步调用
  • 应快速返回以避免阻塞执行
  • 任何错误都应被捕获并在内部处理
源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_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_end abstractmethod

on_trace_end(trace: Trace) -> None

当跟踪完成执行时调用。

参数

名称 类型 描述 默认
trace Trace

包含所有跨度和结果的完成的跟踪。

required
注意事项
  • 在跟踪完成时同步调用
  • 导出/处理完整跟踪的好时机
  • 应处理任何特定于跟踪的资源的清理
源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_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_start abstractmethod

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

当新的跨度开始执行时调用。

参数

名称 类型 描述 默认
span Span[Any]

开始的跨度。包含操作详细信息和上下文。

required
注意事项
  • 在跨度开始时同步调用
  • 应快速返回以避免阻塞执行
  • 跨度会自动嵌套在当前跟踪/跨度下
源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_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_end abstractmethod

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

当跨度完成执行时调用。

参数

名称 类型 描述 默认
span Span[Any]

包含执行结果的完成的跨度。

required
注意事项
  • 在跨度完成时同步调用
  • 不应阻塞或引发异常
  • 导出/处理单个跨度的好时机
源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_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

shutdown abstractmethod

shutdown() -> None

在应用程序停止时清理资源。

应执行任何必要的清理,例如:- 清理排队的跟踪/跨度 - 关闭连接 - 释放资源

源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def shutdown(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_flush abstractmethod

force_flush() -> None

强制立即处理任何排队的跟踪/跨度。

注意事项
  • 应在返回之前处理所有排队的项目
  • 在关闭之前或需要立即处理时很有用
  • 在处理完成时可能会阻塞
源代码在 src/agents/tracing/processor_interface.py
@abc.abstractmethod
def force_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

基础: ABC

创建跟踪和跨度的接口。

源代码在 src/agents/tracing/provider.py
class TraceProvider(ABC):
    """Interface for creating traces and spans."""

    @abstractmethod
    def register_processor(self, processor: TracingProcessor) -> None:
        """Add a processor that will receive all traces and spans."""

    @abstractmethod
    def set_processors(self, processors: list[TracingProcessor]) -> None:
        """Replace the list of processors with ``processors``."""

    @abstractmethod
    def get_current_trace(self) -> Trace | None:
        """Return the currently active trace, if any."""

    @abstractmethod
    def get_current_span(self) -> Span[Any] | None:
        """Return the currently active span, if any."""

    @abstractmethod
    def set_disabled(self, disabled: bool) -> None:
        """Enable or disable tracing globally."""

    @abstractmethod
    def time_iso(self) -> str:
        """Return the current time in ISO 8601 format."""

    @abstractmethod
    def gen_trace_id(self) -> str:
        """Generate a new trace identifier."""

    @abstractmethod
    def gen_span_id(self) -> str:
        """Generate a new span identifier."""

    @abstractmethod
    def gen_group_id(self) -> str:
        """Generate a new group identifier."""

    @abstractmethod
    def create_trace(
        self,
        name: str,
        trace_id: str | None = None,
        group_id: str | None = None,
        metadata: dict[str, Any] | None = None,
        disabled: bool = False,
        tracing: TracingConfig | None = None,
    ) -> Trace:
        """Create a new trace."""

    @abstractmethod
    def create_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."""

    @abstractmethod
    def shutdown(self) -> None:
        """Clean up any resources used by the provider."""

register_processor abstractmethod

register_processor(processor: TracingProcessor) -> None

添加一个处理器,它将接收所有跟踪和跨度。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def register_processor(self, processor: TracingProcessor) -> None:
    """Add a processor that will receive all traces and spans."""

set_processors abstractmethod

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

使用 processors 替换处理器列表。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def set_processors(self, processors: list[TracingProcessor]) -> None:
    """Replace the list of processors with ``processors``."""

get_current_trace abstractmethod

get_current_trace() -> Trace | None

返回当前活动的跟踪(如果有)。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def get_current_trace(self) -> Trace | None:
    """Return the currently active trace, if any."""

get_current_span abstractmethod

get_current_span() -> Span[Any] | None

返回当前活动的跨度(如果有)。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def get_current_span(self) -> Span[Any] | None:
    """Return the currently active span, if any."""

set_disabled abstractmethod

set_disabled(disabled: bool) -> None

全局启用或禁用跟踪。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def set_disabled(self, disabled: bool) -> None:
    """Enable or disable tracing globally."""

time_iso abstractmethod

time_iso() -> str

以 ISO 8601 格式返回当前时间。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def time_iso(self) -> str:
    """Return the current time in ISO 8601 format."""

gen_trace_id abstractmethod

gen_trace_id() -> str

生成一个新的跟踪标识符。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def gen_trace_id(self) -> str:
    """Generate a new trace identifier."""

gen_span_id abstractmethod

gen_span_id() -> str

生成一个新的跨度标识符。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def gen_span_id(self) -> str:
    """Generate a new span identifier."""

gen_group_id abstractmethod

gen_group_id() -> str

生成一个新的组标识符。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def gen_group_id(self) -> str:
    """Generate a new group identifier."""

create_trace abstractmethod

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

创建一个新的跟踪。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def create_trace(
    self,
    name: str,
    trace_id: str | None = None,
    group_id: str | None = None,
    metadata: dict[str, Any] | None = None,
    disabled: bool = False,
    tracing: TracingConfig | None = None,
) -> Trace:
    """Create a new trace."""

create_span abstractmethod

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

创建一个新的跨度。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def create_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."""

shutdown abstractmethod

shutdown() -> None

清理提供程序使用的任何资源。

源代码在 src/agents/tracing/provider.py
@abstractmethod
def shutdown(self) -> None:
    """Clean up any resources used by the provider."""

AgentSpanData

基类: SpanData

表示跟踪中的 Agent 跨度。包括名称、交接、工具和输出类型。

源代码在 src/agents/tracing/span_data.py
class AgentSpanData(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 = name
        self.handoffs: list[str] | None = handoffs
        self.tools: list[str] | None = tools
        self.output_type: str | None = output_type

    @property
    def type(self) -> str:
        return "agent"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "name": self.name,
            "handoffs": self.handoffs,
            "tools": self.tools,
            "output_type": self.output_type,
        }

CustomSpanData

基类: SpanData

表示跟踪中的自定义跨度。包括名称和数据属性包。

源代码在 src/agents/tracing/span_data.py
class CustomSpanData(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 = name
        self.data = data

    @property
    def type(self) -> str:
        return "custom"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "name": self.name,
            "data": self.data,
        }

FunctionSpanData

基类: SpanData

表示跟踪中的函数跨度。包括输入、输出和 MCP 数据(如果适用)。

源代码在 src/agents/tracing/span_data.py
class FunctionSpanData(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 = name
        self.input = input
        self.output = output
        self.mcp_data = mcp_data

    @property
    def type(self) -> str:
        return "function"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "name": self.name,
            "input": self.input,
            "output": str(self.output) if self.output else None,
            "mcp_data": self.mcp_data,
        }

GenerationSpanData

基类: SpanData

表示跟踪中的生成跨度。包括输入、输出、模型、模型配置和使用情况。

源代码在 src/agents/tracing/span_data.py
class GenerationSpanData(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 = input
        self.output = output
        self.model = model
        self.model_config = model_config
        self.usage = usage

    @property
    def type(self) -> str:
        return "generation"

    def export(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

基类: SpanData

表示跟踪中的 Guardrail 跨度。包括名称和触发状态。

源代码在 src/agents/tracing/span_data.py
class GuardrailSpanData(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 = name
        self.triggered = triggered

    @property
    def type(self) -> str:
        return "guardrail"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "name": self.name,
            "triggered": self.triggered,
        }

HandoffSpanData

基类: SpanData

表示跟踪中的交接跨度。包括源代理和目标代理。

源代码在 src/agents/tracing/span_data.py
class HandoffSpanData(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_agent
        self.to_agent = to_agent

    @property
    def type(self) -> str:
        return "handoff"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "from_agent": self.from_agent,
            "to_agent": self.to_agent,
        }

MCPListToolsSpanData

基类: SpanData

表示跟踪中的 MCP List Tools 跨度。包括服务器和结果。

源代码在 src/agents/tracing/span_data.py
class MCPListToolsSpanData(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 = server
        self.result = result

    @property
    def type(self) -> str:
        return "mcp_tools"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "server": self.server,
            "result": self.result,
        }

ResponseSpanData

基类: SpanData

表示跟踪中的响应跨度。包括响应和输入。

源代码在 src/agents/tracing/span_data.py
class ResponseSpanData(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 implementations
        self.input = input

    @property
    def type(self) -> str:
        return "response"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "response_id": self.response.id if self.response else None,
        }

SpanData

基础: ABC

表示跟踪中的跨度数据。

源代码在 src/agents/tracing/span_data.py
class SpanData(abc.ABC):
    """
    Represents span data in the trace.
    """

    @abc.abstractmethod
    def export(self) -> dict[str, Any]:
        """Export the span data as a dictionary."""
        pass

    @property
    @abc.abstractmethod
    def type(self) -> str:
        """Return the type of the span."""
        pass

type abstractmethod property

type: str

返回跨度的类型。

export abstractmethod

export() -> dict[str, Any]

将跨度数据导出为字典。

源代码在 src/agents/tracing/span_data.py
@abc.abstractmethod
def export(self) -> dict[str, Any]:
    """Export the span data as a dictionary."""
    pass

SpeechGroupSpanData

基类: SpanData

表示跟踪中的语音组跨度。

源代码在 src/agents/tracing/span_data.py
class SpeechGroupSpanData(SpanData):
    """
    Represents a Speech Group Span in the trace.
    """

    __slots__ = "input"

    def __init__(
        self,
        input: str | None = None,
    ):
        self.input = input

    @property
    def type(self) -> str:
        return "speech_group"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "input": self.input,
        }

SpeechSpanData

基类: SpanData

表示跟踪中的语音跨度。包括输入、输出、模型、模型配置和第一个内容时间戳。

源代码在 src/agents/tracing/span_data.py
class SpeechSpanData(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 = input
        self.output = output
        self.output_format = output_format
        self.model = model
        self.model_config = model_config
        self.first_content_at = first_content_at

    @property
    def type(self) -> str:
        return "speech"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "input": self.input,
            "output": {
                "data": self.output or "",
                "format": self.output_format,
            },
            "model": self.model,
            "model_config": self.model_config,
            "first_content_at": self.first_content_at,
        }

TranscriptionSpanData

基类: SpanData

表示跟踪中的转录跨度。包括输入、输出、模型和模型配置。

源代码在 src/agents/tracing/span_data.py
class TranscriptionSpanData(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 = input
        self.input_format = input_format
        self.output = output
        self.model = model
        self.model_config = model_config

    @property
    def type(self) -> str:
        return "transcription"

    def export(self) -> dict[str, Any]:
        return {
            "type": self.type,
            "input": {
                "data": self.input or "",
                "format": self.input_format,
            },
            "output": self.output,
            "model": self.model,
            "model_config": self.model_config,
        }

Span

基类: ABC, Generic[TSpanData]

表示具有时序和上下文的可跟踪操作的基类。

跨度表示跟踪中的单个操作(例如,LLM 调用、工具执行或代理运行)。跨度跟踪时序、操作之间的关系以及操作特定数据。

示例
# 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

说明:- 跨度会自动嵌套在当前跟踪下 - 使用上下文管理器以确保可靠的开始/完成 - 包含相关数据,但避免敏感信息 - 使用 set_error() 正确处理错误

源代码在 src/agents/tracing/spans.py
class Span(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.abstractmethod
    def trace_id(self) -> str:
        """The ID of the trace this span belongs to.

        Returns:
            str: Unique identifier of the parent trace.
        """
        pass

    @property
    @abc.abstractmethod
    def span_id(self) -> str:
        """Unique identifier for this span.

        Returns:
            str: The span's unique ID within its trace.
        """
        pass

    @property
    @abc.abstractmethod
    def span_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.abstractmethod
    def start(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.abstractmethod
    def finish(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.abstractmethod
    def __enter__(self) -> Span[TSpanData]:
        pass

    @abc.abstractmethod
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @property
    @abc.abstractmethod
    def parent_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.abstractmethod
    def set_error(self, error: SpanError) -> None:
        pass

    @property
    @abc.abstractmethod
    def error(self) -> SpanError | None:
        """Any error that occurred during span execution.

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

    @abc.abstractmethod
    def export(self) -> dict[str, Any] | None:
        pass

    @property
    @abc.abstractmethod
    def started_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.abstractmethod
    def ended_at(self) -> str | None:
        """When the span finished execution.

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

    @property
    @abc.abstractmethod
    def tracing_api_key(self) -> str | None:
        """The API key to use when exporting this span."""
        pass

trace_id abstractmethod property

trace_id: str

此跨度所属的跟踪的 ID。

返回值

名称 类型 描述
str str

父跟踪的唯一标识符。

span_id abstractmethod property

span_id: str

此跨度的唯一标识符。

返回值

名称 类型 描述
str str

跨度在其跟踪中的唯一 ID。

span_data abstractmethod property

span_data: TSpanData

此跨度的操作特定数据。

返回值

名称 类型 描述
TSpanData TSpanData

特定于此类型跨度的的数据(例如,LLM 生成数据)。

parent_id abstractmethod property

parent_id: str | None

父跨度的 ID(如果有)。

返回值

类型 描述
str | None

str | None: 父跨度的 ID,如果这是根跨度,则为 None。

error abstractmethod property

error: SpanError | None

跨度执行期间发生的任何错误。

返回值

类型 描述
SpanError | None

SpanError | None: 如果发生错误,则为错误详细信息,否则为 None。

started_at abstractmethod property

started_at: str | None

跨度开始执行的时间。

返回值

类型 描述
str | None

str | None: 跨度开始的 ISO 格式时间戳,如果尚未开始,则为 None。

ended_at abstractmethod property

ended_at: str | None

跨度完成执行的时间。

返回值

类型 描述
str | None

str | None: 跨度结束的 ISO 格式时间戳,如果尚未完成,则为 None。

tracing_api_key abstractmethod property

tracing_api_key: str | None

导出此跨度时使用的 API 密钥。

start abstractmethod

start(mark_as_current: bool = False)

启动跨度。

参数

名称 类型 描述 默认
mark_as_current bool

如果为 True,则将跨度标记为当前跨度。

False
源代码在 src/agents/tracing/spans.py
@abc.abstractmethod
def start(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

finish abstractmethod

finish(reset_current: bool = False) -> None

完成跨度。

参数

名称 类型 描述 默认
reset_current bool

如果为 True,则将跨度重置为当前跨度。

False
源代码在 src/agents/tracing/spans.py
@abc.abstractmethod
def finish(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

基础: TypedDict

表示跨度执行期间发生的错误。

属性

名称 类型 描述
message str

人类可读的错误描述

data dict[str, Any] | None

可选字典,包含其他错误上下文

源代码在 src/agents/tracing/spans.py
class SpanError(TypedDict):
    """Represents an error that occurred during span execution.

    Attributes:
        message: A human-readable error description
        data: Optional dictionary containing additional error context
    """

    message: str
    data: dict[str, Any] | None

Trace

基础: ABC

一个完整的端到端工作流,包含相关的跨度和元数据。

跟踪表示一个逻辑工作流或操作(例如,“客户服务查询”或“代码生成”),并包含在该工作流期间发生的所有跨度(单个操作)。

示例
# 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)
注意事项
  • 使用描述性工作流名称
  • 使用一致的 group_ids 对相关跟踪进行分组
  • 添加相关的元数据以进行筛选/分析
  • 使用上下文管理器以确保可靠的清理
  • 在添加跟踪数据时考虑隐私
源代码在 src/agents/tracing/traces.py
class Trace(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.abstractmethod
    def __enter__(self) -> Trace:
        pass

    @abc.abstractmethod
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    @abc.abstractmethod
    def start(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.abstractmethod
    def finish(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.abstractmethod
    def trace_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.abstractmethod
    def name(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.abstractmethod
    def export(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

    @property
    @abc.abstractmethod
    def tracing_api_key(self) -> str | None:
        """The API key to use when exporting this trace and its spans."""
        pass

trace_id abstractmethod property

trace_id: str

获取此跟踪的唯一标识符。

返回值

名称 类型 描述
str str

跟踪的唯一 ID,格式为 'trace_<32_alphanumeric>'

注意事项
  • ID 在全局范围内是唯一的
  • 用于将跨度链接到其父跟踪
  • 可用于在仪表板中查找跟踪

name abstractmethod property

name: str

获取此工作流跟踪的人类可读名称。

返回值

名称 类型 描述
str str

工作流名称(例如,“客户服务”、“数据处理”)

注意事项
  • 应具有描述性和意义
  • 用于仪表板中的分组和筛选
  • 有助于识别跟踪的目的

tracing_api_key abstractmethod property

tracing_api_key: str | None

导出此跟踪及其跨度时使用的 API 密钥。

start abstractmethod

start(mark_as_current: bool = False)

启动跟踪并可以选择将其标记为当前跟踪。

参数

名称 类型 描述 默认
mark_as_current bool

如果为 True,则将此跟踪标记为执行上下文中的当前跟踪。

False
注意事项
  • 必须在添加任何跨度之前调用
  • 一次只能有一个跟踪是当前的
  • 使用 mark_as_current 时线程安全
源代码在 src/agents/tracing/traces.py
@abc.abstractmethod
def start(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

finish abstractmethod

finish(reset_current: bool = False)

完成跟踪并可以选择重置当前跟踪。

参数

名称 类型 描述 默认
reset_current bool

如果为 True,则将当前跟踪重置为执行上下文中之前的跟踪。

False
注意事项
  • 必须调用以完成跟踪
  • 完成所有打开的跨度
  • 使用 reset_current 时线程安全
源代码在 src/agents/tracing/traces.py
@abc.abstractmethod
def finish(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

export abstractmethod

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

将跟踪数据导出为可序列化的字典。

返回值

类型 描述
dict[str, Any] | None

dict | None: 包含跟踪数据的字典,如果禁用跟踪,则为 None。

注意事项
  • 包括所有跨度及其数据
  • 用于将跟踪发送到后端
  • 可能包括元数据和组 ID
源代码在 src/agents/tracing/traces.py
@abc.abstractmethod
def export(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]

创建一个代理跨度。跨度不会自动启动,您应该使用 with agent_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
name str

代理的名称。

required
handoffs list[str] | None

可选的代理名称列表,该代理可以将控制权交接给这些代理。

None
工具 list[str] | None

可选的此代理可用的工具名称列表。

None
output_type str | None

可选的代理生成的输出类型名称。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[AgentSpanData]

新创建的 agent span。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的自定义 span,你可以向其添加自己的元数据。该 span 不会自动启动,你应该使用 with custom_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
name str

自定义 span 的名称。

required
data dict[str, Any] | None

与 span 关联的任意结构化数据。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[CustomSpanData]

新创建的自定义 span。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_trace_provider().create_span(
        span_data=CustomSpanData(name=name, data=data or {}),
        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]

创建一个新的函数 span。该 span 不会自动启动,你应该使用 with function_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
name str

函数的名称。

required
input str | None

函数的输入。

None
output str | None

函数的输出。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[FunctionSpanData]

新创建的函数跨度。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的生成 span。该 span 不会自动启动,你应该使用 with generation_span() ... 或手动调用 span.start() + span.finish()

此 span 捕获模型生成细节,包括输入消息序列、任何生成的输出、模型名称和配置以及使用数据。如果你只需要捕获模型响应标识符,请使用 response_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

包含使用信息的字典(输入 token、输出 token 等)。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[GenerationSpanData]

新创建的生成 span。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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

返回当前活动的 span(如果存在)。

源文件在 src/agents/tracing/create.py
def get_current_span() -> Span[Any] | None:
    """Returns the currently active span, if present."""
    return get_trace_provider().get_current_span()

get_current_trace

get_current_trace() -> Trace | None

返回当前活动的 trace(如果存在)。

源文件在 src/agents/tracing/create.py
def get_current_trace() -> Trace | None:
    """Returns the currently active trace, if present."""
    return get_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]

创建一个新的 guardrail span。该 span 不会自动启动,你应该使用 with guardrail_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
name str

防护栏的名称。

required
triggered bool

guardrail 是否被触发。

False
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False
源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的 handoff span。该 span 不会自动启动,你应该使用 with handoff_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
来自 Agent str | None

移交的 agent 的名称。

None
前往 Agent str | None

接收移交的 agent 的名称。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[HandoffSpanData]

新创建的 handoff span。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的 MCP list tools span。该 span 不会自动启动,你应该使用 with mcp_tools_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
server str | None

MCP 服务器的名称。

None
result list[str] | None

MCP list tools 调用结果。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False
源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的 response span。该 span 不会自动启动,你应该使用 with response_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
response Response | None

OpenAI Response 对象。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False
源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的 speech group span。该 span 不会自动启动,你应该使用 with speech_group_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
input str | None

用于语音请求的输入文本。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False
源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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]

创建一个新的 speech span。该 span 不会自动启动,你应该使用 with speech_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
model str | None

用于文本到语音的模型名称。

None
input str | None

文本到语音的文本输入。

None
output str | None

文本到语音的音频输出,为 PCM 音频字节的 base64 编码字符串。

None
output_format str | None

音频输出的格式(默认为 "pcm")。

'pcm'
model_config Mapping[str, Any] | None

使用的模型配置(超参数)。

None
first_content_at str | None

音频输出的第一个字节的时间。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False
源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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,
    tracing: TracingConfig | None = None,
    disabled: bool = False,
) -> Trace

创建一个新的 trace。该 trace 不会自动启动;你应该使用它作为上下文管理器 (with trace(...):) 或手动调用 trace.start() + trace.finish()

除了工作流名称和可选的分组标识符之外,你还可以提供一个任意的元数据字典来附加额外的用户定义信息到 trace。

参数

名称 类型 描述 默认
workflow_name str

逻辑应用程序或工作流的名称。例如,你可能为编码 agent 提供 "code_bot",或为客户支持 agent 提供 "customer_support_agent"。

required
trace_id str | None

trace 的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_trace_id() 生成 trace ID,以保证 ID 正确格式化。

None
group_id str | None

可选的分组标识符,用于链接来自同一对话或过程的多个 trace。例如,你可能使用聊天线程 ID。

None
metadata dict[str, Any] | None

可选的附加元数据字典,用于附加到 trace。

None
追踪 TracingConfig | None

用于导出此 trace 的可选 tracing 配置。

None
disabled bool

如果为 True,我们将返回一个 Trace,但该 Trace 不会被记录。

False

返回值

类型 描述
Trace

新创建的 trace 对象。

源文件在 src/agents/tracing/create.py
def trace(
    workflow_name: str,
    trace_id: str | None = None,
    group_id: str | None = None,
    metadata: dict[str, Any] | None = None,
    tracing: TracingConfig | 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.
        tracing: Optional tracing configuration for exporting this 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()
    if current_trace:
        logger.warning(
            "Trace already exists. Creating a new trace, but this is probably a mistake."
        )

    return get_trace_provider().create_trace(
        name=workflow_name,
        trace_id=trace_id,
        group_id=group_id,
        metadata=metadata,
        tracing=tracing,
        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]

创建一个新的 transcription span。该 span 不会自动启动,你应该使用 with transcription_span() ... 或手动调用 span.start() + span.finish()

参数

名称 类型 描述 默认
model str | None

用于语音到文本的模型名称。

None
input str | None

语音到文本转录的音频输入,为音频字节的 base64 编码字符串。

None
input_format str | None

音频输入的格式(默认为 "pcm")。

'pcm'
output str | None

语音到文本转录的输出。

None
model_config Mapping[str, Any] | None

使用的模型配置(超参数)。

None
span_id str | None

跨度的 ID。可选。如果未提供,我们将生成一个 ID。我们建议使用 util.gen_span_id() 生成跨度 ID,以确保 ID 正确格式化。

None
parent Trace | Span[Any] | None

父跨度或跟踪。如果未提供,我们将自动使用当前跟踪/跨度作为父级。

None
disabled bool

如果为 True,我们将返回一个 Span,但该 Span 将不会被记录。

False

返回值

类型 描述
Span[TranscriptionSpanData]

新创建的语音到文本 span。

源文件在 src/agents/tracing/create.py
def 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 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.
    """
    return get_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

获取 tracing 工具使用的全局 trace 提供程序。

源文件在 src/agents/tracing/setup.py
def get_trace_provider() -> TraceProvider:
    """Get the global trace provider used by tracing utilities."""
    if GLOBAL_TRACE_PROVIDER is None:
        raise RuntimeError("Trace provider not set")
    return GLOBAL_TRACE_PROVIDER

set_trace_provider

set_trace_provider(provider: TraceProvider) -> None

设置 tracing 工具使用的全局 trace 提供程序。

源文件在 src/agents/tracing/setup.py
def set_trace_provider(provider: TraceProvider) -> None:
    """Set the global trace provider used by tracing utilities."""
    global GLOBAL_TRACE_PROVIDER
    GLOBAL_TRACE_PROVIDER = provider

gen_span_id

gen_span_id() -> str

生成一个新的跨度 ID。

源文件在 src/agents/tracing/util.py
def gen_span_id() -> str:
    """Generate a new span ID."""
    return get_trace_provider().gen_span_id()

gen_trace_id

gen_trace_id() -> str

生成一个新的追踪 ID。

源文件在 src/agents/tracing/util.py
def gen_trace_id() -> str:
    """Generate a new trace ID."""
    return get_trace_provider().gen_trace_id()

add_trace_processor

add_trace_processor(
    span_processor: TracingProcessor,
) -> None

添加一个新的 trace 处理器。该处理器将接收所有 trace/span。

源文件在 src/agents/tracing/__init__.py
def add_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

设置 trace 处理器列表。这将替换当前的处理器列表。

源文件在 src/agents/tracing/__init__.py
def set_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

设置是否全局禁用 tracing。

源文件在 src/agents/tracing/__init__.py
def set_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

设置后端导出器的 OpenAI API 密钥。

源文件在 src/agents/tracing/__init__.py
def set_tracing_export_api_key(api_key: str) -> None:
    """
    Set the OpenAI API key for the backend exporter.
    """
    default_exporter().set_api_key(api_key)