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 | CDK | The preferred IaC provider |
ジェネレータ出力
Section titled “ジェネレータ出力”既存のPythonプロジェクトに以下のファイルが追加されます:
Directoryyour-project/
Directoryyour_module/
Directoryagent/(カスタム名指定時はそれを使用)
- __init__.py Pythonパッケージ初期化ファイル
- agent.py サンプルツール付きメインエージェント定義
- main.py Bedrock AgentCore Runtime用エントリーポイント
- agentcore_mcp_client.py 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デプロイ用汎用モジュール
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サーバーの利用”Bedrock AgentCore RuntimeにデプロイされたMCPサーバーからツールを追加できます。
py#mcp-server
またはts#mcp-server
ジェネレータで作成した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
ターゲットが設定され、ローカルでStrandsエージェントを起動できます:
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
でターゲットプラットフォーム用依存関係をインストール
エージェント固有のdocker
ターゲットも追加され:
- AgentCoreランタイム契約に準拠した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, ...]}*/
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オブザーバビリティドキュメントを参照。