跳至内容

追踪模块

TracingProcessor

基类: ABC

处理跨度的接口。

Source code in src/agents/tracing/processor_interface.py
class TracingProcessor(abc.ABC):
    """Interface for processing spans."""

    @abc.abstractmethod
    def on_trace_start(self, trace: "Trace") -> None:
        """Called when a trace is started.

        Args:
            trace: The trace that started.
        """
        pass

    @abc.abstractmethod
    def on_trace_end(self, trace: "Trace") -> None:
        """Called when a trace is finished.

        Args:
            trace: The trace that started.
        """
        pass

    @abc.abstractmethod
    def on_span_start(self, span: "Span[Any]") -> None:
        """Called when a span is started.

        Args:
            span: The span that started.
        """
        pass

    @abc.abstractmethod
    def on_span_end(self, span: "Span[Any]") -> None:
        """Called when a span is finished. Should not block or raise exceptions.

        Args:
            span: The span that finished.
        """
        pass

    @abc.abstractmethod
    def shutdown(self) -> None:
        """Called when the application stops."""
        pass

    @abc.abstractmethod
    def force_flush(self) -> None:
        """Forces an immediate flush of all queued spans/traces."""
        pass

跟踪开始 abstractmethod

on_trace_start(trace: Trace) -> None

在跟踪开始时调用。

参数:

名称 类型 描述 默认值
trace Trace

启动的追踪记录。

required
Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_trace_start(self, trace: "Trace") -> None:
    """Called when a trace is started.

    Args:
        trace: The trace that started.
    """
    pass

on_trace_end abstractmethod

on_trace_end(trace: Trace) -> None

当跟踪完成时调用。

参数:

名称 类型 描述 默认值
trace Trace

开始的追踪。

required
Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_trace_end(self, trace: "Trace") -> None:
    """Called when a trace is finished.

    Args:
        trace: The trace that started.
    """
    pass

on_span_start abstractmethod

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

当开始一个span时调用。

参数:

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

开始的跨度。

required
Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_span_start(self, span: "Span[Any]") -> None:
    """Called when a span is started.

    Args:
        span: The span that started.
    """
    pass

on_span_end abstractmethod

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

当某个span完成时调用。不应阻塞或引发异常。

参数:

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

已完成的跨度。

required
Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def on_span_end(self, span: "Span[Any]") -> None:
    """Called when a span is finished. Should not block or raise exceptions.

    Args:
        span: The span that finished.
    """
    pass

关机 abstractmethod

shutdown() -> None

当应用程序停止时调用。

Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def shutdown(self) -> None:
    """Called when the application stops."""
    pass

force_flush abstractmethod

force_flush() -> None

强制立即刷新所有排队的跨度/追踪数据。

Source code in src/agents/tracing/processor_interface.py
@abc.abstractmethod
def force_flush(self) -> None:
    """Forces an immediate flush of all queued spans/traces."""
    pass

Span

基类: ABC, Generic[TSpanData]

Source code in src/agents/tracing/spans.py
class Span(abc.ABC, Generic[TSpanData]):
    @property
    @abc.abstractmethod
    def trace_id(self) -> str:
        pass

    @property
    @abc.abstractmethod
    def span_id(self) -> str:
        pass

    @property
    @abc.abstractmethod
    def span_data(self) -> TSpanData:
        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:
        pass

    @abc.abstractmethod
    def set_error(self, error: SpanError) -> None:
        pass

    @property
    @abc.abstractmethod
    def error(self) -> SpanError | None:
        pass

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

    @property
    @abc.abstractmethod
    def started_at(self) -> str | None:
        pass

    @property
    @abc.abstractmethod
    def ended_at(self) -> str | None:
        pass

开始 abstractmethod

start(mark_as_current: bool = False)

开始跨度。

参数:

名称 类型 描述 默认值
mark_as_current bool

如果为true,该span将被标记为当前span。

False
Source code in 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

完成 abstractmethod

finish(reset_current: bool = False) -> None

完成这个span。

参数:

名称 类型 描述 默认值
reset_current bool

如果为true,该span将被重置为当前span。

False
Source code in 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

追踪

追踪(trace)是追踪功能创建的根级对象。它代表一个逻辑上的"工作流程"。

