Claude 4と連携するBedrock AgentCoreを動かしてみた
1. はじめに
現時点(2025年7月)で Amazon Bedrock AgentCore はプレビュー段階にあり、動作の安定度にはばらつきがあります。特にインスタンス起動やモデル呼び出しでエラーが散見され、us‑east‑1(北バージニア)リージョンの利用がお勧めです。
公式の内容は随時変更になる可能性がありますので、内容がずれている場合には公式の情報を確認してください。
1.1 AWS Summit NY 2025での発表内容まとめ
AWSが2025年7月に開催したAWS Summit New Yorkにて、新世代エージェント開発基盤「Amazon Bedrock AgentCore」が発表されました。
特徴・メリット
構成は豊富な機能を持ちつつ、一部だけを採用できる柔軟性が最大の強みです。
| 項目名 | 説明 |
|---|---|
| AgentCore Runtime | サーバーレス、マルチプロトコル/マルチモデル対応、セッション隔離、低レイテンシの実行環境 |
| AgentCore Memory | 短期・長期メモリのサポート、エージェント間でのコンテキスト共有機能 |
| AgentCore Identity | エージェント用に固有IDを発行、OAuth・IAM・APIキー対応、認証・認可を一元管理 |
| AgentCore Gateway | 既存API/LambdaのMCP化、自動安全ラッパー生成 |
| Code Interpreter | 隔離環境でのコード実行機能(Python/JS) |
| Browser Tool | クラウドブラウザを通じた動的Web操作、安全かつスケーラブル |
| Observability | OpenTelemetry対応、CloudWatch連携でのトレース・メトリクス可視化 |
| Marketplace | サードパーティ製エージェント・ツール購入が可能に |
| S3 Vectors | ベクトルクエリ低コスト化(最大90%)ストレージの実装 |
※Introducing Amazon Bedrock AgentCore: Securely deploy and operate AI agents at any scale (preview)
1.2 GitHub チュートリアルの体系と目的
公式Github には様々なコンポーネント別・ユースケース別でチュートリアルが公開されています :
- 01‑tutorials/:Notebook形式で基礎から、特に「Runtime」「Gateway」「Memory」「Identity」「Tools」「Observability」などの各機能を手順付きで学ぶ内容
- 02‑use‑cases/:特定のユースケースに適した統合的エージェント構築例
- 03‑integrations/:Strands、LangChain、CrewAI等との連携方法を詳細に解説
今回選択したチュートリアル(01‑AgentCore‑runtime/strands‑agent‑runtime)は「AgentCore Runtime」に特化した内容となっており、エージェントのローカル開発からクラウドへのデプロイ、Boto3経由での呼び出しまで一貫して確認することを目的としたものです。
2. 環境構築とローカル動作の確認
Bedrock AgentCore Runtime は、作成した LLM エージェントをクラウド上にデプロイしてエンドポイントを公開するための仕組みです。AgentCore では、Python ベースのエージェントロジックを Docker イメージとしてパッケージし、Amazon ECR (Elastic Container Registry) にプッシュした上で、それを AgentCore のマネージドなエージェントランタイムとして起動します。
これらを参考にしながら、以下のステップでローカル環境の準備を進めます。
2.1 事前作業
まずは、GitHubから対象のチュートリアルをCloneして、Python仮想環境を構築し、依存ライブラリをインストールします。
$git clone https://github.com/awslabs/amazon-bedrock-agentcore-samples.git
$cd amazon-bedrock-agentcore-samples/01-tutorials/01-AgentCore-runtime/strands-agent-runtime
$python -m venv .venv
$source .venv/bin/activate
$pip install -r requirements.txt
2.2 boto3 の動作とリージョン設定
boto3 はAWS SDK for Python の一部であり、デフォルトでは AWS CLIと共通の設定ファイル(~/.aws/config および ~/.aws/credentials) を参照しますので、正しいリージョンが指定されている必要があります。ただし、Session()などで呼び出す時に個別にリージョンを指定するのであれば、デフォルトの設定を変更する必要はありません。
$aws configure list
Name Value Type Location
---- ----- ---- --------
profile <not set> None None
access_key ****************ZDVW shared-credentials-file
secret_key ****************ivqa shared-credentials-file
region ap-northeast-1 config-file ~/.aws/config
$aws configure
AWS Access Key ID [****************TNH2]:
AWS Secret Access Key [****************MVC7]:
Default region name [ap-northeast-1]: us-east-1
Default output format [None]: json
2.3 Claude Sonnet 4 モデルの有効化
Amazon Bedrock を使うには、あらかじめ モデルカタログ から使用したいモデルを有効化する必要があります。今回は claude-sonnet-4 モデルを選定しました。このモデルに関しては地域毎の利用可能な Inference Profiles IDを指定する必要があります。
$aws bedrock list-inference-profiles \
--query "inferenceProfileSummaries[].inferenceProfileId" \
--output table
--------------------------------------------------
| ListInferenceProfiles |
+------------------------------------------------+
| us.anthropic.claude-3-sonnet-20240229-v1:0 |
| us.anthropic.claude-3-opus-20240229-v1:0 |
| us.anthropic.claude-3-haiku-20240307-v1:0 |
| us.meta.llama3-2-11b-instruct-v1:0 |
| us.meta.llama3-2-3b-instruct-v1:0 |
| us.meta.llama3-2-90b-instruct-v1:0 |
| us.meta.llama3-2-1b-instruct-v1:0 |
| us.anthropic.claude-3-5-sonnet-20240620-v1:0 |
| us.anthropic.claude-3-5-haiku-20241022-v1:0 |
| us.meta.llama3-1-8b-instruct-v1:0 |
| us.meta.llama3-1-70b-instruct-v1:0 |
| us.meta.llama3-3-70b-instruct-v1:0 |
| us.anthropic.claude-3-5-sonnet-20241022-v2:0 |
| us.deepseek.r1-v1:0 |
| us.mistral.pixtral-large-2502-v1:0 |
| us.meta.llama4-scout-17b-instruct-v1:0 |
| us.meta.llama4-maverick-17b-instruct-v1:0 |
| us.amazon.nova-premier-v1:0 |
| us.anthropic.claude-opus-4-20250514-v1:0 |
| us.anthropic.claude-sonnet-4-20250514-v1:0 |
| us.anthropic.claude-3-7-sonnet-20250219-v1:0 |
| us.amazon.nova-pro-v1:0 |
| us.amazon.nova-micro-v1:0 |
| us.amazon.nova-lite-v1:0 |
+------------------------------------------------+
上記コマンドで us.anthropic.claude-sonnet-4-20250514-v1:0 といったモデルIDが確認できました。
2.4 Claude Sonnet 4 を使ったローカル実行
準備が整ったら、strands_claude_local.py スクリプトを使ってプロンプトを投げてみます。
動作としては、Agentがローカルで動作していて、そこからBedrock LLMへ投げている経路になります。
$python strands_claude_local.py '{"prompt": "What is the weather now?"}'
I'll check the current weather for you.
Tool #1: weather
The current weather is sunny! It's a beautiful day outside.
このように、Claude 4 Sonnet モデルを使ったプロンプトへの応答が確認できれば、事前の確認は完了です。
3. AgentCore Runtimeへのデプロイ
3.1 AgentCore Runtime で動作させるためのコード変更
AgentCore Runtime 上でエージェントを動作させるには、ローカルでのコードに対していくつかの変更が必要です。これにより、AgentCore のライフサイクル制御やイベントハンドリングが有効になり、デプロイ可能な形に整備されます。
Runtimeアプリケーションクラスのインポート
最初に、AgentCore Runtime に必要なクラスをインポートします。
from bedrock_agentcore.runtime import BedrockAgentCoreApp
アプリケーションの初期化
コード内で BedrockAgentCoreApp のインスタンスを生成し、アプリケーション全体のエントリポイントを管理します。
app = BedrockAgentCoreApp()
呼び出し関数にデコレーターを付与
AgentCoreが処理すべき関数を明示的に登録するため、@app.entrypoint デコレーターを使用します。
@app.entrypoint
def invoke_agent(request):
...
アプリケーションの起動制御
最後に app.run() を記述することで、AgentCore Runtime による実行制御が可能になります。
app.run()
以上、簡単なご説明になりますが、FastAPIのような書式で簡単にAgentCore Runtimeにて動作させる形式に変更ができます。
変更後のスクリプト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-sonnet-4-20250514-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()
3.2 IAMロールの作成
まず、AgentCore Runtime がエージェントを実行するための IAM ロールを作成します。これには、上位デレクトリのutils.pyをimportしており、その中で定義されていますが付与するポリシーや信頼関係が自動で設定されるヘルパー関数 create_agentcore_role() を使用します。
>>> import sys
>>> import os
>>> # Get the current notebook's directory
>>> current_dir = os.path.dirname(os.path.abspath('__file__' if '__file__' in globals() else '.'))
>>> # Navigate up to the utils.py location
>>> utils_dir = os.path.join(current_dir, '..')
>>> utils_dir = os.path.abspath(utils_dir)
>>> # Add to sys.path
>>> sys.path.insert(0, utils_dir)
>>> from utils import create_agentcore_role
>>> agent_name="strands_claude_us1"
>>> agentcore_iam_role = create_agentcore_role(agent_name=agent_name)
attaching role policy agentcore-strands_claude_us1-role
この出力から分かるように、IAM ロール agentcore-strands_claude_us1-role の作成と、必要な IAM ポリシーの付与が行われました。コンソール等から確認ができるはずです。
3.3 Runtime構成ファイルの生成
次に、Bedrock AgentCore にデプロイするための設定ファイル .bedrock_agentcore.yamlなどを生成します。これは、エントリーポイントスクリプト、使用する IAM ロール、Python の依存ファイル (requirements.txt) などを指定することで行います。
>>> from bedrock_agentcore_starter_toolkit import Runtime
>>> from boto3.session import Session
>>> boto_session = Session()
>>> region = boto_session.region_name
>>> region
'us-east-1'
>>> agentcore_runtime = Runtime()
>>> response = agentcore_runtime.configure(
... entrypoint="strands_claude.py",
... execution_role=agentcore_iam_role['Role']['Arn'],
... auto_create_ecr=True,
... requirements_file="requirements.txt",
... region=region,
... agent_name=agent_name+"2"
... )
Bedrock AgentCore configured: /Users/*/awsagentcore_test/amazon-bedrock-agentcore-samples/01-tutorials/01-AgentCore-runtime/01-hosting-agent/01-strands-with-bedrock-model/.bedrock_agentcore.yaml
>>> response
・・・
この構成により、以下が生成・設定されました:
- .bedrock_agentcore.yaml(構成ファイル)
- Dockerfile(Runtime環境構築用)
このステップで、デプロイに向けた準備が完了しました。
3.4 AWSへのビルド & デプロイ
以下のコードagentcore_runtime.launch()により、Dockerイメージビルド → ECRへのプッシュ → AgentCore Runtimeへのデプロイが一括で行われます。
>>> launch_result = agentcore_runtime.launch()
Build: #9 11.18 ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
The push refers to repository [441244353***.dkr.ecr.us-east-1.amazonaws.com/bedrock_agentcore-strands_claude_us12]
7646fc0da09f: Pushed
041cd873b188: Pushed
5f71b7594485: Pushed
fb457be60215: Pushed
996c066575b9: Pushed
ff3274401a0c: Pushed
8b31ad78e00c: Pushed
83ab85380878: Pushed
58d7b7786e98: Pushed
latest: digest: sha256:2e7125226fdd94a0d4b726e0c81223b1df57642622c2c293f5264ab08538c1bf size: 2209
Deployed to cloud: arn:aws:bedrock-agentcore:us-east-1:441244353***:runtime/strands_claude_us12-DVjAf98s0v
🔍 Agent logs available at:
/aws/bedrock-agentcore/runtimes/strands_claude_us12-DVjAf98s0v-DEFAULT
/aws/bedrock-agentcore/runtimes/strands_claude_us12-DVjAf98s0v-DEFAULT/runtime-logs
💡 Tail logs with: aws logs tail /aws/bedrock-agentcore/runtimes/strands_claude_us12-DVjAf98s0v-DEFAULT --follow
💡 Or view recent logs: aws logs tail /aws/bedrock-agentcore/runtimes/strands_claude_us12-DVjAf98s0v-DEFAULT --since 1h
>>>
>>> launch_result
長い依存関係インストールや、依存コンフリクトによる警告が出る点(opentelemetry関連)が出力に見られますが、致命的なエラーではなく構築自体は完了しているようです。
Runtimeステータス確認
ステータスが 'READY' になるまで待機し、正常起動を確認するような内容になっているようです。READYであればクラウド側Runtime起動完了になります。
>>> status_response = agentcore_runtime.status()
Retrieved Bedrock AgentCore status for: strands_claude_us12
>>> status = status_response.endpoint['status']
>>> end_status = ['READY', 'CREATE_FAILED', 'DELETE_FAILED', 'UPDATE_FAILED']
>>> while status not in end_status:
... time.sleep(10)
... status_response = agentcore_runtime.status()
... status = status_response.endpoint['status']
... print(status)
>>>
>>> status
'READY'
>>>
3.5 AgentCore Runtime からの呼出
セットアップが完了したら、 agentcore_runtime モジュールを使ってエージェントに問い合わせを行ってみましょう。今回は、シンプルなプロンプト "How is the weather now?" を送信して、現在の天気情報を取得してみます。
以下は、実際のインタラクションの様子です:
>>> invoke_response = agentcore_runtime.invoke({"prompt": "How is the weather now?"})
>>> invoke_response
{'ResponseMetadata': {'RequestId': 'c7ba8b6f-d0b3-4fba-b860-c988c4f2cccc', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Mon, 21 Jul 2025 14:09:26 GMT', 'content-type': 'application/json', ... ', 'contentType': 'application/json', 'statusCode': 200, 'response': [b'"The weather is currently sunny! It\'s a beautiful day outside."']}
>>> import json
>>> response_text = json.loads(invoke_response['response'][0].decode("utf-8"))
>>> print(response_text)
The weather is currently sunny! It's a beautiful day outside.
>>>
3.6 boto3 からの呼出
今回扱うのは、boto3 の低レベル API を直接叩いて Bedrock Agent Runtime を動かす方法です。高レベルの Runtime() クラスを使わないダイレクトな呼び出しで、より細かい制御やストリーミング対応が可能になります。
- クライアント生成:boto3.client('bedrock-agent-runtime') を使い、エージェントランタイムにアクセスするクライアントを生成。
- invoke_agent_runtime 呼び出し:必要なパラメーター(ARN、qualifier、payload)を指定。
- ストリーミングおよび非ストリーミングレスポンス・イベント処理などを適切に扱うことで、リアルタイム応答を取得可能。
invoke_agent_runtime は リアルタイムストリーミング対応であり、JSON やバイナリでチャンク単位応答を扱えます。
公式 AWS ドキュメントには、Node.js 版、Python(boto3)版、その他コードサンプルがあります。Python 版では、invoke_agent_runtime によるエージェント呼び出し例があり、設定方法や応答処理フローも解説されていますので参照ください。
以下は、Githubのチュートリアルで公開されているコード例からです。
>>> import boto3
>>> agent_arn = launch_result.agent_arn # 呼び出し情報(事前 launch_result で得た agent_arn)
>>> agentcore_client = boto3.client(
... 'bedrock-agentcore',
... region_name=region #'us-east-1'
... )
>>>
>>> boto3_response = agentcore_client.invoke_agent_runtime(
... agentRuntimeArn=agent_arn,
... qualifier="DEFAULT",
... payload=json.dumps({"prompt": "What is 2+2?"})
... )
>>> if "text/event-stream" in boto3_response.get("contentType", ""):
... content = []
... for line in boto3_response["response"].iter_lines(chunk_size=1):
... if line:
... line = line.decode("utf-8")
... if line.startswith("data: "):
... line = line[6:]
... logger.info(line)
... content.append(line)
... display(Markdown("\n".join(content)))
... else:
... try:
... events = []
... for event in boto3_response.get("response", []):
... events.append(event)
... except Exception as e:
... events = [f"Error reading EventStream: {e}"]
... display(Markdown(json.loads(events[0].decode("utf-8"))))
...
<IPython.core.display.Markdown object>
>>>
>>> json.loads(events[0].decode("utf-8"))
'The answer is 4.'
>>>
(コードをそのまま利用したので、Objectが返されていますが後の、Jsonでデコードした部分がレスポンスになります。)
4. まとめ
本記事では、Amazon Bedrock AgentCore の概要から、Claude Sonnet 4 モデルとの統合手順、さらには AgentCore Runtimeへのデプロイ方法やboto3経由の呼び出し方法まで、チュートリアルに沿った形式で手順を追って解説しました。Bedrock AgentCoreは、OpenTelemetryやMarketplace連携など、今後さらに発展が期待されるエージェント開発基盤です。AWSエコシステムにおけるAIエージェントの実運用を視野に入れた構築・検証を進めるうえで、本記事がその第一歩になれば幸いです。
Discussion