Serverless Operations, inc

>_cd /blog/id_jollwrw8qv6

title

Amazon Bedrock AgentCore (6) Observability :OpenTelemetry を用いた AgentCore Runtime の実行状況や消費トークンの管理を行う

今日は Amazon Bedrock AgentCore Observability を触っていきます。

Amazon Bedrock AgentCore Observability とは

AgentCore Observabilityは、Amazon CloudWatch で提供されるダッシュボードを通じて、本番環境におけるエージェントのパフォーマンスをトレース、デバッグ、監視する開発者の支援ツールです。

AWS Distro for OpenTelemetry (ADOT) を用いたOpenTelemetry互換のテレメトリとエージェントワークフローの各ステップの詳細な可視化がサポートされており、アラーム(CloudWatch Alarm)を設定して、失敗やレイテンシー増加を自動通知することができるようになります。

OTLP (OpenTelemetry Protocol)エクスポーターを用いることで外部o11yツールへのデータ送信も可能になっているため、普段お使いのダッシュボードへの統合も可能です。

さっそくやってみる

ここに手順がまとまっているのでやっていきます。この手順は詳細が省略されており、そのままでは動作しなかったため、補足を入れながら作業を進めていきます。

1. us-west-2 で Claude 3.7 Sonnet の有効化

Bedrockマネージメントコンソールで Claude 3.7 Sonnet モデルを有効化します。

2. 初期環境セットアップ

まずはPythonの実行環境を整備します。

mkdir agentcore-observability-quickstart
cd agentcore-observability-quickstart
python3 -m venv venv
source venv/bin/activate

3. OpenTelemetry を有効化されたAgentの作成

OpenTelemetryを有効化されたAgentを作成するために、必要なモジュールをインストールします。

pip install 'strands-agents[otel]'
pip install bedrock_agentcore_starter_toolkit

次に`strands_claude.py`というファイル名で以下を作成します。

##  Save this as strands_claude.py
from strands import Agent, tool
from strands_tools import calculator # Import the calculator tool
import argparse
import json
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands.models import BedrockModel

app = BedrockAgentCoreApp()

# Create a custom tool
@tool
def weather():
    """ Get weather """ # Dummy implementation
    return "sunny"


model_id = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
model = BedrockModel(
    model_id=model_id,
)
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")
    print("User input:", user_input)
    response = agent(user_input)
    return response.message['content'][0]['text']

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

この strands_claude.py は、Anthropic Claude 3.7 Sonnet をベースにしたエージェントを定義し、簡単な計算機能と天気を返すダミーの機能を組み込んだうえで、Bedrock AgentCore のエントリポイントとして実行できるようにしたファイルです。ユーザーからの入力を受け取ると、エージェントがモデルやツールを使って処理を行い、その結果を返す仕組みになっています。つまりAgentの実行を担う本体になります。

次にAgentの起動を定義するファイルをagent.pyとして作成します。

from bedrock_agentcore_starter_toolkit import Runtime
from boto3.session import Session
boto_session = Session()
region = boto_session.region_name

agentcore_runtime = Runtime()
agent_name = "strands_claude_getting_started"
response = agentcore_runtime.configure(
    entrypoint="strands_claude.py", # file created in Step 1
    auto_create_execution_role=True,
    auto_create_ecr=True,
    requirements_file="requirements.txt", # ensure aws-opentelemetry-distro exists along with your libraries required to run your agent
    region=region,
    agent_name=agent_name
)

launch_result = agentcore_runtime.launch()
launch_result

agent.py はAgentの起動をつかさどりstrands_claude.pyを呼び出します。

公式サンプルではstrands_claude.pyで呼び出されているダミーツールであるcalculatorが含まれていないのでそれを追加で作成するために以下のコマンドを実行します。

cd ~/bedrock/agentcore-observability-quickstart

mkdir -p strands_tools
cat > strands_tools/__init__.py <<'PY'
from .calculator import calculator
PY

cat > strands_tools/calculator.py <<'PY'
from strands import tool

@tool
def calculator(a: float, b: float, op: str = "+") -> float:
    """Simple calculator: a (+,-,*,/) b"""
    if op == "+": return a + b
    if op == "-": return a - b
    if op == "*": return a * b
    if op == "/": return a / b
    raise ValueError(f"Unsupported op: {op}")
PY

cd ~/bedrock/agentcore-observability-quickstart

mkdir -p strands_tools
cat > strands_tools/__init__.py <<'PY'
from .calculator import calculator
PY

cat > strands_tools/calculator.py <<'PY'
from strands import tool

@tool
def calculator(a: float, b: float, op: str = "+") -> float:
    """Simple calculator: a (+,-,*,/) b"""
    if op == "+": return a + b
    if op == "-": return a - b
    if op == "*": return a * b
    if op == "/": return a / b
    raise ValueError(f"Unsupported op: {op}")
PY

最後に起動に必要なrequirements.txtを作成します。

cat > requirements.txt << EOF
bedrock-agentcore
strands-agents
EOF

4. Agent の起動

ではAgentをさっそく起動してみます。

 python agent.py

以下の様にCloudWatchのログ出力コマンド付きでAgentがコンテナ形式でデプロイされます。

5. テスト

agentcore invoke "2 と 3 を足して"

このコマンドを実行するとcalculatorの実行結果が出てきます。

╭─────────────────────────────────────────── strands_claude_getting_started ───────────────────────────────────────────╮
│ Session: 2afd4457-8bb5-425b-abe7-1f8c28efec06                                                                        │
│ Request ID: 8859f649-004a-452c-bb55-0a20feb6bf4d                                                                     │
│ ARN: arn:aws:bedrock-agentcore:us-west-2:917561075114:runtime/strands_claude_getting_started-aDbDl745QZ              │
│ Logs: aws logs tail /aws/bedrock-agentcore/runtimes/strands_claude_getting_started-aDbDl745QZ-DEFAULT                │
│ --log-stream-name-prefix "2025/09/11/[runtime-logs]" --follow                                                        │
│       aws logs tail /aws/bedrock-agentcore/runtimes/strands_claude_getting_started-aDbDl745QZ-DEFAULT                │
│ --log-stream-name-prefix "2025/09/11/[runtime-logs]" --since 1h                                                      │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

Response:
The sum of 2 and 3 is 5.

画面に表示されているログのtailコマンドを実行すると以下の様にログが出力されています。

aws logs tail /aws/bedrock-agentcore/runtimes/strands_claude_getting_started-aDbDl745QZ-DEFAULT  --log-stream-name-prefix "2025/09/11/[runtime-logs]" --follow

2025-09-11T07:33:59.240000+00:00 2025/09/11/[runtime-logs]baebaa6e-ab22-4c9e-bd12-c8930155ee35 2025-09-11 07:33:59,240 - bedrock_agentcore.app - INFO - [rid:f90060bf-908b-42f4-9f39-f6e9468253cf] [sid:2afd4457-8bb5-425b-abe7-1f8c28efec06] Invocation completed successfully (2.788s)

CloudWatchにはBedrockという名前の自動ダッシュボードが作成されています。

まとめ

AgentCore Observabilityを使用することでただ、エージェントをつくるだけではなくて、本番環境で安全に運用することができる環境を整えることができます。単純にCloudWatchと連携するだけでなく外部の使いなれたObservabilityツール(Datadog, New Relic, Grafana など)との連携も可能であることからより柔軟な監視体制を構築しての運用が可能になりそうです。

Written by
編集部

亀田 治伸

Kameda Harunobu

  • Facebook->
  • X->
  • GitHub->

Share

Facebook->X->
Back
to list
<-