Source code in src/agents/tracing/traces.py
class Trace:
    """
    A trace is the root level object that tracing creates. It represents a logical "workflow".
    """

    @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.

        Args:
            mark_as_current: If true, the trace will be marked as the current trace.
        """
        pass

    @abc.abstractmethod
    def finish(self, reset_current: bool = False):
        """
        Finish the trace.

        Args:
            reset_current: If true, the trace will be reset as the current trace.
        """
        pass

    @property
    @abc.abstractmethod
    def trace_id(self) -> str:
        """
        The trace ID.
        """
        pass

    @property
    @abc.abstractmethod
    def name(self) -> str:
        """
        The name of the workflow being traced.
        """
        pass

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

追踪ID abstractmethod property

trace_id: str

追踪ID。

名称 abstractmethod property

name: str

正在追踪的工作流名称。

开始 abstractmethod

start(mark_as_current: bool = False)

开始追踪。

参数:

名称 类型 描述 默认值
mark_as_current bool

如果为true,该追踪将被标记为当前追踪。

False
Source code in src/agents/tracing/traces.py
@abc.abstractmethod
def start(self, mark_as_current: bool = False):
    """
    Start the trace.

    Args:
        mark_as_current: If true, the trace will be marked as the current trace.
    """
    pass

完成 abstractmethod

finish(reset_current: bool = False)

完成追踪。

参数:

名称 类型 描述 默认值
reset_current bool

如果为true,跟踪将被重置为当前跟踪。

False
Source code in src/agents/tracing/traces.py
@abc.abstractmethod
def finish(self, reset_current: bool = False):
    """
    Finish the trace.

    Args:
        reset_current: If true, the trace will be reset as the current trace.
    """
    pass

导出 abstractmethod

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

将跟踪记录导出为字典。

Source code in src/agents/tracing/traces.py
@abc.abstractmethod
def export(self) -> dict[str, Any] | None:
    """
    Export the trace as a dictionary.
    """
    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
tools 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]

新创建的代理范围。

Source code in 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 GLOBAL_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(
    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),您可以向其添加自己的元数据。该跨度不会自动启动,您应该使用with custom_span() ...语法或手动调用span.start() + span.finish()

参数:

名称 类型 描述 默认值
name str

自定义跨度的名称。

required
data dict[str, Any] | None

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

None
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False

返回值:

类型 描述
Span[CustomSpanData]

新创建的自定义跨度。

Source code in 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 GLOBAL_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]

创建一个新的函数跨度。该跨度不会自动启动,您应该执行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]

新创建的函数范围。

Source code in 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 GLOBAL_TRACE_PROVIDER.create_span(
        span_data=FunctionSpanData(name=name, input=input, output=output),
        span_id=span_id,
        parent=parent,
        disabled=disabled,
    )

生成范围

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]

创建一个新的生成跨度。该跨度不会自动启动,您应该使用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

一个包含使用信息的字典(输入令牌数、输出令牌数等)。

None
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False

返回值:

类型 描述
Span[GenerationSpanData]

新创建的生成跨度。

Source code in 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 GLOBAL_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(如果存在)。

Source code in src/agents/tracing/create.py
def get_current_span() -> Span[Any] | None:
    """Returns the currently active span, if present."""
    return GLOBAL_TRACE_PROVIDER.get_current_span()

get_current_trace

get_current_trace() -> Trace | None

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

Source code in src/agents/tracing/create.py
def get_current_trace() -> Trace | None:
    """Returns the currently active trace, if present."""
    return GLOBAL_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]

创建一个新的防护栏跨度。该跨度不会自动启动,您应该使用with guardrail_span() ...或手动调用span.start() + span.finish()

参数:

名称 类型 描述 默认值
name str

防护栏的名称。

required
triggered bool

护栏是否被触发。

False
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False
Source code in 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 GLOBAL_TRACE_PROVIDER.create_span(
        span_data=GuardrailSpanData(name=name, triggered=triggered),
        span_id=span_id,
        parent=parent,
        disabled=disabled,
    )

交接范围

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]

创建一个新的交接跨度。该跨度不会自动启动,您应该执行 with handoff_span() ... 或手动调用 span.start() + span.finish()

参数:

名称 类型 描述 默认值
from_agent str | None

正在交接的代理名称。

None
to_agent str | None

接收交接的代理名称。

None
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False

返回值:

类型 描述
Span[HandoffSpanData]

新创建的交接跨度。

Source code in 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 GLOBAL_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列表工具span。该span不会自动启动,您应该使用with mcp_tools_span() ...语法或手动调用span.start() + span.finish()

参数:

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

MCP服务器的名称。

None
result list[str] | None

MCP列表工具调用的结果。

None
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False
Source code in 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 GLOBAL_TRACE_PROVIDER.create_span(
        span_data=MCPListToolsSpanData(server=server, result=result),
        span_id=span_id,
        parent=parent,
        disabled=disabled,
    )

响应范围

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

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

参数:

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

OpenAI响应对象。

None
span_id str | None

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

None
parent Trace | Span[Any] | None

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False
Source code in 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 GLOBAL_TRACE_PROVIDER.create_span(
        span_data=ResponseSpanData(response=response),
        span_id=span_id,
        parent=parent,
        disabled=disabled,
    )

语音组_span

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

创建一个新的语音组跨度。该跨度不会自动启动,您应该执行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

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False
Source code in 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 GLOBAL_TRACE_PROVIDER.create_span(
        span_data=SpeechGroupSpanData(input=input),
        span_id=span_id,
        parent=parent,
        disabled=disabled,
    )

语音片段

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]

创建一个新的语音片段。该片段不会自动开始,您应该使用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

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False
Source code in 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 GLOBAL_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(
    workflow_name: str,
    trace_id: str | None = None,
    group_id: str | None = None,
    metadata: dict[str, Any] | None = None,
    disabled: bool = False,
) -> Trace

创建一个新的跟踪。跟踪不会自动启动;您应该将其用作上下文管理器(with trace(...):)或手动调用trace.start() + trace.finish()

除了工作流名称和可选的分组标识符外,您还可以提供一个任意的元数据字典,用于将额外的用户定义信息附加到跟踪记录中。

参数:

名称 类型 描述 默认值
workflow_name str

逻辑应用或工作流的名称。例如,对于编码代理可以提供"code_bot",对于客户支持代理可以提供"customer_support_agent"。

required
trace_id str | None

追踪ID。可选参数。如果未提供,我们将生成一个ID。建议使用util.gen_trace_id()来生成追踪ID,以确保ID格式正确。

None
group_id str | None

可选的分组标识符,用于关联来自同一对话或进程的多个跟踪记录。例如,您可以使用聊天线程ID。

None
metadata dict[str, Any] | None

可选的附加元数据字典,用于附加到跟踪记录中。

None
disabled bool

如果为True,我们将返回一个Trace但不会记录该Trace。如果已存在trace且even_if_trace_running为True时,此设置将不会被检查。

False

返回值:

类型 描述
Trace

新创建的跟踪对象。

Source code in 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,
    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. This will
            not be checked if there's an existing trace and `even_if_trace_running` is True.

    Returns:
        The newly created trace object.
    """
    current_trace = GLOBAL_TRACE_PROVIDER.get_current_trace()
    if current_trace:
        logger.warning(
            "Trace already exists. Creating a new trace, but this is probably a mistake."
        )

    return GLOBAL_TRACE_PROVIDER.create_trace(
        name=workflow_name,
        trace_id=trace_id,
        group_id=group_id,
        metadata=metadata,
        disabled=disabled,
    )

