

# AgentCore 可觀測性入門
<a name="observability-get-started"></a>

Amazon Bedrock Amazon Bedrock AgentCore 可觀測性可協助您追蹤、偵錯和監控生產環境中的代理程式效能。本指南可協助您在代理程式應用程式中實作可觀測性功能。

**Topics**
+ [先決條件](#prerequisites)
+ [步驟 1：在 CloudWatch 上啟用交易搜尋](#enabling-transaction-search)
+ [步驟 2：啟用 Amazon Bedrock AgentCore 執行期託管代理程式的可觀測性](#enabling-observability-runtime-hosted)
+ [步驟 3：啟用非 Amazon Bedrock AgentCore 託管代理程式的可觀測性](#enabling-observability-non-runtime-hosted)
+ [步驟 4：在 Amazon CloudWatch 上使用 GenAI 可觀測性觀察您的代理程式](#agentcore-observability-genai-cloudwatch)
+ [最佳實務](#best-practices)

## 先決條件
<a name="prerequisites"></a>

開始之前，請確定您有：
+  ** AWS 帳戶**已設定登入資料 `aws configure` ()，並已啟用您想要使用之基礎模型的模型存取。
+  已安裝 **Python 3.10\+** 
+  在 Amazon CloudWatch 上**啟用交易搜尋**。只有一次，第一次使用者必須啟用 [CloudWatch 交易搜尋](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Enable-TransactionSearch.html)，才能檢視 Bedrock Amazon Bedrock AgentCore 範圍和追蹤
+  **（僅限非執行期代理程式） 在 requirements.txt 檔案中新增 OpenTelemetry 程式庫** – 包含 `aws-opentelemetry-distro`(ADOT)。如果您在 AWS Lambda 上託管代理程式，請改用 AWS Distro [AWS for OpenTelemetry 網站上的 Lambda Layer](https://aws-otel.github.io/docs/getting-started/lambda) for OpenTelemetry。
+  **（僅限非執行期代理程式）** 確認您的架構已設定為發出追蹤 （例如`strands-agents[otel]`套件）。有時您可能需要包含代理程式架構的自動檢測器 （例如 `opentelemetry-instrumentation-langchain` )。

Amazon Bedrock AgentCore 可觀測性提供兩種方式來設定監控以符合不同的基礎設施需求：

1. Amazon Bedrock AgentCore 執行期託管代理程式

1. 非執行期託管代理程式

做為每個 AWS 帳戶的一次性設定，第一次使用者需要在 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. 使用 CLI 建立政策，授予 CloudWatch Logs 中擷取範圍 AWS 的存取權。

   以下是如何使用 格式化 AWS 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. 設定追蹤區段的目的地。

   以下是如何使用 格式化 AWS 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. 透過 [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/) 開啟 CloudWatch 主控台。

1. 在**設定** 下的導覽窗格中，選擇**設定**。

1. 選取**帳戶**，然後選擇 **X-Ray 追蹤**索引標籤。

1. 在**交易搜尋**區段中，選擇**檢視設定**。

1. 在開啟的頁面上，選擇**編輯**。

1. 選擇**啟用 Transaction Search**。

1. 選取**適用於 X-Ray 使用者**，然後輸入要編製索引的追蹤百分比。您可以免費為 1% 的追蹤編製索引，並在稍後根據您的需求調整此百分比。

1. 選擇**儲存**。等到 **Ingest OpenTelemetry 範圍**顯示**已啟用**，再傳送追蹤。

現在讓我們繼續探索兩種設定可觀測性的方式。

## 步驟 2：啟用 Amazon Bedrock AgentCore 執行期託管代理程式的可觀測性
<a name="enabling-observability-runtime-hosted"></a>

Amazon Bedrock AgentCore 執行期託管代理程式會直接在 Amazon Bedrock AgentCore 環境中部署和執行，以最少的組態提供自動檢測。當您使用 AgentCore CLI 部署代理程式時，執行時間會自動使用 OpenTelemetry 檢測您的代理程式，不需要額外的 OTEL 程式庫或組態。

如需完整範例，請參閱此[筆記本](https://github.com/awslabs/amazon-bedrock-agentcore-samples/blob/main/01-tutorials/06-AgentCore-observability/01-Agentcore-runtime-hosted/Strands%20Agents/runtime_with_strands_and_bedrock_models.ipynb) 

### 建立您的代理程式專案
<a name="create-agent-strands"></a>

使用 AgentCore CLI 建立新專案。這會設定您的專案資料夾、虛擬環境和相依性：

```
npm install -g @aws/agentcore
agentcore create --name StrandsClaudeGettingStarted
```

在專案的代理程式目錄中，將預設代理程式程式碼取代為您自己的代理程式邏輯。以下是使用 Strands Agents 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")
    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 檢測：

```
cd StrandsClaudeGettingStarted
agentcore deploy
```

部署之後，您的代理程式會在 AgentCore 執行期上執行，並使用 OpenTelemetry 自動檢測。叫用您的代理程式，並在 Amazon CloudWatch 的 GenAI 可觀測性儀表板上檢視追蹤、工作階段和指標：

```
agentcore invoke
```

或者，您可以使用 AWS 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：啟用非 Amazon Bedrock AgentCore 託管代理程式的可觀測性
<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)。

### 設定 AWS 環境變數
<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
```

以唯一名稱取代 {{<YOUR-AGENT-NAME>}}，以在 GenAI 可觀測性儀表板和日誌中識別此代理程式。

**注意**  
如果您`OTEL_EXPORTER_OTLP_TRACES_HEADERS`將 設定為將範圍交付至您自己的日誌群組，您還必須新增 Amazon CloudWatch Logs 資源政策。此政策必須允許 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>

在您的 requirements.txt `aws-opentelemetry-distro`中使用 ，`opentelemetry-instrument`命令將：
+ 從環境變數載入 OTEL 組態
+ 自動檢測 Strands、Amazon Bedrock 呼叫、客服人員工具和資料庫，以及客服人員提出的其他請求
+ 將追蹤傳送至 CloudWatch
+ 可讓您在 GenAI 可觀測性儀表板中視覺化客服人員的決策程序

使用下列命令透過自動檢測來執行您的代理程式：

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

如果您在 AWS Lambda 上託管代理程式，請使用 AWS Distro [AWS for OpenTelemetry 網站上的 Lambda Layer](https://aws-otel.github.io/docs/getting-started/lambda) for OpenTelemetry。將 layer 新增至函數，然後將`AWS_LAMBDA_EXEC_WRAPPER`環境變數設定為 `/opt/otel-instrument`。然後， layer 會自動檢測您的函數。使用此方法，您不需要新增`aws-opentelemetry-distro`套件或執行先前所述的`opentelemetry-instrument`命令。

**代理程式可觀測性不支援 ADOT Collector**  
ADOT Collector 不支援代理程式可觀測性。若要從託管於 AgentCore 執行期之外的代理程式傳送遙測，您必須使用 ADOT SDK 或 AWS Lambda Layer for OpenTelemetry。

您現在可以使用您在[環境變數](#configure-opentelemetry-environment-variables)中設定的 **YOUR-AGENT-NAME** 值，在 Amazon CloudWatch 的 GenAI 可觀測性儀表板上檢視追蹤、工作階段和指標。

若要關聯多個代理程式執行的追蹤，您可以使用 OpenTelemetry 包包將工作階段 ID 與您的遙測資料建立關聯：

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

## 步驟 4：在 Amazon CloudWatch 上使用 GenAI 可觀測性觀察您的代理程式
<a name="agentcore-observability-genai-cloudwatch"></a>

實作可觀測性之後，您可以在 CloudWatch 中檢視收集的資料：

### 觀察您的代理程式
<a name="agentcore-observability-observe"></a>

1. 在 [ CloudWatch 主控台上開啟 GenAI 可觀測性](https://console.aws.amazon.com/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.aws.amazon.com/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.aws.amazon.com/cloudwatch/) 

1. 從左側導覽選取**交易搜尋** 

1. 位置：客服人員日誌群組 (`/aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>`) `spans` 中的`default`日誌串流，或使用共用範圍目的地的客服人員日誌群組中的`aws/spans`日誌串流

1. 依服務名稱或其他條件篩選

1. 選取追蹤以檢視詳細的執行圖表

### 檢視 指標
<a name="view-metrics"></a>

 **檢視指標** 

1. 開啟 [CloudWatch 主控台](https://console.aws.amazon.com/cloudwatch/) 

1. 從左側導覽選取**指標** 

1. 瀏覽至 `bedrock-agentcore` 命名空間

1. 探索可用的指標

## 最佳實務
<a name="best-practices"></a>

1.  **啟動簡單，然後展開** - Amazon Bedrock AgentCore 提供的預設可觀測性會自動擷取最關鍵的指標，包括模型呼叫、字符用量和工具執行。

1.  **為開發階段設定** - 量身打造您的可觀測性組態，以符合您目前的開發階段並逐步調整。

1.  **使用一致的命名** - 從頭開始建立服務、範圍和屬性的命名慣例

1.  **篩選敏感資料** - 從可觀測性屬性和承載篩選敏感資料，以防止機密資訊暴露。

1.  **設定警示** - 設定 CloudWatch 警示，在潛在問題影響使用者之前通知您