27
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Strands Agents SDK×Bedrock AgentCore Runtimeで最先端のAIエージェント開発を楽しもう!

Last updated at Posted at 2025-07-16

この記事は人間が書きました。

こんにちは、ふくちと申します。

日本時間2025年7月17日、AWS Summit New York City 2025のキーノートがオンライン配信されていました。
Dr.Swamiからいくつも生成AI、とりわけAIエージェントのアップデートが発表され、界隈が大盛りあがりしていました。

詳しいアップデート内容はこちら↓を御覧ください。超絶わかりやすく纏めてくださってます!

そんな中でも目玉はやはり Amazon Bedrock AgentCore でしょう!

これは、任意のフレームワークやモデルを使用しているAIエージェントを迅速かつ安全に導入・運用できるようにするサービスセットです。

これまではLangChainやStrands Agents SDKなどを用いる場合、ECSやLambda上にデプロイしてアプリケーションを動かしていました。
ただ、その際には他のインフラ部分に幾つも気を配る必要がありました。例えば、セッション管理・メモリ・オブザーバビリティ・ツールとの連携など…

その面倒くさいインフラ構築・管理の部分を簡易的にしてくれるサービスとなっているようです。
これで開発者はアプリケーションロジックの実装へ注力できるようになり、よりビジネス的な価値をもたらすことに注力できます。

とはいえ、実際に使ってみないとよくわかりませんよね。
ということで、Strands Agents SDKを使ってAIエージェントを作り、AgentCoreを用いてサクッとデプロイするというところまでやってみました。

1.AIエージェントを作る

1.1 Strands Agents SDKでのエージェント作成

Strands Agents SDKはAgentCoreと同じくらいのタイミングでGAされた、AIエージェント作成用フレームワークの1つです。

(AWSが提供しているフレームワークなので、AWSサービスとの親和性は抜群だったのですが、AgentCoreのせいでおかげで、その優位性は失われてしまいました。お労しや…)

まず、さっくりAIエージェントを作っていきます。

terminal
# uvで仮想環境を作成し、プロジェクトを初期化
$ uv venv
$ source .venv/bin/activate
$ uv init

続いて、エージェントを作成します。たった3行でAIエージェントが作成できてしまいます。

my-strands-agent.py
from strands import Agent

# デフォルト設定でエージェントを定義
agent = Agent()

# エージェントへ質問
agent("Tell me about agentic AI")

1.2 AgentCore互換エージェントへ修正

ここから、4つの要素を追加してエージェントをAgentCore互換エージェントへ変化させます。

  1. ランタイムのインポート
  2. アプリの初期化
  3. 関数の修飾
  4. 実行コマンドの追加
my-strands-agent.py
from strands import Agent
+ from bedrock_agentcore.runtime import BedrockAgentCoreApp # 1.

+ app = BedrockAgentCoreApp() # 2.
agent = Agent()

+ @app.entrypoint # 3.
+ def invoke(payload):
+     """Process user input and return a response"""
+     user_message = payload.get("prompt", "Hello")
+     result = agent(user_message)
+     return str(result)

+ if __name__ == "__main__": # 4.
+     app.run()

1.3 ローカルでの動作確認

ここまで来たら必要なモジュールをインストールして、ローカルでテストを実行します。

terminal
$ uv pip install strands-agents bedrock-agentcore
 + bedrock-agentcore==0.1.0 

$ uv run my-strands-agent.py
INFO:     Started server process [10179]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit)

これでポート8080をリッスンするHTTPサーバーが起動しました。
別ターミナルから、このサーバーへアクセス確認します。

terminal
$ curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{"prompt": "Hello world!"}'

# 回答例
{"result":{"role":"assistant","content":[{"text":"Hello! It's nice to meet you! How are you doing today? Is there anything I can help you with?"}]}}%

※bedrock-agentcoreのバージョンは0.1.0以上を使用してください。
※私は0.0.1までしか用意されていないときに実行してImportErrorになりました…

2. 作ったエージェントをスターターツールキットでデプロイする

