Skip to main content
当您全局设置了环境变量 LANGSMITH_TRACING=true 时,追踪数据会自动发送到 LangSmith。本指南将向您展示如何为特定请求选择性地禁用或自定义追踪。 tracing_context 上下文管理器(Python)和 tracingEnabled 选项(TypeScript)允许您在运行时覆盖全局追踪设置,无需重构代码或更改环境变量。 当您需要以下情况时,请使用条件追踪:
  • 遵守数据保留策略:某些客户可能出于合规或隐私原因要求零数据保留。
  • 处理敏感操作:对涉及个人身份信息(PII)、凭证或机密数据的操作禁用追踪。
  • 实现每租户配置:根据客户将追踪路由到不同项目或应用不同设置。
  • 控制成本:对低价值请求禁用追踪,同时保持对关键操作的可见性。
  • 支持功能标志:仅在特定功能或实验性代码路径激活时启用追踪。
以下部分提供了特定语言的示例,您可以根据应用逻辑和业务需求进行调整。

追踪上下文的工作原理

当您使用 tracing_context 上下文管理器时,它会覆盖其作用域内执行代码的全局追踪配置。这意味着您可以保持全局自动追踪启用,同时选择性地控制特定函数调用的追踪行为。有三个优先级的控制级别:
  1. tracing_context(enabled=...):最高优先级(用于作用域追踪控制的上下文管理器)。
  2. ls.configure(enabled=...):全局配置(设置全局追踪行为)。
  3. 环境变量:最低优先级(LANGSMITH_TRACING)。

为特定调用禁用追踪

要为特定操作禁用追踪,请将其包装在 enabled=Falsetracing_context 中:
import langsmith as ls
from langsmith import traceable

# LANGSMITH_TRACING=true is set globally

@traceable
def my_function(input_text: str):
    return process(input_text)

# Default invocation - is traced
result = my_function("regular data")

# Disable tracing for sensitive data
with ls.tracing_context(enabled=False):
    result = my_function("sensitive data")  # not traced
此模式适用于您知道特定数据不应被记录的一次性情况。

根据业务逻辑启用条件追踪

您可以根据运行时条件(如客户端设置或请求属性)动态启用或禁用追踪。
import langsmith as ls
from langsmith import traceable

@traceable
def my_function(input_text: str):
    return process(input_text)

def client_requires_zero_retention(client_id: str) -> bool:
    """
    Check if a client has a zero-retention policy.

    In production, this would query a database, configuration service,
    or feature flag system. Consider caching results for performance.
    """
    # Example: Query from database or config
    zero_retention_clients = get_zero_retention_clients()  # Your implementation
    return client_id in zero_retention_clients

def handle_request(client_id: str, user_input: str):
    """
    Process a request with conditional tracing based on client requirements.
    """
    should_disable = client_requires_zero_retention(client_id)

    with ls.tracing_context(enabled=not should_disable):
        return my_function(user_input)

# Example usage
handle_request("client-a", "some input")  # Traced or not based on client settings

根据请求自定义追踪配置

您还可以动态自定义追踪设置,例如将追踪路由到不同项目或添加特定于请求的元数据。
import langsmith as ls
from langsmith import traceable

@traceable
def my_function(input_text: str):
    return process(input_text)

def handle_request(client_id: str, user_input: str, region: str):
    """
    Route traces to client-specific projects with custom metadata.
    """
    client_tier = get_client_tier(client_id)  # e.g., "enterprise", "standard"

    with ls.tracing_context(
        enabled=True,
        project_name=f"client-{client_id}",
        tags=["production", f"tier-{client_tier}", f"region-{region}"],
        metadata={
            "client_id": client_id,
            "region": region,
            "tier": client_tier
        }
    ):
        return my_function(user_input)

# Traces go to "client-abc" project with custom tags and metadata
handle_request("abc", "some input", "us-west")
此模式适用于:
  • 多租户应用程序:在单独的项目中按客户隔离追踪
  • 区域部署:按地理区域跟踪性能和行为
  • 功能分支:将实验性功能追踪路由到专用项目
  • 用户细分:按用户层级、群组或 A/B 测试组分析行为

