はじめに
日本時間 7/16(水) の AWS Summit New York にて、Amazon Bedrock AgentCore の発表がありました。
翌日以降、SNS や社内 Slack などでも盛り上がっているわけですが、特に私は AWS Summit New York に注目していなかったこともあってなんとなく乗り遅れてしまって2週間ほど経過している今日この頃です。
(AWS Summit New York の直前に発表のあった Kiro は発表直後にインストールしてちょっと触ったんですが、独自のIDEという点で自分の中ではかなり使いにくい印象をもってしまっていて深くのめりこめていないのが正直なところです。。)
今回はそんな私のような「Amazon Bedrock AgentCore に乗り遅れている自覚のある人」にとって、5分で後れを取り戻せる記事を書こうと思います。
といっても、まだ東京リージョンでも使えないプレビュー段階なんで、この記事を開いている時点で乗り遅れていることなんてないと思いますけどね😉
.....もうここまでで30秒くらい?
starter toolkit を利用した最速 Agent Runtime 構築
百聞は一見に如かず
百見は一触にしかず 1
時間もないので早速 Agent Runtime を構築していきましょう!w
Amazon Bedrock AgentCore とはなにか?という体系的な情報は公式ドキュメントや他の方の記事にまとまっているので、そちらをご参照ください。
今回は入門ということで、 Amazon Bedrock AgentCore の主要な構成要素の1つである
Agent Runtime を構築していきます。
最速で駆け抜けるので python や AWS 等の前提知識については触れませんが(ごめんなさい)、もし手元に AWS アカウントがある方はぜひ一緒に構築しましょう!
starter toolkit という便利なスターターキットが用意されているので今回はこれを使います。
動作環境
OS: Ubuntu 24.04.2 LTS (WSL2)
Python: 3.12.3
AWS CLI: 2.27.20
Docker: 27.5.1
事前準備
IAMロール
Agent Runtime の実行ロールを先に用意しておく必要があります。Lambda の実行ロールのようなものですね。詳細は以下をご参照ください。
今回は AmazonBedrockAgentCoreRuntimeExampleRole
という名前でロールを作ります。
AWS CLIを利用したIAMロールの作成
# リージョンは us-east-1 を指定する。執筆時点では US East (N. Virginia), US West (Oregon), Europe (Frankfurt), Asia Pacific (Sydney) の4つのリージョンで展開されている。
$ export AWS_REGION=us-east-1
# アカウントIDの取得
$ export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
# 信頼関係
$ cat > agentcore-runtime-trust-policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "bedrock-agentcore.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
# ポリシー
$ cat > agentcore-runtime-execution-policy.json << EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ECRImageAccess",
"Effect": "Allow",
"Action": [
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"
],
"Resource": [
"arn:aws:ecr:${AWS_REGION}:${AWS_ACCOUNT_ID}:repository/*"
]
},
{
"Effect": "Allow",
"Action": [
"logs:DescribeLogStreams",
"logs:CreateLogGroup"
],
"Resource": [
"arn:aws:logs:${AWS_REGION}:${AWS_ACCOUNT_ID}:log-group:/aws/bedrock-agentcore/runtimes/*"
]
},
{
"Effect": "Allow",
"Action": [
"logs:DescribeLogGroups"
],
"Resource": [
"arn:aws:logs:${AWS_REGION}:${AWS_ACCOUNT_ID}:log-group:*"
]
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:${AWS_REGION}:${AWS_ACCOUNT_ID}:log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*"
]
},
{
"Sid": "ECRTokenAccess",
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets"
],
"Resource": [ "*" ]
},
{
"Effect": "Allow",
"Resource": "*",
"Action": "cloudwatch:PutMetricData",
"Condition": {
"StringEquals": {
"cloudwatch:namespace": "bedrock-agentcore"
}
}
},
{
"Sid": "GetAgentAccessToken",
"Effect": "Allow",
"Action": [
"bedrock-agentcore:GetWorkloadAccessToken",
"bedrock-agentcore:GetWorkloadAccessTokenForJWT",
"bedrock-agentcore:GetWorkloadAccessTokenForUserId"
],
"Resource": [
"arn:aws:bedrock-agentcore:${AWS_REGION}:${AWS_ACCOUNT_ID}:workload-identity-directory/default",
"arn:aws:bedrock-agentcore:${AWS_REGION}:${AWS_ACCOUNT_ID}:workload-identity-directory/default/workload-identity/agentName-*"
]
},
{"Sid": "BedrockModelInvocation",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:*::foundation-model/*",
"arn:aws:bedrock:${AWS_REGION}:${AWS_ACCOUNT_ID}:*"
]
}
]
}
EOF
# IAMロールを作成
$ aws iam create-role \
--role-name AmazonBedrockAgentCoreRuntimeExampleRole \
--assume-role-policy-document file://agentcore-runtime-trust-policy.json
# IAMポリシーを作成
$ aws iam create-policy \
--policy-name BedrockAgentCorePolicy \
--policy-document file://agentcore-runtime-execution-policy.json
# ロールにポリシーをアタッチ
$ aws iam attach-role-policy \
--role-name AmazonBedrockAgentCoreRuntimeExampleRole \
--policy-arn arn:aws:iam::${AWS_ACCOUNT_ID}:policy/BedrockAgentCorePolicy
デプロイするソースの用意
AgentCore Runtime のデプロイは ECR にプッシュされた Docker イメージをもとに行います。まずはその Docker イメージを作成するのに必要なファイルを用意します。
# ライブラリのインストール
$ pip install bedrock-agentcore-starter-toolkit bedrock-agentcore
# メインファイルを作成
$ cat > agent_example.py << 'EOF'
from strands import Agent
from bedrock_agentcore.runtime import BedrockAgentCoreApp
agent = Agent()
app = BedrockAgentCoreApp()
@app.entrypoint
def invoke(payload):
"""Process user input and return a response"""
user_message = payload.get("prompt", "Hello")
response = agent(user_message)
return str(response) # response should be json serializable
if __name__ == "__main__":
app.run()
EOF
# requirements.txt を作成
$ cat > requirements.txt << 'EOF'
strands-agents
bedrock-agentcore
EOF
デプロイ用の設定ファイルを生成
starter-toolkit には agentcore
という色々な事をよしなにやってくれる便利なコマンドが用意されています。
agentcore configure
でデプロイに必要なファイルを生成します。
$ agentcore configure --entrypoint agent_example.py -er AmazonBedrockAgentCoreRuntimeExampleRole
いくつか質問されますが、すべてデフォルト値でOKです。
(ECR とか requirements.txt とか認可どうする?って聞かれています)
Configuring Bedrock AgentCore...
Entrypoint parsed: file=/home/inoue_d/git/bedrock-agent-core-sample/starter-toolkit/agent_example.py, bedrock_agentcore_name=agent_example
Agent name: agent_example
🏗️ ECR Repository
Press Enter to auto-create ECR repository, or provide ECR Repository URI to use existing
ECR Repository URI (or press Enter to auto-create):
✓ Will auto-create ECR repository
🔍 Detected dependency file: requirements.txt
Press Enter to use this file, or type a different path (use Tab for autocomplete):
Path or Press Enter to use detected dependency file:
✓ Using detected file: requirements.txt
🔐 Authorization Configuration
By default, Bedrock AgentCore uses IAM authorization.
Configure OAuth authorizer instead? (yes/no) [no]:
✓ Using default IAM authorization
Configuring BedrockAgentCore agent: agent_example
Bedrock AgentCore Configured
と表示されたら成功です!
╭───────────────────────────────────── Bedrock AgentCore Configured ──────────────────────────────────────────╮
│ Configuration Summary │
│ │
│ Name: agent_example │
│ Runtime: Docker │
│ Region: us-east-1 │
│ Account: {aws-account-id} │
│ Execution Role: arn:aws:iam::{aws-account-id}:role/AmazonBedrockAgentCoreRuntimeExampleRole │
│ ECR: Auto-create │
│ Authorization: IAM (default) │
│ │
│ Configuration saved to: /home/inoue_d/git/bedrock-agent-core-sample/starter-toolkit/.bedrock_agentcore.yaml │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
(少しお時間ある方向け)
agentcore configure
の実行により以下のファイルが自動で生成されます。面白いのでぜひ中身を確認してみてください。
-
.bedrock_agentcore.yaml
AgentCore Runtime の設定が記述された yaml ファイル -
Dockerfile
イメージをビルドするために必要な情報が記述された Docker ファイル -
.dockerignore
Docker イメージ作成時に無視するファイルやディレクトリが記載されたファイル
デプロイ
デプロイの用意が整いました!それではデプロイしていきましょう。
$ agentcore launch
実行すると
- ECR repository の作成
- Docker イメージのビルド
- ECR への Push
- AgentCore Runtime
をすべて一括で行ってくれます。
Launching Bedrock AgentCore (cloud mode)...
Launching Bedrock AgentCore agent 'agent_example' to cloud
⠴ Launching Bedrock AgentCore...Docker image built: bedrock_agentcore-agent_example:latest
Using execution role from config: arn:aws:iam::{aws-account-id}:role/AmazonBedrockAgentCoreRuntimeExampleRole
⠴ Launching Bedrock AgentCore...✅ Execution role validation passed: arn:aws:iam::{aws-account-id}:role/AmazonBedrockAgentCoreRuntimeExampleRole
Uploading to ECR...
⠦ Launching Bedrock AgentCore...Getting or creating ECR repository for agent: agent_example
Repository doesn't exist, creating new ECR repository: bedrock-agentcore-agent_example
⠦ Launching Bedrock AgentCore...✅ ECR repository available: {aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example
⠸ Launching Bedrock AgentCore...Authenticating with registry...
⠙ Launching Bedrock AgentCore...Registry authentication successful
Tagging image: bedrock_agentcore-agent_example:latest -> {aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example:latest
⠹ Launching Bedrock AgentCore...Pushing image to registry...
⠙ Launching Bedrock AgentCore...The push refers to repository [{aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example]
4634c3a3dd1b: Pushed
3c282a4360cb: Pushed
610e525cd9e7: Pushed
1109b1544f61: Pushed
a0907917b100: Pushed
012c0910b84d: Pushed
05ed7b2bcaa5: Pushed
d74514903961: Pushed
e26286284f6e: Pushed
dd97e58b4e81: Pushed
⠏ Launching Bedrock AgentCore...latest: digest: sha256:62617e38106b1a9e29c5f3c92d47096b031ea5980409203f734fe1fe90002faf size: 2413
⠋ Launching Bedrock AgentCore...Image pushed successfully
Image uploaded to ECR: {aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example
Deploying to Bedrock AgentCore...
⠼ Launching Bedrock AgentCore...✅ Agent created/updated: arn:aws:bedrock-agentcore:us-east-1:{aws-account-id}:runtime/agent_example-nFjVI0Gzd4
Polling for endpoint to be ready...
⠧ Launching Bedrock AgentCore...Agent endpoint: arn:aws:bedrock-agentcore:us-east-1:{aws-account-id}:runtime/agent_example-nFjVI0Gzd4/runtime-endpoint/DEFAULT
✓ Image pushed to ECR: {aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example:latest
Deployment Successful!
が表示されたら成功です!
╭──────────────────────────────── Bedrock AgentCore Deployed ──────────────────────────────────╮
│ Deployment Successful! │
│ │
│ Agent Name: agent_example │
│ Agent ARN: arn:aws:bedrock-agentcore:us-east-1:{aws-account-id}:runtime/agent_example-nFjVI0Gzd4 │
│ ECR URI: {aws-account-id}.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-agent_example │
│ │
│ You can now check the status of your Bedrock AgentCore endpoint with: │
│ agentcore status │
│ │
│ You can now invoke your Bedrock AgentCore endpoint with: │
│ agentcore invoke '{"prompt": "Hello"}' │
│ │
│ 📋 Agent logs available at: │
│ /aws/bedrock-agentcore/runtimes/agent_example-nFjVI0Gzd4-DEFAULT │
│ /aws/bedrock-agentcore/runtimes/agent_example-nFjVI0Gzd4-DEFAULT/runtime-logs │
│ │
│ 💡 Tail logs with: │
│ aws logs tail /aws/bedrock-agentcore/runtimes/agent_example-nFjVI0Gzd4-DEFAULT --follow │
│ aws logs tail /aws/bedrock-agentcore/runtimes/agent_example-nFjVI0Gzd4-DEFAULT --since 1h │
╰──────────────────────────────────────────────────────────────────────────────────────────────╯
Agent Runtime の一覧にも作成した Runtime agent が表示されていると思います。
Agent の呼び出し
これでようやく構築が完了しました。早速呼び出してみましょう。
$ agentcore invoke '{"prompt": "こんにちは。現在「まだ間に合う!5分で出来る Amazon Bedrock AgentCore 入門」という記事をもとに、あなたをデプロイしました。ようやく今に至るのですが、間に合っていたと思いますか??"}'
Response:
こんにちは!とても興味深い質問ですね😊
「まだ間に合う!5分で出来る」というタイトルの記事を使って私をデプロイしていただいたとのことですが、実際のところ、Amazon Bedrock Agent Coreのセットアップは思ったより時間がかかることが多いんですよね。
IAMロールの設定、エージェントの作成、テスト、デバッグなど、初回セットアップでは5分を超えてしまうことがほとんどだと思います。特に:権限周りでつまずいたり
エージェントの応答をテストして調整したり
思わぬエラーで調べ物をしたりといったことがあると、あっという間に時間は過ぎてしまいます。
でも「ようやく今に至る」ということは、最終的に成功されたということですよね!それなら十分「間に合った」と言えるのではないでしょうか。技術的な挑戦では、完了までの時間よりも「最終的にやり遂げること」の方が重要だと思います。
お疲れさまでした!何かお手伝いできることがあれば、お気軽にお声かけください。
無事に呼び出すことが出来ました!感覚としては Lambda を呼び出しているような感覚に近いですね。
さいごに
いかがでしたでしょうか。ここまで5分以上かかってしまった人はごめんなさいmm
エージェントの言う通り「最終的にやり遂げること」が出来ているのであれば何よりです。もしエラーなどで詰まるようなことがあれば、コメントでご質問ください。
Amazon Bedrock AgentCore 入門 と銘打っておきながら starter toolkit を使って Agent Runtime を構築しただけですが、十分入門出来たのではないかと思います。
本当はもう少し深掘って
「デフォルトではモデルは何が呼ばれているのか?どのモデルが対応しているのか?」
「Runtimeのメモリは?タイムアウトはある?」
「Agentのメモリは設定できる?どこに保存される?」
といった詳細も書きたかったのですが、到底5分では終わらない内容になったのでまた別の記事にでもしたいと思います🤗
最後までお読みいただき、ありがとうございました!
参考記事
-
範馬勇次郎の言葉より引用 今の時代に大切にしたい「百見は一触にしかず」のアナログ精神 ↩