主题
如何使用 OpenTelemetry 进行评估
本指南展示如何使用 LangSmith 的 OpenTelemetry 追踪来运行评估。
INFO
评估 | 数据集 | 使用 OpenTelemetry 追踪
如果你已经使用 OpenTelemetry 追踪 LLM 应用,可以通过将追踪路由到实验会话来运行评估。当你想要评估已使用 OpenTelemetry 插桩但不使用 LangSmith SDK 的 evaluate() 函数的应用时,此方法很有用。
概述
使用 OpenTelemetry 进行评估时,你需要:
- 在 LangSmith 中创建实验会话。
- 配置 OpenTelemetry 将追踪发送到 LangSmith。
- 添加特定的 span 属性,将追踪链接到实验和数据集示例。
- 为数据集中的每个示例运行你的应用。
前置条件
本指南假设你具备:
- 一个使用 OpenTelemetry 插桩并将追踪发送到 LangSmith 的应用。
- 一个在 LangSmith 中创建的、包含待评估示例的数据集。你可以通过 LangSmith UI 或 SDK 创建数据集。
本教程使用 Strands agents 作为示例实现,但该方法适用于任何 OpenTelemetry 插桩。
安装依赖:
bash
pip install langsmith strands-agents strands-agents-tools opentelemetry-sdk opentelemetry-exporter-otlpbash
npm install langsmith @strands-agents/sdk @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources设置以下环境变量:
bash
# 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>"NOTE
如果你正在自托管 LangSmith,请将 OTEL_EXPORTER_OTLP_ENDPOINT 替换为你的自托管 URL 并附加 /api/v1/otel。例如:OTEL_EXPORTER_OTLP_ENDPOINT = "https://ai-company.com/api/v1/otel"。
将 LANGSMITH_ENDPOINT 替换为你的 LangSmith API 端点。例如:LANGSMITH_ENDPOINT = "https://ai-company.com/api/v1"。
步骤 1. 创建实验会话
本指南假设已在 LangSmith 中创建包含待评估示例的数据集。你可以通过 LangSmith UI 或 SDK 创建数据集。
实验会话将所有评估追踪分组在一起。使用 LangSmith 客户端创建一个:
python
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)typescript
import { Client } from "langsmith";
// 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 标头中包含实验 ID,设置 OpenTelemetry 将追踪路由到你的实验会话。此步骤的总体思路是拥有一个已使用 OpenTelemetry 插桩的 agent 或应用。
NOTE
本步骤未提供 TypeScript 示例,因为 Strands TypeScript SDK 目前不支持 OpenTelemetry 可观测性(截至 2026 年 2 月)。
python
import os
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 追踪。
python
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_texttypescript
import { trace, Span } from "@opentelemetry/api";
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 中创建链接到你的数据集示例的追踪。
python
# 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
)typescript
// 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 中导航到你的实验以分析结果。