与自动追踪配合使用

tracing_context 上下文管理器与自动追踪配合工作。您可以保持 LANGSMITH_TRACING=true 全局设置,并使用 tracing_context 为特定请求覆盖设置:
import os
import langsmith as ls

# Global environment variable set
os.environ["LANGSMITH_TRACING"] = "true"

@ls.traceable
def process_data(data: str):
    return data.upper()

# Automatically traced (respects LANGSMITH_TRACING)
process_data("hello")

# Override global setting - disable for this call
with ls.tracing_context(enabled=False):
    process_data("sensitive")  # not traced

# Override global setting - enable with custom config
with ls.tracing_context(
    enabled=True,
    project_name="special-project"
):
    process_data("important")  # Traced to "special-project"

嵌套追踪上下文

当您嵌套 tracing_context 块时,最内层的上下文优先。
Python
import langsmith as ls

@ls.traceable
def inner_function(data: str):
    return data

@ls.traceable
def outer_function(data: str):
    # This call respects the inner context
    return inner_function(data)

# Outer context disables tracing
with ls.tracing_context(enabled=False):
    # But inner context re-enables it
    with ls.tracing_context(enabled=True):
        outer_function("data")  # is traced
当您想在通常不追踪的部分中临时启用追踪进行调试时,这会很有用。

在部署的代理中自定义追踪

在 LangSmith 部署的 Agent Server 中,追踪默认启用。使用工厂函数时,您可以将生成的图包装在 tracing_context 中,以按执行控制追踪。这对于添加自定义元数据、完全禁用追踪或根据经过身份验证的用户自定义追踪非常有用。

为图禁用追踪

import contextlib
import langsmith as ls
from langgraph_sdk.runtime import ServerRuntime


@contextlib.asynccontextmanager
async def make_graph(runtime: ServerRuntime):
    graph = build_my_graph()

    # You can use tracing_context to dynamically enable/disable tracing,
    # set metadata or tags, override the tracing project, etc.
    with ls.tracing_context(enabled=False, metadata={"foo": "bar"}):
        yield graph

按用户追踪

import contextlib
import langsmith as ls
from langgraph_sdk.runtime import ServerRuntime

def get_project_for_user(user_id: str) -> str | None:
    ...
    return "my-project"

graph = build_my_graph()

@contextlib.asynccontextmanager
async def make_graph(runtime: ServerRuntime):
    user = runtime.user
    # Route traces to a different project depending on user or disable tracing entirely
    project_name = get_project_for_user(user.identity)

    if project_name is None:
        with ls.tracing_context(enabled=False):
            yield graph
    else:
        with ls.tracing_context(
            enabled=True,
            project_name=project_name,
            metadata={"user_id": user.identity, "foo": "bar"},
        ):
            yield graph

可复用的追踪包装器

创建一个装饰器来自动应用条件追踪逻辑。
Python
import functools
import langsmith as ls
from langsmith import traceable

def conditional_trace(check_function):
    """
    Decorator that conditionally traces based on a check function.

    Args:
        check_function: Function that returns True if tracing should be enabled
    """
    def decorator(func):
        traced_func = traceable(func)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            should_trace = check_function(*args, **kwargs)
            with ls.tracing_context(enabled=should_trace):
                return traced_func(*args, **kwargs)
        return wrapper
    return decorator

# Usage
def should_trace_client(client_id: str, *args, **kwargs) -> bool:
    return not client_requires_zero_retention(client_id)

@conditional_trace(should_trace_client)
def process_request(client_id: str, data: str):
    return data.upper()

# Automatically applies conditional tracing based on client_id
process_request("client-a", "some data")

与采样的比较

条件追踪和采样服务于不同的目的:
特性条件追踪采样
控制确定性(显式启用/禁用)概率性(随机采样)
用例业务逻辑、合规性、按请求决策成本优化、高容量可观测性
可预测性特定请求的保证行为流量的统计表示
配置运行时代码逻辑环境变量或客户端配置
您可以结合两种方法以实现细粒度控制。

相关内容