AgentCoreには、スターターツールキットなる便利なものが用意されています。
これを用いることで、簡単なパッケージ化およびAgentCore Runtimeへのデプロイが可能になります。

2.1 Dockerfileの作成

まずはパッケージ化もといDockerFileの作成です。
image.png

事前準備として、今回使用するECRリポジトリと、以下権限を持ったIAM実行ロールを予め環境にデプロイしておいてください。

IAMロールに付与する権限
AgentCore Runtime用ポリシー
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "ECRImageAccess",
            "Effect": "Allow",
            "Action": [
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ],
            "Resource": [
                "arn:aws:ecr:{{region}}:{{accountId}}:repository/{{repository-name}}"
            ]        
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:DescribeLogStreams",
                "logs:CreateLogGroup"
            ],
            "Resource": [
                "arn:aws:logs:{{region}}:{{accountId}}:log-group:/aws/bedrock-agentcore/runtimes/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:DescribeLogGroups"
            ],
            "Resource": [
                "arn:aws:logs:{{region}}:{{accountId}}:log-group:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:{{region}}:{{accountId}}: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:{{region}}:{{accountId}}:workload-identity-directory/default",
              "arn:aws:bedrock-agentcore:{{region}}:{{accountId}}: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:{{region}}:{{accountId}}:*"
            ]
        }
    ]
}
AgentCore Runtime 信頼ポリシー
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AssumeRolePolicy",
      "Effect": "Allow",
      "Principal": {
        "Service": "bedrock-agentcore.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
            "StringEquals": {
                "aws:SourceAccount": "{{accountId}}"
            },
            "ArnLike": {
                "aws:SourceArn": "arn:aws:bedrock-agentcore:{{region}}:{{accountId}}:*"
            }
       }
    }
  ]
}
      

ECRとIAMロールを作成したら、以下の構成でファイルを作成します。

agentcore/ #自分のルートディレクトリ名
├── my_strands_agents.py # メインとなるエージェントコード、上記で作成済み
├── requirements.txt # 必要な依存関係を記載
└── __init__.py # ディレクトリをPythonパッケージとして認識させるためのファイル、空でOK

メインとなるエージェントコード用ファイルの名前に「-(ハイフン)」を使うと、エラーになるようです。代わりにアンダースコアなどを使用してください。

requirements.txt
strands-agents
bedrock-agentcore

その後、Docker Desktopを立ち上げておきます。

agentcore configureコマンドを用いて、Dockerfileを作成していきます。

terminal
$ agentcore configure --entrypoint my_strands_agent.py -er arn:aws:iam::<AccountId>:role/<AgentCore用に作成したIAMロール名>
Configuring Bedrock AgentCore...
Entrypoint parsed: file=/path/to/agentcore/my_strands_agent.py, bedrock_agentcore_name=my_strands_agent                                                                    
Agent name: my_strands_agent

🏗️  ECR Repository
Press Enter to auto-create ECR repository, or provide ECR Repository URI to use existing
ECR Repository URI (or skip to auto-create): (先ほど作成したECRリポジトリのURI)
✓ Using existing ECR repository: (先ほど作成したECRリポジトリのURI)

🔍 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: my_strands_agent

Found credentials in shared credentials file: ~/.aws/credentials

Generated .dockerignore
Generated Dockerfile: /path/to/agentcore/Dockerfile
Generated .dockerignore: /path/to/agentcore/.dockerignore
Setting 'my_strands_agent' as default agent

╭───────────────────────────────────────────────────────────────────────────────────────────── Bedrock AgentCore Configured ─────────────────────────────────────────────────────────────────────────────────────────────╮
│ Configuration Summary                                                                                                                                                                                                  │
│                                                                                                                                                                                                                        │
│ Name: my_strands_agent                                                                                                                                                                                                 │
│ Runtime: Docker                                                                                                                                                                                                        │
│ Region: Region                                                                                                                                                                                                         │
│ Account: ************                                                                                                                                                                                                  │
│ Execution Role: 先ほど作成したIAMロールのARN                                                                                                                                                                       │
│ ECR: 先ほど作成したECRリポジトリ名                                                                                                                                                                            │
│ Authorization: IAM (default)                                                                                                                                                                                           │
│                                                                                                                                                                                                                        │
│ Configuration saved to: /path/to/agentcore/.bedrock_agentcore.yaml                                                                                                                                  │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

