在使用高并发应用程序时,您可能不想将每个跟踪都记录到 LangSmith。采样率允许您控制记录的跟踪百分比,帮助您平衡可观测性需求和成本考量。
设置全局采样率
本节适用于使用 LangSmith SDK 或 LangChain 的用户,不适用于直接使用 LangSmith API 记录的用户。
默认情况下,所有跟踪都记录到 LangSmith。要减少记录到 LangSmith 的跟踪数量,请将 LANGSMITH_TRACING_SAMPLING_RATE 环境变量设置为 0(无跟踪)到 1(所有跟踪)之间的任何浮点数。例如,设置以下环境变量将记录 75% 的跟踪。
export LANGSMITH_TRACING_SAMPLING_RATE=0.75
这适用于 traceable 装饰器和 RunTree 对象。
为每个客户端设置不同的采样率
您还可以在特定的 Client 实例上设置采样率,并使用 tracing_context 上下文管理器。
from langsmith import Client, tracing_context
# Create clients with different sampling rates
client_1 = Client(tracing_sampling_rate=0.5) # 50% sampling
client_2 = Client(tracing_sampling_rate=0.25) # 25% sampling
client_no_trace = Client(tracing_sampling_rate=0.0) # No tracing
# Use different sampling rates for different operations
with tracing_context(client=client_1):
# Your code here - will be traced with 50% sampling rate
agent_1.invoke(...)
with tracing_context(client=client_2):
# Your code here - will be traced with 25% sampling rate
agent_1.invoke(...)
with tracing_context(client=client_no_trace):
# Your code here - will not be traced
agent_1.invoke(...)
这允许您在操作级别控制采样率。