主题
追踪 Strands Agents 应用
使用 LangSmith 追踪 Strands Agents 应用。
Strands Agents 是用于构建模型驱动智能体的 SDK。LangSmith 提供 Strands Agents 集成,可将 Strands OpenTelemetry span 以 LangSmith 兼容格式导出,包括智能体运行、模型调用、工具调用、提示词、补全和 token 使用量。
安装
安装支持 Strands Agents 的 LangSmith:
bash
pip install "langsmith[strands-agents]"bash
uv add "langsmith[strands-agents]"这会安装 LangSmith、Strands Agents、Strands Agents 工具以及 OpenTelemetry OTLP HTTP 导出器。
设置
1. 配置环境变量
设置你的 LangSmith API key 和项目名称。如果你使用 Amazon Bedrock 作为 Strands Agents 的模型提供商,还需使用你偏好的 AWS 认证方式配置 AWS 凭据。
bash
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.smith.langchain.com/otel/v1/traces
export OTEL_EXPORTER_OTLP_HEADERS="x-api-key=<your_langsmith_api_key>,Langsmith-Project=<your_project_name>"
# Required when using Amazon Bedrock.
export AWS_REGION=<your_aws_region>NOTE
Strands Agents 集成使用标准 OpenTelemetry OTLP 导出器。在调用 setup_langsmith_telemetry() 之前,请配置 LangSmith 端点和请求头。
2. 启用 Strands Agents 遥测
在应用启动时、创建或调用智能体之前,调用一次 setup_langsmith_telemetry():
python
from langsmith.integrations.strands_agents import setup_langsmith_telemetry
setup_langsmith_telemetry()进行本地调试时,传入 console=True 还可以将转换后的 span 打印到 stdout:
python
setup_langsmith_telemetry(console=True)3. 创建并运行你的智能体
配置完成后,Strands Agents 追踪会自动导出到 LangSmith:
python
from langsmith.integrations.strands_agents import setup_langsmith_telemetry
from strands import Agent
setup_langsmith_telemetry()
agent = Agent(
system_prompt="You are a concise assistant.",
)
response = agent("Explain what LangSmith tracing is in one sentence.")
print(response)在 LangSmith 中查看追踪
运行应用后,打开 LangSmith 项目查看包含以下内容的追踪:
- 智能体调用 span
- 事件循环周期 span
- 包含提示词、补全和 token 使用量的 LLM 调用 span
- 当智能体使用工具时,包含工具输入和输出的工具调用 span
自定义 OTLP 导出器
如果你需要向底层 OpenTelemetry 导出器传递自定义选项,请使用 create_langsmith_exporter() 创建 LangSmithSpanExporter,并手动将其附加到 Strands tracer provider:
python
from langsmith.integrations.strands_agents import create_langsmith_exporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from strands.telemetry import StrandsTelemetry
telemetry = StrandsTelemetry()
exporter = create_langsmith_exporter(
endpoint="https://api.smith.langchain.com/otel/v1/traces",
headers={
"x-api-key": "<your_langsmith_api_key>",
"Langsmith-Project": "<your_project_name>",
},
)
telemetry.tracer_provider.add_span_processor(BatchSpanProcessor(exporter))当你希望在代码中而不是通过环境变量配置导出器选项时,请使用此方法。