Strands Agents を任意のリージョン・推論モデルで利用する
はじめに
プログデンスの圓佛です。 先日、AWS が GitHub で Strands Agents を公開しました。 Strands Agents については AWS Blog で紹介されています。
この記事中で Strands Agents は「Strands Agents は、わずか数行のコードで AI エージェントを構築・実行するモデル駆動型アプローチを採用したオープンソース SDK です。」と紹介されています。
Strands Agents には Python SDK も用意されており、デフォルトで us-west-2 の Claude Sonnet 3.7 を利用します。 その為、Strands Agents を利用するには事前に Amazon Bedrock で us-west-2 の Claude Sonnet 3.7 を有効化しておく必要があります。 今回はこれを変更し、任意のリージョン・別の推論モデルを利用する方法について説明します。
Strands Agents のソースコードでデフォルトリージョン・推論モデルを確認する
Strands Agents がデフォルトで利用するリージョン・推論モデルは sdk-python/src/strands/models/bedrock.py で定義されているようです。 デフォルトの推論モデルは 23 行目 で以下のように定義されています。
DEFAULT_BEDROCK_MODEL_ID = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"
デフォルトのリージョンは 113 行目 で定義されています。
session = boto_session or boto3.Session(
region_name=region_name or os.getenv("AWS_REGION") or "us-west-2",
)
リージョン・推論モデルを指定せずに実行する
試しに Strands Agents のサンプルコードを写経してみます。 作業用ディレクトリを作成したら Python の仮想環境を作成・有効化します。
mkdir my-strands-agents/
cd my-strands-agents/
python -m venv .venv
source .venv/bin/activate
Python の仮想環境を有効化したら strands-agents と strands-agents-tools をインストールします。 今回は strands-agents 0.1.5 と strands-agents-tools 0.1.4 がインストールされました。
pip install strands-agents strands-agents-tools
Strands Agents の Quick Start に掲載されているサンプルコードは以下です。 今回はこのサンプルコードを sample.py
という名前で保存しました。
from strands import Agent
from strands_tools import calculator
agent = Agent(tools=[calculator])
agent("What is the square root of 1764")
これを実行してみます。 標準出力 / 標準エラー出力をバッファリングさせずに実行する為、-u
オプションを指定します。 しかし、エラーになってしまいました。
% python -u sample.py
…
botocore.errorfactory.AccessDeniedException: An error occurred (AccessDeniedException) when calling the ConverseStream operation: You don't have access to the model with the specified model ID.
このエラーは「今回、利用している AWS アカウントでは Strands Agents がデフォルトで利用する us-west-2 の Claude Sonnet 3.7 を Bedrock で有効化していない」為に発生しています。 試しに Claude Sonnet 3.7 を有効化済みである us-east-1 を環境変数で指定すると正常に実行出来ます。
% AWS_REGION=us-east-1 python -u sample.py
I'll help you find the square root of 1764.
Tool #1: calculator
The square root of 1764 is 42.
任意のリージョン・推論モデルを指定して実行する
サンプルコードを以下の方針で変更します。
- 推論モデルは Amazon Nova を利用する
- 東京リージョン (
ap-northeast-1
) を利用する
修正後のサンプルコードは以下です。
from strands import Agent
from strands.models import BedrockModel
from strands_tools import calculator
model = BedrockModel(
model_id="apac.amazon.nova-micro-v1:0",
region_name="ap-northeast-1",
)
agent = Agent(model=model, tools=[calculator])
agent("What is the square root of 1764")
実行結果は以下の通りです。 リージョンを指定していませんが、正常に実行されています。
% python -u sample.py
<thinking> To find the square root of 1764, I can use the calculator tool with the "evaluate" mode. The expression to evaluate will be "sqrt(1764)". </thinking>
Tool #1: calculator
The square root of 1764 is 42.