View a markdown version of this page

AgentCore 可觀測性入門 - Amazon Bedrock AgentCore

AgentCore 可觀測性入門

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

先決條件

開始之前,請確定您有:

  • AWS 帳戶已設定登入資料 aws configure (),並已啟用您想要使用之基礎模型的模型存取。

  • 已安裝 Python 3.10+

  • 在 Amazon CloudWatch 上啟用交易搜尋。只有一次,第一次使用者必須啟用 CloudWatch 交易搜尋,才能檢視 Bedrock Amazon Bedrock AgentCore 範圍和追蹤

  • (僅限非執行期代理程式) 在 requirements.txt 檔案中新增 OpenTelemetry 程式庫 – 包含 aws-opentelemetry-distro(ADOT)。如果您在 AWS Lambda 上託管代理程式,請改用 AWS Distro AWS for OpenTelemetry 網站上的 Lambda Layer for OpenTelemetry。

  • (僅限非執行期代理程式) 確認您的架構已設定為發出追蹤 (例如strands-agents[otel]套件)。有時您可能需要包含代理程式架構的自動檢測器 (例如 opentelemetry-instrumentation-langchain )。

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

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

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

做為每個 AWS 帳戶的一次性設定,第一次使用者需要在 Amazon CloudWatch 上啟用交易搜尋。有兩種方式可以透過 API 和 CloudWatch 主控台執行此操作。

啟用 Transaction Search 後,需等待約十分鐘,範圍才可用於搜尋和分析。選擇下列其中一個選項:

選項 1:使用 API 啟用交易搜尋

使用 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" } } } ]}'
  2. 設定追蹤區段的目的地。

    以下是如何使用 格式化 AWS CLI 命令的範例UpdateTraceSegmentDestination

    aws xray update-trace-segment-destination --destination CloudWatchLogs
  3. 選用 設定要編製索引的跨度。

    使用 設定所需的取樣百分比UpdateIndexingRule

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

選項 2:在 CloudWatch 主控台中啟用交易搜尋

在 CloudWatch 主控台中啟用交易搜尋

  1. 透過 https://console.aws.amazon.com/cloudwatch/ 開啟 CloudWatch 主控台。

  2. 設定 下的導覽窗格中,選擇設定

  3. 選取帳戶,然後選擇 X-Ray 追蹤索引標籤。

  4. 交易搜尋區段中,選擇檢視設定

  5. 在開啟的頁面上,選擇編輯

  6. 選擇啟用 Transaction Search

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

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

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

步驟 2:啟用 Amazon Bedrock AgentCore 執行期託管代理程式的可觀測性

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

如需完整範例,請參閱此筆記本

建立您的代理程式專案

使用 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()

部署和叫用您的代理程式

將代理程式部署到 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 託管代理程式的可觀測性

對於在 Amazon Bedrock AgentCore 執行時間之外執行的代理程式,您可以為部署在自有基礎設施上的代理程式提供相同的監控功能。無論您的代理程式在何處執行,這都允許一致的可觀測性。使用下列步驟來設定觀察代理程式所需的環境變數。

如需完整範例,請參閱 GitHub 網站上的 Amazon EKS 上的客服人員範例

設定 AWS 環境變數

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 記錄

在 Amazon CloudWatch 中為您的代理程式建立日誌群組和日誌串流,可用於設定下列環境變數。

設定 OpenTelemetry 環境變數

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 啟用交易搜尋中顯示的相同政策,以及 中的日誌群組 ARNResource。如果沒有此政策,X-Ray 就無法將範圍交付到您的日誌群組。

在本機建立代理程式

# 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)

使用自動檢測命令執行您的代理程式

在您的 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 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。

您現在可以使用您在環境變數中設定的 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 可觀測性觀察您的代理程式

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

觀察您的代理程式

  1. CloudWatch 主控台上開啟 GenAI 可觀測性

  2. 您可以在儀表板的 Bedrock Amazon Bedrock AgentCore 上檢視與模型調用和代理程式相關的資料。

  3. 在 Bedrock Agentcore 索引標籤中,您可以檢視客服人員檢視、工作階段檢視和追蹤檢視。

  4. 客服人員檢視會列出所有在執行期和不在執行期的客服人員,您也可以選擇客服人員,並檢視其他詳細資訊,例如執行期指標、工作階段和特定於客服人員的追蹤。

  5. 工作階段檢視索引標籤中,您可以瀏覽與客服人員相關聯的所有工作階段。

  6. 追蹤檢視索引標籤中,您可以查看客服人員的追蹤和跨度資訊。也選擇追蹤來探索追蹤軌跡和時間軸。

檢視 CloudWatch 中的日誌

在 CloudWatch 中檢視日誌

  1. 開啟 CloudWatch 主控台

  2. 在左側導覽窗格中,展開日誌,然後選取日誌群組

  3. 搜尋代理程式的日誌群組:

    • 標準日誌 (stdout/stderr) 位置: /aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>/[runtime-logs] <UUID>

    • OTEL 結構化日誌: /aws/bedrock-agentcore/runtimes/<agent_id>-<endpoint_name>/runtime-logs

檢視追蹤和範圍

檢視追蹤和範圍

  1. 開啟 CloudWatch 主控台

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

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

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

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

檢視 指標

檢視指標

  1. 開啟 CloudWatch 主控台

  2. 從左側導覽選取指標

  3. 瀏覽至 bedrock-agentcore 命名空間

  4. 探索可用的指標

最佳實務

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

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

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

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

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