4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS AgentCore Runtimeで最小チャットエージェントアプリを構築してみた

Posted at

はじめに

この記事では、AWS Bedrock の AgentCore Runtime を使い、Python で簡単な AI エージェントを作成・ローカル確認・デプロイするまでの手順をまとめました。

※AWS 初心者なので色々と間違っている点などあるかもしれません...

作業前の環境

  • WSL2
  • Ubuntu24.04
  • AWS CLI が設定済み
  • Python 3.10 以上

ローカル環境準備

作業用ディレクトリに Python 仮想環境を作成し、必要なライブラリをインストールします。

pip install --upgrade pip
pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit

Pythonで最小チャットエージェント作成

プロジェクトディレクトリ直下にmy_agent.py を作成して以下のコードを記述します。

my_agent.py

from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent

app = BedrockAgentCoreApp()
agent = Agent()

@app.entrypoint
def invoke(payload: dict):
    user_message = payload.get("prompt", "Hello! How can I help you?")
    result = agent(user_message)
    return {"result": result.message}

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

依存関係はプロジェクトディレクトリ配下にrequirements.txt に記述します。

requirements.txt
bedrock-agentcore
strands-agents

ローカル環境でのテスト

サーバを起動します。

python my_agent.py

別ターミナルで確認してみて、以下のようにメッセージが返ってくればOK。

# bash
curl -X POST http://localhost:8080/invocations \
  -H "Content-Type: application/json" \
  -d '{"prompt":"こんにちは"}'

# response
{"result": "こんにちは!どうお手伝いできますか?"}

AgentCore Starter Toolkit の初期設定

下記コマンドよりAgentCore Starter Toolkitの初期設定を実行します。
質問事項はすべてEnterで設定。

agentcore configure -e my_agent.py -r ap-northeast-1

設定完了後に プロジェクトディレクトリ配下に.bedrock_agentcore.yaml が生成されます。

.bedrock_agentcore.yaml

default_agent: my_agent
agents:
  my_agent:
    name: my_agent
    entrypoint: /home/user/projects/xxxxxx/my_agent.py
    deployment_type: container
    runtime_type: null
    platform: linux/arm64
    container_runtime: docker
    source_path: /home/user/projects/xxxxxx
    aws:
      execution_role: arn:aws:iam::xxxxxxxx:role/AmazonBedrockAgentCoreSDKRuntime-ap-northeast-1-xxxxxx
      execution_role_auto_create: false
      account: xxxxxxxx
      region: ap-northeast-1
      ecr_repository: xxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/bedrock-agentcore-my_agent
      ecr_auto_create: false
      s3_path: null
      s3_auto_create: false
      network_configuration:
        network_mode: PUBLIC
        network_mode_config: null
      protocol_configuration:
        server_protocol: HTTP
      observability:
        enabled: true
      lifecycle_configuration:
        idle_runtime_session_timeout: null
        max_lifetime: null
    bedrock_agentcore:
      agent_id: my_agent-xxxxxx
      agent_arn: arn:aws:bedrock-agentcore:ap-northeast-1:xxxxxxxx:runtime/my_agent-xxxxxx
      agent_session_id: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    codebuild:
      project_name: bedrock-agentcore-my_agent-builder
      execution_role: arn:aws:iam::xxxxxxxx:role/AmazonBedrockAgentCoreSDKCodeBuild-ap-northeast-1-xxxxxx
      source_bucket: bedrock-agentcore-codebuild-sources-xxxxxxxx-ap-northeast-1
    memory:
      mode: STM_ONLY
      memory_id: my_agent_mem-xxxxxxx
      memory_arn: arn:aws:bedrock-agentcore:ap-northeast-1:xxxxxxxx:memory/my_agent_mem-xxxxxxx
      memory_name: my_agent_mem
      event_expiry_days: 30
      first_invoke_memory_check_done: true
      was_created_by_toolkit: false
    identity:
      credential_providers: []
      workload: null
    aws_jwt:
      enabled: false
      audiences: []
      signing_algorithm: ES384
      issuer_url: null
      duration_seconds: 300
    authorizer_configuration: null
    request_header_configuration: null
    oauth_configuration: null
    api_key_env_var_name: null
    api_key_credential_provider_name: null
    is_generated_by_agentcore_create: false

AgentCore Runtime へのデプロイ

下記コマンドよりデプロイを実行します。

agentcore deploy

ここでエラーが発生。

エラー内容
...

❌ Launch failed: An error occurred (ValidationException) when calling the CreateAgentRuntime operation: 
Access denied while validating ECR URI 
'xxxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/bedrock-agentcore-my_agent:latest'. 
The execution role requires permissions for ecr:GetAuthorizationToken, 
ecr:BatchGetImage, and ecr:GetDownloadUrlForLayer operations.

どうやらデプロイ時に以下2つのロールが作成されたが、Runtimeの実行ロールの権限不足らしい...


○デプロイ時に生成されたロール
  • AmazonBedrockAgentCoreSDKCodeBuild-ap-northeast-1-xxxxxx
  • AmazonBedrockAgentCoreSDKRuntime-ap-northeast-1-xxxxxx

Runtimeのロール AmazonBedrockAgentCoreSDKRuntime-xxxx に対して以下を付与した。
(今回は試しなのでフルアクセス権を付与)

# 用途:ECRにイメージをpushする
・ AmazonEC2ContainerRegistryFullAccess 
# 用途:CloudWatchでのログを出力する
・ CloudWatchLogsFullAccess
# 用途:Bedrockのモデル呼び出し
・ AmazonBedrockFullAccess

権限付与後に再度デプロイすると正常に Runtime が起動します。

Agent Details:
Agent Name: my_agent
Agent ARN: arn:aws:bedrock-agentcore:ap-northeast-1:xxxxxxx:runtime/my_agent-xxxxxxxx
ECR URI: xxxxxxx.dkr.ecr.ap-northeast-1.amazonaws.com/bedrock-agentcore-my_agent:latest
CodeBuild ID: bedrock-agentcore-my_agent-builder:xxxx

🚀 ARM64 container deployed to Bedrock AgentCore

CloudWatch Logs や GenAI Dashboard も確認可能です。

...


Runtime 上のエージェントを呼び出してみる

下記コマンドからRuntime上のエージェントの返答を確認します。

# bash
agentcore invoke '{"prompt": "Hello"}' 

#response
{"result": {"role": "assistant", "content": [{"text": "Hello! How can I help you today?}]}}

正常なレスポンスが返ってきたので構築完了。

デプロイ時のAgent ARNの値やポリシーの設定をすれば、最小限の環境でRuntime上のエージェントを使用できるみたいです!
ローカル環境と違ってログ管理や必要に応じてスケーリングも行ってくれるので頼りになるなと思いました。

ポイント

特にAWSのポリシー周りの設定がされているかを確認することが大事かと思います! 最初は自分のユーザ権限で全て実行できると勘違いしていて、ロールというものに気が付くのにかなり時間がかかりました...

感想

簡単なチャットエージェントの構築だけですが、無事動作確認まで完了できてよかったです!
今回初めてのAWSなのと、今まで簡単な対話でしかAIを触っていなかったので理解がかなり大変でした...

まだまだ分からない部分も多々あるので精進あるのみですね。 RuntimeはAgentCoreのうちの基礎基盤となるものなので、今後はGateWayやPolicy等のツールも確認していきたいです。

4
0
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?