3
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?

【StrandsAgents×Lambda×ECR】strands-agents-toolsがLambdaレイヤーに登録できないのでコンテナイメージ起動した

Last updated at Posted at 2025-09-12

LambdaでStrandsAgentsを起動した話は以下の記事で紹介しています。

Lambdaレイヤーにstrands-agents-tools追加できなくね?

単純に、Lambda関数内のpythonファイルでimport strands-agentsをするために、Lambdaレイヤーにstrands-agentsを追加しておくことは可能でした。
しかし、import strands-agents-toolsを実行するために、Lambdaレイヤーにstrands-agents-toolsを追加することができませんでした。

原因

原因は、容量が大きすぎることでした。

以下のコマンドを実行し、Zip化すると100MBくらいになります。これだとLambdaレイヤーには登録できないです。

$ pip install strands-agents-tools --target ./python --platform manylinux2014_x86_64 --only-binary=:all:

対策

どうしてもLambdaでstrands-agents-toolsを使いたい場合は、Dockerイメージを使用してLambda関数を起動するという方法を取るのが良いと思います。

ほな、やってみよ

1. AWS CLIの設定を見直し

$ aws configure

2. ファイルを用意

$ touch Dockerfile
$ lambda_function.py
$ requirements.txt

Dockerfileの内容

FROM public.ecr.aws/lambda/python:3.13

# 必要なファイルをコンテナにコピー
COPY requirements.txt ${LAMBDA_TASK_ROOT}
COPY lambda_function.py ${LAMBDA_TASK_ROOT}

# 依存関係のインストール
RUN pip install -r requirements.txt --target ${LAMBDA_TASK_ROOT}

# PYTHONPATHを設定してモジュールを確実に見つけられるようにする
ENV PYTHONPATH=${LAMBDA_TASK_ROOT}

# Lambdaハンドラーを指定
CMD ["lambda_function.lambda_handler"]

lambda_function.pyの内容

from strands import Agent, tool
from strands_tools import retrieve # Bedrockナレッジベースを検索するためのツール
import json

def lambda_handler(event, context):
    # Agent定義
    agent = Agent(
        tools=[retrieve],
        model="apac.anthropic.claude-3-7-sonnet-20250219-v1:0",
        system_prompt="あなたは優秀なAIアシスタントです。",
    )

    # Agentへリクエストを送信 & レスポンス取得
    message = "こんにちは!なんか返事してよ。"
    print(f"質問: {message}")

    print("回答:")
    response = agent(message)

    return {
        'statusCode': 200,
        'body': json.dumps({
            'response': str(response)  # str()で文字列に変換
        })
    }

requirements.txtの内容

strands-agents
strands-agents-tools

3. Dockerイメージをビルド

$ docker buildx build --platform linux/amd64 -t strands-lambda-function .

4. 変数を設定

$ export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) 
$ export AWS_REGION=ap-northeast-1

5. イメージにタグ付け

$ docker tag strands-lambda-function:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-lambda-function:latest

6. ECRにリポジトリを作成して、プッシュ

$ aws ecr create-repository --repository-name strands-lambda-function --image-scanning-configuration scanOnPush=true
$ docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-lambda-function:latest

これで、AWSマネジメントコンソールのECRにイメージがプッシュされているはずです。

7. ECRでリポジトリを確認

ECRでプライベートリポジトリを確認してみましょう。

image.png

strands-lambda-functionというリポジトリがあればOKです。

8. イメージのURIをコピー

アーティファクト・タイプがImage Indexとなっているものは、Lambdaのイメージとしては使えないものなので、除外します。サイズが0MBになっているものも除外します。

image.png

そうすると、コピーすべきURIは、キャプチャで言うと上から2番目になります。

9. Lambda関数を作成

「コンテナイメージ」を選択し、作成したイメージのURIを指定します。

スクリーンショット 2025-09-12 13.59.46.png

「関数の作成」をクリックしたときに「権限がない」というようなエラーが発生した場合、IAMでKMSのポリシーを変更する必要があります。
この場合、使用するIAMロールに以下のようなインラインポリシーを追加しておく必要があります。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "kms:Decrypt",
                "kms:CreateGrant",
                "kms:GenerateDataKey"
            ],
            "Resource": "*"
        }
    ]
}

8. テストを実行

テストを実行すると、エラーが出ずに実行完了すると思います。

Lambda関数を編集して再アップロード

Lambda関数の処理を編集したい場合は、以下のような手順で実行すると良いです。

1. Lambda関数の処理を変更

良きにはからって修正してください。

2. 以下のコマンドを実行

以下のコマンドを実行すると、ビルド・タグ付け・デプロイが一発で実行できます。(&&で繋げただけですが。)

$ docker buildx build --platform linux/amd64 -t strands-lambda-function . && export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) && export AWS_REGION=ap-northeast-1 && docker tag strands-lambda-function:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-lambda-function:latest && docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-lambda-function:latest

3. 新しいイメージをデプロイする

Lambda関数の画面から、ECRにデプロイしたイメージを指定します。

image.png

まとめ

AWS SAM を使用したら、ローカルでテストできるのでそっちと併用するのが良さそうですね。

以上

3
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
3
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?