ここでディレクトリを確認すると、恐らくDockerfileや.dockerignoreなどができているはずです。

2.2 AgentCore Runtimeへデプロイする

いよいよ大詰め、デプロイ作業です。
先ほど作成したDockerfileなどを用いて作業を進めます。
image.png

とはいえ、ここでもスターターツールキットの agentcore launch を使用すれば、コマンド一発でデプロイ可能です。

$ agentcore launch
Launching Bedrock AgentCore (cloud mode)...
Launching Bedrock AgentCore agent 'my_strands_agent' to cloud

(略)

Docker image built: bedrock_agentcore-my_strands_agent:latest
Uploading to ECR...

(略)

Image pushed successfully
Image uploaded to ECR: (作成したECRリポジトリのURI)

Creating/updating agent...
Creating agent 'my_strands_agent' with image URI: (作成したECRリポジトリのURI)

Successfully created agent 'my_strands_agent' with ID: my_strands_agent-**********, ARN: arn:aws:bedrock-agentcore:<Region>:<AccountId>:runtime/my_strands_agent-**********

Agent endpoint: arn:aws:bedrock-agentcore:<Region>:<AccountId>:runtime/my_strands_agent-**********/runtime-endpoint/DEFAULT

╭────────────────────────────────────────────────────────────────────────────────────────────── Bedrock AgentCore Deployed ──────────────────────────────────────────────────────────────────────────────────────────────╮
│ Deployment Successful!                                                                                                                                                                                                 │
│                                                                                                                                                                                                                        │
│ Agent Name: my_strands_agent                                                                                                                                                                                           │
│                                                                                                                                                                                                                        │
│ 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/my_strands_agent-**********-DEFAULT                                                                                                                                                 │
│    /aws/bedrock-agentcore/runtimes/my_strands_agent-**********-DEFAULT/runtime-logs                                                                                                                                    │
│                                                                                                                                                                                                                        │
│ 💡 Tail logs with:                                                                                                                                                                                                     │
│    aws logs tail /aws/bedrock-agentcore/runtimes/my_strands_agent-**********-DEFAULT --follow                                                                                                                          │
│    aws logs tail /aws/bedrock-agentcore/runtimes/my_strands_agent-**********-DEFAULT --since 1h                                                                                                                        │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

ステータス確認コマンドはこちら。Runtimeだけでなく、エンドポイント・ログの状態も確認できます。

$  agentcore status

コンソール上でももちろん確認できます。
image.png

エージェントを呼び出します。

$ agentcore invoke '{"prompt": "Hello"}'

Response:
{
  "ResponseMetadata": {
    "RequestId": *****,
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "date": "Wed, 16 Jul 2025 20:04:06 GMT",
      "content-type": "application/json",
      "transfer-encoding": "chunked",
      "connection": "keep-alive",
      "x-amzn-requestid": *****,
      "baggage": *****,
      "x-amzn-bedrock-agentcore-runtime-session-id": *****,
      "x-amzn-trace-id": *****
    },
    "RetryAttempts": 0
  },
  "runtimeSessionId": *****,
  "traceId": *****,
  "baggage": *****,
  "contentType": "application/json",
  "statusCode": 200,
  "response": [
    "b'\"Hello! How are you doing today? Is there anything I can help you with?\\\\n\"'"
  ]
}

呼び出した後、CloudWatchのGen AI Observabilityを確認すると…
image.png

まとめ

ここで触った機能はAgentCoreサービスのほんの一部、はじめの一歩に過ぎません。
他のリソースについてもガンガン触っていこうと思います!

また、気になるお値段ですが、もちろんサーバーレスです。つまり使った分だけ課金です。

ただ、9月16日まではAgentCoreは無料で使えるそうです。今のうちに使い倒して、GAされて東京リージョンへ来たとき、即座にスタートダッシュできるようにしておきましょう!

参考

27
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?