Skip to content
LangSmith 文档版本 跟随上游 源快照 fbb8b30e 更新于 2026-10-18

条件式追踪

当你在全局设置了环境变量 LANGSMITH_TRACING=true 时,追踪会自动发送到 LangSmith。本指南介绍如何针对特定请求有选择地禁用或自定义追踪。

在以下场景中使用条件式追踪:

  • 遵守数据保留策略:某些客户出于合规或隐私原因可能要求零数据保留。
  • 处理敏感操作:对涉及 PII、凭证或机密数据的操作禁用追踪。
  • 实现按租户配置:根据客户将追踪路由到不同项目,或应用不同的设置。
  • 控制成本:对低价值请求禁用追踪,同时保留对关键操作的可见性。
  • 支持 feature flag:仅在特定功能或实验性代码路径处于启用状态时启用追踪。

TIP

若要通过只记录一定百分比的运行来减少追踪量,请参阅为追踪设置采样率。

tracing_context 上下文管理器(Python)与 tracingEnabled 选项(TypeScript)允许你在运行时覆盖全局追踪设置,而无需重构代码或修改环境变量。

NOTE

以下各节提供针对具体语言的示例,你可以根据自己的应用逻辑和业务需求进行调整。

tracing context 的工作原理

当你使用 tracing_context 上下文管理器时,它会覆盖其作用域内执行的代码的全局追踪配置。这意味着你可以在全局保持自动追踪启用,同时对特定函数调用有选择地控制追踪行为。

共有三个优先级层次:

  1. tracing_context(enabled=...):优先级最高(用于作用域级追踪控制的上下文管理器)。
  2. ls.configure(enabled=...):全局配置(设置全局追踪行为)。
  3. 环境变量:优先级最低(LANGSMITH_TRACING)。

针对特定调用禁用追踪

若要针对某个特定操作禁用追踪,请将其包装在 enabled=False 的 tracing_context 中:

python
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

这种模式适用于一次性场景,即你明确知道某些特定数据不应被记录的情况。

基于业务逻辑启用条件式追踪

你可以根据运行时条件(例如客户端设置或请求属性)动态启用或禁用追踪。

python
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

按请求自定义追踪配置

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

python
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 覆盖特定请求的设置:

python
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

当你嵌套 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

当你希望在通常不被追踪的代码段中临时启用追踪以便调试时,这会很有用。

按条件脱敏输入与输出

有时你希望追踪仍被记录——从而保留运行的耗时、结构、错误和元数据——但对特定请求隐藏输入和输出(例如来自有严格隐私要求的租户的追踪)。这与完全禁用追踪不同,也与 Client(hide_inputs=...) 不同,后者会对该客户端发送的每条追踪应用相同的脱敏处理。

若要按请求脱敏,请使用带 replicas 参数的 tracing_context,并传入一个 updates 字典,覆盖所记录运行上的 inputs 和 outputs。由于 tracing_context 的作用域限定在当前执行上下文,采用不同脱敏策略的并发请求之间不会产生竞争。

python
import langsmith as ls
from langsmith import traceable

@traceable
def my_agent(user_input: str) -> str:
    return process(user_input)

def should_redact(tenant_id: str) -> bool:
    """Return True if traces for this tenant should have inputs/outputs masked."""
    return tenant_id in get_redacted_tenants()

def handle_request(tenant_id: str, user_input: str) -> str:
    replica: dict = {"project_name": "my-project"}
    if should_redact(tenant_id):
        # Recorded run will have empty inputs/outputs but full structure,
        # timing, metadata, and any errors.
        replica["updates"] = {"inputs": {}, "outputs": {}}

    with ls.tracing_context(replicas=[replica]):
        return my_agent(user_input)

你可以在 updates 中使用运行字段的任意子集(例如,{"inputs": {"redacted": True} 用于保留一个标记,或 {"outputs": {} 仅脱敏输出)。同样的模式也适用于将不同的脱敏策略路由到不同的目标位置——每个 replica 都可以指定自己的 project_name、api_key 和 updates。完整的 replica 参考请参阅使用 replicas 将追踪写入多个目标位置。

NOTE

在使用 updates 脱敏输入或输出时,务必在 replica 上设置 project_name。如果 replica 的 project_name 与当前会话的项目相同,updates 可能会被丢弃,从而发送未经脱敏的输入/输出。

在已部署的智能体中自定义追踪

在 LangSmith Deployment 的 Agent Server 中,追踪默认启用。使用工厂函数时,你可以用 tracing_context 包裹生成的图,以便按每次执行控制追踪。这对于添加自定义元数据、完全禁用追踪,或基于已认证的用户自定义追踪都非常有用。

针对图禁用追踪

python
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

按用户追踪

python
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")

与采样的对比

条件式追踪与采样的用途不同:

功能条件式追踪采样
控制方式确定性(显式启用/禁用)概率性(随机采样)
使用场景业务逻辑、合规、按请求决策成本优化、高流量的可观测性
可预测性特定请求的行为有保证流量的统计代表性
配置方式运行时代码逻辑环境变量或客户端配置

你可以结合这两种方式,以实现细粒度控制。

相关


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。