> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 条件追踪

当您全局设置了环境变量 `LANGSMITH_TRACING=true` 时，追踪数据会自动发送到 LangSmith。本指南将向您展示如何为特定请求选择性地禁用或自定义追踪。

[`tracing_context`](https://reference.langchain.com/python/langsmith/run_helpers/tracing_context) 上下文管理器（Python）和 [`tracingEnabled`](https://reference.langchain.com/javascript/classes/langsmith.run_trees.RunTree.html#tracingenabled) 选项（TypeScript）允许您在运行时覆盖全局追踪设置，无需重构代码或更改环境变量。

当您需要以下情况时，请使用条件追踪：

* **遵守数据保留策略**：某些客户可能出于合规或隐私原因要求零数据保留。
* **处理敏感操作**：对涉及个人身份信息（PII）、凭证或机密数据的操作禁用追踪。
* **实现每租户配置**：根据客户将追踪路由到不同项目或应用不同设置。
* **控制成本**：对低价值请求禁用追踪，同时保持对关键操作的可见性。
* **支持功能标志**：仅在特定功能或实验性代码路径激活时启用追踪。

<Note>
  以下部分提供了特定语言的示例，您可以根据应用逻辑和业务需求进行调整。
</Note>

<Tabs>
  <Tab title="Python" icon="brand-python">
    ## 追踪上下文的工作原理

    当您使用 [`tracing_context`](https://reference.langchain.com/python/langsmith/run_helpers/tracing_context) 上下文管理器时，它会覆盖其作用域内执行代码的全局追踪配置。这意味着您可以保持全局自动追踪启用，同时选择性地控制特定函数调用的追踪行为。

    有三个优先级的控制级别：

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

    ## 为特定调用禁用追踪

    要为特定操作禁用追踪，请将其包装在 `enabled=False` 的 `tracing_context` 中：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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`](https://reference.langchain.com/python/langsmith/run_helpers/tracing_context) 上下文管理器与自动追踪配合工作。您可以保持 `LANGSMITH_TRACING=true` 全局设置，并使用 `tracing_context` 为特定请求覆盖设置：

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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](/langsmith/agent-server) 中，追踪默认启用。使用[工厂函数](/langsmith/graph-rebuild)时，您可以将生成的图包装在 `tracing_context` 中，以按执行控制追踪。这对于添加自定义元数据、完全禁用追踪或根据经过身份验证的用户自定义追踪非常有用。

    ### 为图禁用追踪

    ```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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 Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    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")
    ```
  </Tab>

  <Tab title="TypeScript" icon="brand-javascript">
    ## 追踪启用的工作原理

    在 TypeScript 中，您在调用 [`traceable()`](https://reference.langchain.com/python/langsmith/run_helpers/traceable) 时使用 [`tracingEnabled`](https://reference.langchain.com/javascript/classes/langsmith.run_trees.RunTree.html#tracingenabled) 参数来按函数控制追踪。这允许您在函数级别选择性地启用或禁用追踪。

    一个两级系统，其中追踪按函数控制：

    1. **`tracingEnabled` 参数**：最高优先级（传递给 [`traceable()`](https://reference.langchain.com/python/langsmith/run_helpers/traceable) 配置）。
    2. **环境变量**：最低优先级（`LANGSMITH_TRACING`）。

    ## 为特定调用禁用追踪

    要为特定操作禁用追踪，请创建一个带有 `tracingEnabled: false` 的可追踪函数版本：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { traceable } from "langsmith/traceable";

    const myFunction = traceable(
        (inputText: string) => {
            return process(inputText);
        },
        { name: "my_function" }
    );

    // Default invocation - is traced
    await myFunction("regular data");

    // Disable tracing for sensitive data
    const myFunctionNoTrace = traceable(
        (inputText: string) => {
            return process(inputText);
        },
        { name: "my_function", tracingEnabled: false }
    );

    await myFunctionNoTrace("sensitive data");  // not traced
    ```

    此模式适用于您知道特定数据不应被记录的一次性情况。

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

    在许多应用程序中，您需要根据运行时条件（如客户端隐私要求、法规合规性或功能标志）动态控制追踪。

    在 TypeScript 中，最有效的方法是预先创建函数的已追踪和未追踪变体，然后在运行时根据业务逻辑在它们之间进行选择。这避免了在每个请求上创建新的追踪包装器的性能开销，同时仍然提供对追踪发生时间的细粒度控制。例如：

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { traceable } from "langsmith/traceable";

    // Define the core logic once
    function processText(inputText: string): string {
        // Your actual processing logic
        return inputText.toUpperCase();
    }

    // Create traced and non-traced variants upfront
    const myFunction = traceable(processText, { name: "my_function" });
    const myFunctionNoTrace = traceable(processText, {
        name: "my_function",
        tracingEnabled: false
    });

    function clientRequiresZeroRetention(clientId: string): boolean {
        /**
         * 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.
         */
        const zeroRetentionClients = getZeroRetentionClients();  // Your implementation
        return zeroRetentionClients.includes(clientId);
    }

    async function handleRequest(clientId: string, userInput: string) {
        /**
         * Process a request with conditional tracing based on client requirements.
         * Efficiently selects pre-created traced or non-traced variant.
         */
        const shouldDisable = clientRequiresZeroRetention(clientId);

        // Select the appropriate pre-created variant
        const fn = shouldDisable ? myFunctionNoTrace : myFunction;
        return await fn(userInput);
    }

    // Example usage
    await handleRequest("client-a", "some input");  // Traced or not based on client settings
    ```

    ## 与自动追踪配合使用

    [`tracingEnabled`](https://reference.langchain.com/javascript/classes/langsmith.run_trees.RunTree.html#tracingenabled) 选项与自动追踪无缝协作。您可以保持 `LANGSMITH_TRACING=true` 全局设置，并使用 `tracingEnabled` 为特定函数覆盖设置。

    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
    import { traceable } from "langsmith/traceable";

    // Global tracing enabled via environment
    process.env.LANGSMITH_TRACING = "true";

    const processData = traceable(
        (data: string) => {
            return data.toUpperCase();
        },
        { name: "process_data" }
    );

    // Automatically traced (respects LANGSMITH_TRACING)
    await processData("hello");

    // Override global setting - disable for this call
    const processDataNoTrace = traceable(
        (data: string) => {
            return data.toUpperCase();
        },
        { name: "process_data", tracingEnabled: false }
    );

    await processDataNoTrace("sensitive");  // not traced

    // Override global setting - enable with custom config
    const processDataCustom = traceable(
        (data: string) => {
            return data.toUpperCase();
        },
        {
            name: "process_data",
            project_name: "special-project",
            tracingEnabled: true
        }
    );

    await processDataCustom("important");  // Traced to "special-project"
    ```
  </Tab>
</Tabs>

## 与采样的比较

条件追踪和[采样](/langsmith/sample-traces)服务于不同的目的：

| 特性       | 条件追踪           | 采样           |
| -------- | -------------- | ------------ |
| **控制**   | 确定性（显式启用/禁用）   | 概率性（随机采样）    |
| **用例**   | 业务逻辑、合规性、按请求决策 | 成本优化、高容量可观测性 |
| **可预测性** | 特定请求的保证行为      | 流量的统计表示      |
| **配置**   | 运行时代码逻辑        | 环境变量或客户端配置   |

您可以结合两种方法以实现细粒度控制。

## 相关内容

* [不使用环境变量进行追踪](/langsmith/trace-without-env-vars)：以编程方式配置追踪，而不是使用环境变量。
* [为追踪设置采样率](/langsmith/sample-traces)：概率性地采样追踪以减少数据量
* [屏蔽输入和输出](/langsmith/mask-inputs-outputs)：在追踪中隐藏敏感数据，而不是完全禁用追踪。
* [向追踪添加元数据和标签](/langsmith/add-metadata-tags)：使用自定义属性对追踪进行分类和筛选。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/conditional-tracing.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
