

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 开始使用 AgentCore 可观测性
<a name="observability-get-started"></a>

Amazon Bedrock 可 AgentCore 观测性可帮助您跟踪、调试和监控生产环境中的代理性能。本指南可帮助您在代理应用程序中实现可观察性功能。

**Topics**
+ [先决条件](#prerequisites)
+ [步骤 1：启用交易搜索 CloudWatch](#enabling-transaction-search)
+ [第 2 步：为 Amazon Bedrock AgentCore Runtime 托管的代理启用可观察性](#enabling-observability-runtime-hosted)
+ [第 3 步：为非亚马逊 Bedrock 代理启用可观察性 AgentCore-hosted](#enabling-observability-non-runtime-hosted)
+ [第 4 步：在亚马逊上使用 GenAI 可观察性观察您的代理 CloudWatch](#agentcore-observability-genai-cloudwatch)
+ [最佳实践](#best-practices)

## 先决条件
<a name="prerequisites"></a>

在开始之前，请确保你有：
+  ** Amazon 配置**了凭据的账户 (`aws configure`)，启用了您想要使用的基础模型的模型访问权限。
+  **已安装 Python 3.10\+ **
+  ****在亚马逊上启用交易搜索 CloudWatch。只有一次，首次使用的用户必须启用 “[CloudWatch 交易搜索” ](https://docs.amazonaws.cn/AmazonCloudWatch/latest/monitoring/Enable-TransactionSearch.html) 才能查看 Bedrock Amazon Bedrock 的跨度和轨 AgentCore 迹
+  **（仅限Non-runtime 代理）添加 OpenTelemetry 库 ** — 在 requirements.txt 文件中包含`aws-opentelemetry-distro`（ADOT）。如果您在 Amazon Lambda 上托管代理，请改用 Amazon 发行版网站 OpenTelemetry[上的 ](https://aws-otel.github.io/docs/getting-started/lambda)Amazon Lambda 层。 OpenTelemetry 
+  **（仅限Non-runtime 代理）**确保将您的框架配置为发出跟踪（例如，`strands-agents[otel]`软件包）。有时您可能需要加入代理框架的自动分析器（例如，`opentelemetry-instrumentation-langchain`）。

Amazon Bedrock AgentCore 可观测性提供了两种配置监控以满足不同的基础设施需求的方法：

1. 亚马逊 Bedrock 代理商 AgentCore Runtime-hosted 

1. Non-runtime 托管代理

作为每个 Amazon 账户的一次性设置，首次使用的用户需要在亚马逊上启用交易搜索 CloudWatch。有两种方法可以做到这一点，即通过 API 和通过 CloudWatch 控制台。

## 步骤 1：启用交易搜索 CloudWatch
<a name="enabling-transaction-search"></a>

启用 Transaction Search 后，可能需要十分钟才能使用跨度进行搜索和分析。选择以下选项之一：

### 选项 1：使用 API 启用交易搜索
<a name="enable-transaction-search-api"></a>

 **使用 API 启用交易搜索 ** 

1. 使用 Amazon CLI 创建策略，授予对 CloudWatch 日志中采集跨度的访问权限。

   下面显示了如何使用格式化您的 Amazon CLI 命令的示例`PutResourcePolicy`。

   ```
   aws logs put-resource-policy --policy-name MyResourcePolicy --policy-document '{ "Version": "2012-10-17", "Statement": [ { "Sid": "TransactionSearchXRayAccess", "Effect": "Allow", "Principal": { "Service": "xray.amazonaws.com" }, "Action": "logs:PutLogEvents", "Resource": [ "arn:partition:logs:region:account-id:log-group:aws/spans:*", "arn:partition:logs:region:account-id:log-group:/aws/application-signals/data:*" ], "Condition": { "ArnLike": { "aws:SourceArn": "arn:partition:xray:region:account-id:*" }, "StringEquals": { "aws:SourceAccount": "account-id" } } } ]}'
   ```

1. 配置追踪分段的目的地。

   下面显示了如何使用格式化您的 Amazon CLI 命令的示例`UpdateTraceSegmentDestination`。

   ```
   aws xray update-trace-segment-destination --destination CloudWatchLogs
   ```

1.  **可选**配置索引的跨度量。

   使用配置所需的采样百分比`UpdateIndexingRule`。

   ```
   aws xray update-indexing-rule --name "Default" --rule '{"Probabilistic": {"DesiredSamplingPercentage": number}}'
   ```

### 选项 2：在 CloudWatch 控制台中启用交易搜索
<a name="enable-transaction-search-console"></a>

 **在 CloudWatch 控制台中启用交易搜索 ** 

1. 在处打开 CloudWatch 控制台[https://console.aws.amazon.com/cloudwatch/](https://console.amazonaws.cn/cloudwatch/)。

1. 在导航窗格的 “**设置” 下**，选择 “**设置” **。

1. 选择 “**账户”**，然后选择 “**X-Ray 跟踪**” 选项卡。

1. 在**交易搜索**部分，选择**查看设置**。

1. 在打开的页面上，选择**编辑**。

1. 选择**启用 Transaction Search**。

1. 选择 “**面向 X-Ray 用户”，**然后输入要索引的跟踪百分比。您可以免费索引 1% 的追踪，然后根据需要调整该百分比。

1. 选择**保存**。等待 ** Ingest OpenTelemetry spans ** 显示**已启用，**然后再发送跟踪。

现在让我们继续探索配置可观测性的两种方法。

## 第 2 步：为 Amazon Bedrock AgentCore Runtime 托管的代理启用可观察性
<a name="enabling-observability-runtime-hosted"></a>

Amazon Bedrock AgentCore Runtime-hosted 代理直接在 Amazon Bedrock AgentCore 环境中部署和执行，以最少的配置提供自动检测。当您使用 AgentCore CLI 部署代理时，运行时会自动为您的代理进行检 OpenTelemetry 测，无需额外的 OTEL 库或配置。

有关完整示例，请参阅上的可[AgentCore 观测性示例 GitHub ](https://github.com/awslabs/amazon-bedrock-agentcore-samples/tree/main/01-features/06-observe-evaluate-optimize-your-agent/01-observe) 

### 创建您的代理项目
<a name="create-agent-strands"></a>

使用 AgentCore CLI 创建新项目。这将设置您的项目文件夹、虚拟环境和依赖关系：

```
npm install -g @aws/agentcore
agentcore create \
  --project-name StrandsObservability \
  --name StrandsClaudeGettingStarted \
  --language Python \
  --framework Strands \
  --model-provider Bedrock \
  --memory none
cd StrandsObservability/app/StrandsClaudeGettingStarted
uv add strands-agents-tools
cd ../..
```

在项目的代理目录中，用您自己的代理逻辑替换默认代理代码。以下是使用 Strands 代理 SDK 的示例：

```
## app/StrandsClaudeGettingStarted/main.py
from strands import Agent, tool
from strands_tools import calculator
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands.models import BedrockModel

app = BedrockAgentCoreApp()

@tool
def weather():
    """Get weather"""
    return "sunny"

model = BedrockModel(
    model_id="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
)
agent = Agent(
    model=model,
    tools=[calculator, weather],
    system_prompt="You're a helpful assistant. You can do simple math calculation, and tell the weather."
)

@app.entrypoint
def strands_agent_bedrock(payload):
    """Invoke the agent with a payload"""
    user_input = payload.get("prompt")
    if not isinstance(user_input, str) or not user_input:
        return "Error: 'prompt' must be a non-empty string"
    response = agent(user_input)
    return response.message['content'][0]['text']

if __name__ == "__main__":
    app.run()
```

### 部署和调用您的代理
<a name="deploy-invoke-agent"></a>

将代理部署到 AgentCore 运行时。 AgentCore CLI 处理打包、部署和自动 OTEL 仪器：

```
agentcore deploy
```

部署后，您的代理在 AgentCore Runtime 上运行，并使用 OpenTelemetry自动进行检测。调用您的代理并在亚马逊的 GenAI 可观察性控制面板上查看跟踪、会话和指标： CloudWatch

```
agentcore invoke
```

或者，您可以使用 Amazon SDK 以编程方式调用代理：

```
import boto3, json

client = boto3.client('bedrock-agentcore')

response = client.invoke_agent_runtime(
    agentRuntimeArn="YOUR_AGENT_RUNTIME_ARN",
    runtimeSessionId="my-observability-session-001",
    payload=json.dumps({"prompt": "What is 2 + 2?"}),
    qualifier="DEFAULT"
)

print(json.loads(response['response'].read()))
```

## 第 3 步：为非亚马逊 Bedrock 代理启用可观察性 AgentCore-hosted
<a name="enabling-observability-non-runtime-hosted"></a>

对于在 Amazon Bedrock AgentCore 运行时之外运行的代理，您可以为部署在自己的基础设施上的代理提供相同的监控功能。无论您的代理在何处运行，这都可实现一致的可观察性。使用以下步骤配置观察代理所需的环境变量。

有关完整示例，请参阅 GitHub 网站上的 Amazon EKS [ 上的](https://github.com/awslabs/agentcore-samples/tree/main/03-integrations/agents-hosted-outside-runtime/agents-on-eks)代理示例。

### 配置 Amazon 环境变量
<a name="configure-aws-environment-variables"></a>

```
export AWS_ACCOUNT_ID=<account id>
export AWS_DEFAULT_REGION=<default region>
export AWS_REGION=<region>
export AWS_ACCESS_KEY_ID=<access key id>
export AWS_SECRET_ACCESS_KEY=<secret key>
```

### 配置 CloudWatch 日志
<a name="configure-cloudwatch-logging"></a>

为您的代理在 Amazon 中创建日志组和日志流 CloudWatch ，您可以使用它来配置以下环境变量。

### 配置 OpenTelemetry 环境变量
<a name="configure-opentelemetry-environment-variables"></a>

```
export AGENT_OBSERVABILITY_ENABLED=true # Activates the ADOT pipeline
export OTEL_PYTHON_DISTRO=aws_distro # Uses AWS Distro for OpenTelemetry
export OTEL_PYTHON_CONFIGURATOR=aws_configurator # Sets AWS configurator for ADOT SDK
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf # Configures export protocol
export  OTEL_EXPORTER_OTLP_LOGS_HEADERS=x-aws-log-group=<YOUR-LOG-GROUP>,x-aws-log-stream=<YOUR-LOG-STREAM>,x-aws-metric-namespace=<YOUR-NAMESPACE>
# Directs logs to CloudWatch groups
export OTEL_EXPORTER_OTLP_TRACES_HEADERS=x-aws-log-group=<YOUR-LOG-GROUP>,x-aws-log-stream=<YOUR-TRACES-LOG-STREAM>
# (Optional) Directs spans to your log group instead of the aws/spans log group. Requires ADOT version 0.18.0 or later.
export OTEL_RESOURCE_ATTRIBUTES=service.name=<YOUR-AGENT-NAME> # Identifies your agent in observability data
export OTEL_AWS_APPLICATION_SIGNALS_ENABLED=false # AWS Lambda Layer for OpenTelemetry only: disables Application Signals
export OTEL_LOGS_EXPORTER=otlp # AWS Lambda Layer for OpenTelemetry only: exports logs over OTLP
export OTEL_METRICS_EXPORTER=awsemf # AWS Lambda Layer for OpenTelemetry only: exports metrics as CloudWatch EMF
```

在 GenAI {{<YOUR-AGENT-NAME>}} 可观测性仪表板和日志中替换为唯一名称以标识此代理。

**注意**  
如果您设置将跨度传送`OTEL_EXPORTER_OTLP_TRACES_HEADERS`到自己的日志组，则还必须添加 Amazon L CloudWatch ogs 资源策略。该策略必须允许 X-Ray (`xray.amazonaws.com`) 调用`logs:PutLogEvents`该日志组。使用与 “使用 API [ 启用事务搜索” 中所示的相同策略](#enable-transaction-search-api)，并输入日志组的 ARN。`Resource`没有此策略，就 X-Ray 无法将跨度传送到您的日志组。

### 在本地创建代理
<a name="create-agent-locally"></a>

```
# Create agent.py -  Strands agent that is a weather assistant
from strands import Agent
from strands_tools import http_request

# Define a weather-focused system prompt
WEATHER_SYSTEM_PROMPT = """You are a weather assistant with HTTP capabilities. You can:

1. Make HTTP requests to the National Weather Service API
2. Process and display weather forecast data
3. Provide weather information for locations in the United States

When retrieving weather information:
1. First get the coordinates or grid information using https://api.weather.gov/points/{latitude},{longitude} or https://api.weather.gov/points/{zipcode}
2. Then use the returned forecast URL to get the actual forecast

When displaying responses:
- Format weather data in a human-readable way
- Highlight important information like temperature, precipitation, and alerts
- Handle errors appropriately
- Convert technical terms to user-friendly language

Always explain the weather conditions clearly and provide context for the forecast.
"""

# Create an agent with HTTP capabilities
weather_agent = Agent(
    system_prompt=WEATHER_SYSTEM_PROMPT,
    tools=[http_request],  # Explicitly enable http_request tool
)

response = weather_agent("What's the weather like in Seattle?")
print(response)
```

### 使用自动检测命令运行代理
<a name="run-agent-automatic-instrumentation"></a>

`aws-opentelemetry-distro`在你的 requirements.txt 中，该`opentelemetry-instrument`命令将：
+ 从环境变量加载您的 OTEL 配置
+ 自动检测 Strands、Amazon Bedrock 调用、代理工具和数据库以及代理提出的其他请求
+ 将痕迹发送至 CloudWatch
+ 使您能够在 GenAI 可观测性仪表板中可视化代理的决策过程

使用以下命令使用自动工具运行代理：

```
opentelemetry-instrument python agent.py
```

如果您在 Amazon Lambda 上托管代理，请在 Amazon 发行版 OpenTelemetry[网站上使用 ](https://aws-otel.github.io/docs/getting-started/lambda)Amazon Lambda 层。 OpenTelemetry 将该层添加到您的函数，然后将`AWS_LAMBDA_EXEC_WRAPPER`环境变量设置为`/opt/otel-instrument`。然后，该层会自动整理您的函数。使用这种方法，您无需添加`aws-opentelemetry-distro`软件包或运行前面描述的`opentelemetry-instrument`命令。

**不支持 ADOT Collector 以实现代理可观察性**  
代理可观察性不支持 ADOT 收集器。要从 AgentCore 运行时之外托管的代理发送遥测数据，必须使用 ADOT SDK 或 Amazon Lambda 层。 OpenTelemetry

现在，您可以使用您在[环境变量中配置的值在亚马逊 CloudWatch 的 GenAI 可观测性控制面板上查看您的跟踪、会话和指标。** YOUR-AGENT-NAME **](#configure-opentelemetry-environment-variables)

要关联多个代理运行中的跟踪，您可以使用行李将会话 ID 与您的遥测 OpenTelemetry 数据关联起来：

```
from opentelemetry import baggage, context
ctx = baggage.set_baggage("session.id", session_id)
```

## 第 4 步：在亚马逊上使用 GenAI 可观察性观察您的代理 CloudWatch
<a name="agentcore-observability-genai-cloudwatch"></a>

实现可观测性后，可以在以下位置查看收集的数据： CloudWatch

### 观察你的经纪人
<a name="agentcore-observability-observe"></a>

1. 在控制台上打开 [ GenAI 可观察性 CloudWatch ](https://console.amazonaws.cn/cloudwatch/home#gen-ai-observability) 

1. 您可以在控制面板的 Bedrock Amazon Bedrock 上查看与模型调用和代理相关的数据。 AgentCore 

1. 在 Bedrock Agentcore 选项卡中，您可以查看代理视图、会话视图和跟踪视图。

1. 代理视图列出了所有已开启和未运行的代理，您也可以选择代理并查看更多详细信息，例如特定于代理的运行时指标、会话和跟踪。

1. 在 “会**话视图**” 选项卡中，您可以浏览与代理关联的所有会话。

1. 在 “**跟踪视图**” 选项卡中，您可以查看代理的跟踪和跨度信息。还可以通过选择轨迹来探索追踪轨迹和时间表。

### 查看日志 CloudWatch
<a name="view-logs-cloudwatch"></a>

 **查看登录信息 CloudWatch ** 

1. 打开 [CloudWatch 控制台](https://console.amazonaws.cn/cloudwatch/) 

1. 在左侧导航窗格中，展开**日志，**然后选择**日志组 ** 

1. 搜索您的代理的日志组：
   + 标准日志 (stdout/stderr) 位置：`/aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>/[runtime-logs] <UUID>`
   + OTEL 结构化日志：`/aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>/runtime-logs`

### 查看跟踪数据与跨度信息
<a name="view-traces-spans"></a>

 **查看轨迹和跨度 ** 

1. 打开 [CloudWatch 控制台](https://console.amazonaws.cn/cloudwatch/) 

1. **从左侧导航栏中选择 “**交易搜索”

1. 位置：代理`spans`日志组 (`/aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>`) 中的`default`日志流，或使用共享跨度目标的代理的`aws/spans`日志组中的日志流

1. 按服务名称或其他条件筛选

1. 选择跟踪记录以查看详细的执行图

### 查看指标
<a name="view-metrics"></a>

 **查看指标 ** 

1. 打开 [CloudWatch 控制台](https://console.amazonaws.cn/cloudwatch/) 

1. **从左侧导航栏中选择**指标

1. 浏览到`bedrock-agentcore`命名空间

1. 探索可用指标

## 最佳实践
<a name="best-practices"></a>

1.  **从简单开始，然后扩展 **-Amazon Bedrock 提供的默认可观察性会自动 AgentCore 捕获最关键的指标，包括模型调用、代币使用和工具执行。

1.  **为开发阶段进行配置 **-定制您的可观测性配置以匹配您当前的开发阶段，并逐步进行调整。

1.  **使用一致的命名 **-从一开始就为服务、跨度和属性建立命名规范

1.  **筛选敏感数据 **-通过从可观测性属性和有效载荷中筛选敏感数据，防止机密信息泄露。

1.  **设置警报 **-配置 CloudWatch 警报，在潜在问题影响用户之前通知您