当您设置全局环境变量时 LANGSMITH_TRACING=true ,追踪将自动发送到 LangSmith。本指南向您展示如何为特定请求选择性地禁用或自定义追踪。
在以下情况下使用条件追踪:
- 遵守数据保留策略:某些客户可能因合规或隐私原因要求零数据保留。
- 处理敏感操作:为涉及个人识别信息、凭证或机密数据的操作禁用追踪。
- 实现每个租户的配置:根据客户将追踪路由到不同项目或应用不同设置。
- 控制成本:为低价值请求禁用追踪,同时保持对关键操作的可视性。
- 支持功能开关:仅在特定功能或实验性代码路径激活时启用追踪。
@[tracing_context][tracing_] 上下文管理器 (Python) 和 tracingEnabled 选项 (TypeScript) 允许您在运行时覆盖全局追踪设置,而无需重构代码或更改环境变量。
Python
追踪上下文的工作原理
当您使用 @[tracing_context][tracing_] 上下文管理器时,它会覆盖在其作用域内执行的代码的全局追踪配置。这意味着您可以保持全局启用自动追踪,同时为特定函数调用选择性地控制追踪行为。
控制有三个优先级:
- **
tracing_context(enabled=...)**:最高优先级(用于作用域追踪控制的上下文管理器)。 - **
ls.configure(enabled=...)**:全局配置(设置全局追踪行为)。 - **环境变量**:最低优先级(
LANGSMITH_TRACING).
为特定调用禁用追踪
要为特定操作禁用追踪,请将其包装在 tracing_context with enabled=False:
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
此模式适用于您知道特定数据不应被记录的一次性情况。
基于业务逻辑启用条件追踪
您可以根据运行时条件动态启用或禁用追踪,例如客户端设置或请求属性。
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
按请求自定义追踪配置
您还可以动态自定义追踪设置,例如将追踪路由到不同项目或添加请求特定的元数据。
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")
此模式适用于:
- 多租户应用程序:按客户在单独的项目中隔离追踪
- 区域部署:按地理区域跟踪性能和行为
- 功能分支:将实验性功能跟踪路由到专用项目
- 用户细分: Analyze behavior by user tier, cohort, or A/B test group
使用自动跟踪
The tracing_context 上下文管理器与自动跟踪配合使用。您可以保持 LANGSMITH_TRACING=true 全局设置并使用 tracing_context 来覆盖特定请求的设置:
# 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 块时,最内层的上下文优先。
@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=...),后者对客户端发送的每条跟踪应用相同的编辑。
要按请求进行编辑,请使用 tracing_context 配合 replicas 参数,并传递一个 updates 字典来覆盖 inputs 和 outputs 在已记录的运行上。由于 tracing_context 的作用域限定在当前执行上下文中,具有不同编辑策略的并发请求不会产生冲突。
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": {}} 仅编辑输出)。相同的模式也适用于将不同的编辑策略路由到不同的目的地——每个副本可以指定自己的 project_name, api_key和 updates。请参阅 使用副本将跟踪写入多个目的地 以获取完整的副本参考。
自定义已部署代理中的跟踪
LangSmith 部署中的 代理服务器中默认启用跟踪。使用 工厂函数时,您可以用 tracing_context 包装生成的图来控制每次执行的跟踪。这对于添加自定义元数据、完全禁用跟踪或根据经过身份验证的用户自定义跟踪很有用。
禁用图的跟踪
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
按用户跟踪
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
可重用的跟踪包装器
创建一个装饰器来自动应用条件追踪逻辑。
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")
TypeScript
追踪启用如何工作
在 TypeScript 中,您可以使用 tracingEnabled 参数在调用 traceable() 时控制按函数的追踪。这允许您在函数级别选择性地启用或禁用追踪。
一个按函数控制追踪的两级系统:
- **
tracingEnabled参数**:最高优先级(传递给traceable()配置)。 - **环境变量**:最低优先级(
LANGSMITH_TRACING).
禁用特定调用的追踪
要禁用特定操作的追踪,请使用 tracingEnabled: false:
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 中,最高效的方法是预先创建函数的追踪和非追踪变体,然后根据业务逻辑在运行时选择它们。这避免了每次请求时创建新追踪包装器的性能开销,同时仍能精细控制追踪何时发生。例如:
// 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 选项与自动追踪无缝配合。您可以全局设置 LANGSMITH_TRACING=true 并使用 tracingEnabled 覆盖特定函数的设置。
// 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"
与采样的比较
条件追踪和 采样 服务于不同的目的:
| 功能 | 条件追踪 | 采样 |
|---|---|---|
| **控制** | Deterministic (explicit enable/disable) | Probabilistic (random sampling) |
| **用例** | 业务逻辑、合规性、按请求决策 | 成本优化、大容量可观测性 |
| **可预测性** | 特定请求的保证行为 | 流量的统计表示 |
| **配置** | 运行时代码逻辑 | 环境变量或客户端配置 |
您可以结合两种方法进行精细控制。
相关
- - 无需环境变量进行追踪:通过编程方式配置追踪,而不是使用环境变量。
- - 设置追踪采样率:通过概率采样追踪以减少数量
- - 屏蔽输入和输出:在追踪中隐藏敏感数据,而不是完全禁用追踪。
- - 向追踪添加元数据和标签:使用自定义属性对追踪进行分类和过滤。