本指南向您展示如何使用 LangSmith 的 OpenTelemetry 跟踪来运行评估。
如果您已经使用 OpenTelemetry 来跟踪您的 LLM 应用程序,您可以通过将跟踪路由到实验会话来运行评估。这种方法在您想要评估使用 OpenTelemetry 插桩但不使用 LangSmith SDK 的 evaluate() 函数。
概述
使用 OpenTelemetry 进行评估时,您需要:
- 在 LangSmith 中创建一个实验会话。
- 配置 OpenTelemetry 将跟踪发送到 LangSmith。
- 添加特定的 span 属性以将跟踪链接到实验和数据集示例。
- 为数据集中的每个示例运行您的应用程序。
前提条件
本指南假设您具备:
- * 一个使用 OpenTelemetry 插桩并向 LangSmith 发送跟踪的应用程序。
- * 在 LangSmith 中创建了一个包含待评估示例的数据集。您可以通过以下方式创建数据集 LangSmith UI 或通过 SDK.
本教程使用 Strands agents 作为示例实现,但该方法适用于任何 OpenTelemetry 插桩。
安装依赖项:
pip install langsmith strands-agents strands-agents-tools opentelemetry-sdk opentelemetry-exporter-otlp
npm install langsmith @strands-agents/sdk @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources
设置以下环境变量:
# Tracing configuration
LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
LANGSMITH_API_KEY="<your-langsmith-api-key>"
OTEL_EXPORTER_OTLP_ENDPOINT = "https://api.smith.langchain.com/otel/"
# AWS Credentials
AWS_ACCESS_KEY_ID="<your-aws-access-key-id>"
AWS_SECRET_ACCESS_KEY="<your-aws-secret-access-key>"
AWS_REGION_NAME="<your-aws-region>"
步骤 1. 创建一个实验会话
本指南假设已在 LangSmith 中创建了包含待评估示例的数据集。您可以通过以下方式创建数据集 LangSmith UI 或通过 SDK.
实验会话将所有评估跟踪分组在一起。使用 LangSmith 客户端创建一个:
from langsmith import Client
# Initialize LangSmith client
client = Client()
experiment_name = "strands-agent-experiment"
# Assumes a dataset has been created. You can find the dataset ID in the LangSmith UI or via the SDK.
dataset_id = "<your-dataset-id>"
# Create an experiment session linked to the dataset
project = client.create_project(
project_name=experiment_name,
reference_dataset_id=dataset_id
)
experiment_id = str(project.id)
// Initialize LangSmith client
const client = new Client({
apiKey: process.env.LANGSMITH_API_KEY,
});
const experimentName = "strands-agent-experiment";
const datasetId = "your-dataset-id";
// Create an experiment session linked to the dataset
const project = await client.createProject({
projectName: experimentName,
referenceDatasetId: datasetId,
});
const experimentId = project.id;
此外,您可以在 LangSmith UI 中创建评估器并将其绑定到您的数据集。对于在 UI 中定义并绑定到您的数据集的评估器,它们将自动在实验跟踪上运行。
要了解有关评估器的更多信息,请参阅 评估器.
步骤 2. 定义应用程序并配置 OpenTelemetry
首先,您需要一个使用 OpenTelemetry 进行跟踪的应用程序。此示例使用 Strands agent,但您可以使用任何 OpenTelemetry 插桩的应用程序。通过在 OTEL headers 中包含实验 ID 来设置 OpenTelemetry 以将跟踪路由到您的实验会话。这一步的总体思路是拥有一个使用 OpenTelemetry 插桩的 agent 或应用程序。
from strands import Agent
from strands_tools import file_read, file_write, python_repl, shell, journal
from strands.telemetry import StrandsTelemetry
# Set OTEL headers with experiment ID as the project
api_key = os.getenv('LANGSMITH_API_KEY')
os.environ['OTEL_EXPORTER_OTLP_HEADERS'] = f"x-api-key={api_key},Langsmith-Project={experiment_id}"
# Initialize telemetry
strands_telemetry = StrandsTelemetry()
strands_telemetry.setup_otlp_exporter()
# Create an agent (Strands automatically creates OTel spans)
agent = Agent(
tools=[file_read, file_write, python_repl, shell, journal],
system_prompt="You are an Expert Software Developer.",
model="us.anthropic.claude-sonnet-4-20250514-v1:0",
)
有关使用 LangSmith 设置 OpenTelemetry 追踪的详细信息,请参阅 使用 OpenTelemetry 追踪.
步骤 3. 设置关键 span 属性
为每次应用运行添加必需的 span 属性。这些属性将每个追踪链接到实验和特定的数据集示例。
以下属性与实验评估相关:
| 属性 | 用途 |
|---|---|
langsmith.trace.session_id | 将追踪路由到您的实验会话 |
langsmith.reference_example_id | 将追踪链接到特定的数据集示例 |
langsmith.span.kind | 设置 span 类型(例如 "llm"、"chain"、"tool") |
inputs | 记录应用的输入 |
outputs | 记录应用的输出 |
有关支持的 OpenTelemetry 属性完整列表,请参阅 使用 OpenTelemetry 追踪.
from opentelemetry import trace
def evaluate_with_opentelemetry(agent, example_id: str, example_input: str, experiment_id: str):
tracer = trace.get_tracer(__name__)
# Wrapper span to add experiment metadata
with tracer.start_as_current_span("experiment_evaluation") as span:
# Route trace to the experiment
span.set_attribute("langsmith.trace.session_id", experiment_id)
# Link trace to the specific dataset example
span.set_attribute("langsmith.reference_example_id", example_id)
# Record input
span.set_attribute("inputs", example_input)
# Run the application
response = agent(example_input)
# Record output
output_text = getattr(response, "output", str(response))
span.set_attribute("outputs", output_text)
return output_text
async function evaluateWithAgent(
agent: Agent,
exampleId: string,
exampleInput: string,
experimentId: string
): Promise<string> {
const tracer = trace.getTracer("experiment-runner");
return await tracer.startActiveSpan(
"experiment_evaluation",
async (span: Span) => {
try {
// Route trace to the experiment
span.setAttribute("langsmith.trace.session_id", experimentId);
// Link trace to the specific dataset example
span.setAttribute("langsmith.reference_example_id", exampleId);
// Record input
span.setAttribute("inputs", exampleInput);
// Run the application
const result = await agent.invoke(exampleInput);
// Record output
const response = String(result);
span.setAttribute("outputs", response);
return response;
} finally {
span.end();
}
}
);
}
步骤 4. 通过迭代数据集示例运行评估
每次实验运行都会在 LangSmith 中创建链接到您数据集示例的追踪。
# Iterate through dataset examples
for example in client.list_examples(dataset_name=dataset_name):
# Extract input from the example inputs dictionary
# Adjust the key based on your dataset structure
# (e.g., "input", "question", etc.)
example_input = example.inputs.get("input")
evaluate_with_opentelemetry(
agent=agent,
example_id=str(example.id),
example_input=str(example_input),
experiment_id=experiment_id
)
// Iterate through dataset examples
for await (const example of client.listExamples({ datasetName })) {
// Extract input from the example inputs dictionary
// Adjust the key based on your dataset structure
// (e.g., "input", "question", etc.)
const exampleInput = example.inputs.input;
await evaluateWithAgent(
agent,
example.id,
String(exampleInput),
experimentId
);
}
运行评估后,您可以 分析实验 在 LangSmith UI 中查看:
- * 每个示例的单独追踪详情
- * 评估器评分和反馈
- * 不同实验运行之间的比较
在 LangSmith UI 中导航至您的实验以分析结果。