Pythonストランドエージェント
AIエージェントをツール付きで構築するためのPython Strands Agentを生成し、オプションでAmazon Bedrock AgentCore Runtimeにデプロイします。
Strandsとは
Section titled “Strandsとは”Strandsは、AIエージェントを構築するための軽量で本番環境対応のPythonフレームワークです。主な特徴:
- 軽量でカスタマイズ可能:シンプルなエージェントループで邪魔になりません
- 本番環境対応:フルオブザーバビリティ、トレーシング、スケール対応のデプロイオプション
- モデル/プロバイダー非依存:様々なプロバイダーのモデルをサポート
- コミュニティ提供ツール:強力なコミュニティ製ツールセット
- マルチエージェント対応:エージェントチームや自律エージェントなどの高度な手法
- 柔軟なインタラクションモード:会話型、ストリーミング、非ストリーミング対応
Strandsエージェントの生成
Section titled “Strandsエージェントの生成”2つの方法でPython Strandsエージェントを生成できます:
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)
"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - py#strands-agent
- 必須パラメータを入力
- クリック
Generate
pnpm nx g @aws/nx-plugin:py#strands-agent
yarn nx g @aws/nx-plugin:py#strands-agent
npx nx g @aws/nx-plugin:py#strands-agent
bunx nx g @aws/nx-plugin:py#strands-agent
変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @aws/nx-plugin:py#strands-agent --dry-run
yarn nx g @aws/nx-plugin:py#strands-agent --dry-run
npx nx g @aws/nx-plugin:py#strands-agent --dry-run
bunx nx g @aws/nx-plugin:py#strands-agent --dry-run
パラメータ | 型 | デフォルト | 説明 |
---|---|---|---|
project 必須 | string | - | The project to add the Strands Agent to |
computeType | string | BedrockAgentCoreRuntime | The type of compute to host your Strands Agent. |
name | string | - | The name of your Strands Agent (default: agent) |
iacProvider | string | Inherit | The preferred IaC provider. By default this is inherited from your initial selection. |
ジェネレーターの出力
Section titled “ジェネレーターの出力”既存のPythonプロジェクトに以下のファイルが追加されます:
Directoryyour-project/
Directoryyour_module/
Directoryagent/(指定した場合はカスタム名)
- __init__.py Pythonパッケージ初期化ファイル
- agent.py サンプルツール付きメインエージェント定義
- main.py Bedrock AgentCore Runtime用エントリーポイント
- agentcore_mcp_client.py Bedrock AgentCore Runtime上のMCPサーバー呼び出し用クライアントファクトリ
- Dockerfile エージェントホスティング用Dockerfile(
computeType
がNone
の場合は生成されない)
- pyproject.toml Strands依存関係が追加された設定ファイル
- project.json エージェントサーブターゲットが追加された設定ファイル
インフラストラクチャ
Section titled “インフラストラクチャ”このジェネレータは選択した iacProvider
に基づいてInfrastructure as Codeを生成するため、packages/common
に関連するCDKコンストラクトまたはTerraformモジュールを含むプロジェクトを作成します。
共通のInfrastructure as Codeプロジェクトは以下の構造を持ちます:
Directorypackages/common/constructs
Directorysrc
Directoryapp/ プロジェクト/ジェネレータ固有のインフラストラクチャ用コンストラクト
- …
Directorycore/
app
内のコンストラクトで再利用される汎用コンストラクト- …
- index.ts
app
からコンストラクトをエクスポートするエントリーポイント
- project.json プロジェクトのビルドターゲットと設定
Directorypackages/common/terraform
Directorysrc
Directoryapp/ プロジェクト/ジェネレータ固有のインフラストラクチャ用Terraformモジュール
- …
Directorycore/
app
内のモジュールで再利用される汎用モジュール- …
- project.json プロジェクトのビルドターゲットと設定
Strandsエージェントのデプロイ用に以下のファイルが生成されます:
Directorypackages/common/constructs/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.ts エージェントデプロイ用CDKコンストラクト
- Dockerfile CDKコンストラクトで使用されるDockerfile
Directorycore
Directoryagent-core
- runtime.ts Bedrock AgentCore Runtimeデプロイ用汎用CDKコンストラクト
Directorypackages/common/terraform/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.tf エージェントデプロイ用Terraformモジュール
Directorycore
Directoryagent-core
- runtime.tf Bedrock AgentCore Runtimeデプロイ用汎用Terraformモジュール
Strandsエージェントの操作
Section titled “Strandsエージェントの操作”ツールの追加
Section titled “ツールの追加”ツールはAIエージェントがアクションを実行するために呼び出す関数です。Strandsフレームワークはデコレータベースのシンプルなアプローチを採用しています。
agent.py
ファイルに新しいツールを追加できます:
from strands import Agent, tool
@tooldef calculate_sum(numbers: list[int]) -> int: """数値リストの合計を計算""" return sum(numbers)
@tooldef get_weather(city: str) -> str: """都市の天気情報を取得""" # 天気API連携をここに実装 return f"{city}の天気:晴れ、25°C"
# エージェントにツールを追加agent = Agent( system_prompt="様々なツールにアクセスできる便利なアシスタントです。", tools=[calculate_sum, get_weather],)
Strandsフレームワークが自動的に処理する機能:
- 関数の型ヒントに基づく型検証
- ツール呼び出し用JSONスキーマ生成
- エラーハンドリングとレスポンスフォーマット
プリビルドツールの使用
Section titled “プリビルドツールの使用”strands-tools
パッケージで提供されるプリビルドツール:
from strands_tools import current_time, http_request, file_read
agent = Agent( system_prompt="便利なアシスタントです。", tools=[current_time, http_request, file_read],)
デフォルトではClaude 4 Sonnetを使用しますが、モデルプロバイダーをカスタマイズ可能。Strandsドキュメントのモデルプロバイダーを参照:
from strands import Agentfrom strands.models import BedrockModel
# BedrockModelの作成bedrock_model = BedrockModel( model_id="anthropic.claude-sonnet-4-20250514-v1:0", region_name="us-west-2", temperature=0.3,)
agent = Agent(model=bedrock_model)
MCPサーバーの利用
Section titled “MCPサーバーの利用”StrandsエージェントにMCPサーバーのツールを追加できます。
py#mcp-server
やts#mcp-server
ジェネレーター(またはBedrock AgentCore Runtime上でホストされた他サーバー)で作成したMCPサーバーを利用する場合、agentcore_mcp_client.py
にクライアントファクトリが生成されます。
agent.py
のget_agent
メソッドを更新してMCPクライアントを作成しツールを追加できます。IAM(SigV4)認証の例:
import osfrom contextlib import contextmanager
import boto3from strands import Agent
from .agentcore_mcp_client import AgentCoreMCPClient
# リージョンと認証情報の取得region = os.environ["AWS_REGION"]boto_session = boto3.Session(region_name=region)credentials = boto_session.get_credentials()
@contextmanagerdef get_agent(session_id: str): mcp_client = AgentCoreMCPClient.with_iam_auth( agent_runtime_arn=os.environ["MCP_AGENTCORE_RUNTIME_ARN"], credentials=credentials, region=region, session_id=session_id, )
with mcp_client: mcp_tools = mcp_client.list_tools_sync()
yield Agent( system_prompt="..." tools=[*mcp_tools], )
上記のIAM認証例では、インフラストラクチャで2つの設定が必要です:
- MCPサーバーのAgentCore Runtime ARN用環境変数の追加
- エージェントにMCPサーバー呼び出し権限の付与
import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
const agent = new MyProjectAgent(this, 'MyProjectAgent', { environment: { MCP_AGENTCORE_RUNTIME_ARN: mcpServer.agentCoreRuntime.arn, }, });
mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime); }}
# MCPサーバーmodule "my_project_mcp_server" { source = "../../common/terraform/src/app/mcp-servers/my-project-mcp-server"}
# エージェントmodule "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
env = { MCP_AGENTCORE_RUNTIME_ARN = module.my_project_mcp_server.agent_core_runtime_arn }
additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_mcp_server.agent_core_runtime_arn, "${module.my_project_mcp_server.agent_core_runtime_arn}/*" ] } ]}
Strandsエージェントの詳細な作成方法はStrandsドキュメントを参照してください。
Bedrock AgentCore Python SDK
Section titled “Bedrock AgentCore Python SDK”ジェネレーターはBedrock AgentCore Python SDKを設定し、AgentCore上のエージェントに必要なHTTP契約を管理します。
SDKの詳細はドキュメントを参照してください。
Strandsエージェントの実行
Section titled “Strandsエージェントの実行”ローカル開発
Section titled “ローカル開発”<your-agent-name>-serve
ターゲットが設定され、ローカルでの開発テストが可能です:
pnpm nx run your-project:agent-serve
yarn nx run your-project:agent-serve
npx nx run your-project:agent-serve
bunx nx run your-project:agent-serve
このコマンドはBedrock AgentCore Python SDKを使用してエージェントを起動します。
Bedrock AgentCore Runtimeへのデプロイ
Section titled “Bedrock AgentCore Runtimeへのデプロイ”インフラストラクチャ即コード
Section titled “インフラストラクチャ即コード”computeType
にBedrockAgentCoreRuntime
を選択した場合、関連するCDK/Terraformインフラストラクチャが生成され、Amazon Bedrock AgentCore Runtimeにデプロイできます。
デフォルトで<ProjectName>Agent
という名前のCDKコンストラクトが生成されます:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // スタックにエージェントを追加 const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Bedrockモデル呼び出し権限の付与 agent.agentCoreRuntime.role.addToPolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], resources: ['arn:aws:bedrock:*::foundation-model/*'], }), ); }}
デフォルトで<ProjectName>-agent
という名前のTerraformモジュールが生成されます:
# エージェントmodule "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] Resource = [ "arn:aws:bedrock:*::foundation-model/*" ] } ]}
バンドルとDockerターゲット
Section titled “バンドルとDockerターゲット”Bedrock AgentCore Runtime向けビルド用にbundle
ターゲットが追加されます:
uv export
で依存関係をrequirements.txt
にエクスポートuv pip install
でターゲットプラットフォーム(aarch64-manylinux2014
)向け依存関係をインストール
エージェント固有のdocker
ターゲットも追加され:
- AgentCore runtime契約に準拠したDockerイメージをビルド
デフォルトでIAM認証が使用されます:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}
// 呼び出し権限の付与例agent.agentCoreRuntime.grantInvoke(lambdaFunction);
# エージェントmodule "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"}
# 呼び出しポリシー例{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}
Cognito JWT認証
Section titled “Cognito JWT認証”Cognito認証の設定例:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const userPool = new UserPool(this, 'UserPool'); const client = userPool.addClient('Client', { authFlows: { userPassword: true, }, });
new MyProjectAgent(this, 'MyProjectAgent', { authorizerConfiguration: { customJwtAuthorizer: { discoveryUrl: `https://cognito-idp.${Stack.of(userPool).region}.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`, allowedClients: [client.userPoolClientId], }, }, }); }}
locals { aws_region = data.aws_region.current.name user_pool_id = "xxx" user_pool_client_ids = ["yyy"]}
module "agent_core_runtime" { source = "../../../core/agent-core" agent_runtime_name = "MyProjectAgent" docker_image_tag = "my-scope-my-project-agent:latest" server_protocol = "HTTP" customJWTAuthorizer = { discoveryUrl = "https://cognito-idp.${local.aws_region}.amazonaws.com/${local.user_pool_id}/.well-known/openid-configuration", allowedClients = local.user_pool_client_ids } # ...その他の設定}
オブザーバビリティ
Section titled “オブザーバビリティ”AWS Distro for Open Telemetry(ADOT)を使用したオブザーバビリティがDockerfile
の自動計装で設定されます。
トレースはCloudWatchコンソールの「GenAI Observability」から確認可能です。Transaction Searchの有効化が必要です。
詳細はAgentCoreオブザーバビリティドキュメントを参照してください。