转录片段

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]

创建一个新的转录片段。该片段不会自动启动,您应该使用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

父级span或trace。如果未提供,我们将自动使用当前的trace/span作为父级。

None
disabled bool

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

False

返回值:

类型 描述
Span[TranscriptionSpanData]

新创建的语音转文本范围。

Source code in 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 GLOBAL_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,
    )

gen_span_id

gen_span_id() -> str

生成一个新的跨度ID。

Source code in src/agents/tracing/util.py
def gen_span_id() -> str:
    """Generates a new span ID."""
    return f"span_{uuid.uuid4().hex[:24]}"

gen_trace_id

gen_trace_id() -> str

生成一个新的追踪ID。

Source code in src/agents/tracing/util.py
def gen_trace_id() -> str:
    """Generates a new trace ID."""
    return f"trace_{uuid.uuid4().hex}"

add_trace_processor

add_trace_processor(
    span_processor: TracingProcessor,
) -> None

添加一个新的跟踪处理器。该处理器将接收所有跟踪/跨度数据。

Source code in 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.
    """
    GLOBAL_TRACE_PROVIDER.register_processor(span_processor)

set_trace_processors

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

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

Source code in 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.
    """
    GLOBAL_TRACE_PROVIDER.set_processors(processors)

set_tracing_disabled

set_tracing_disabled(disabled: bool) -> None

设置是否全局禁用追踪。

Source code in src/agents/tracing/__init__.py
def set_tracing_disabled(disabled: bool) -> None:
    """
    Set whether tracing is globally disabled.
    """
    GLOBAL_TRACE_PROVIDER.set_disabled(disabled)

set_tracing_export_api_key

set_tracing_export_api_key(api_key: str) -> None

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

Source code in 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)