Skip to content

Pythonストランドエージェント

AIエージェントを構築するためのPython Strands Agentを生成し、オプションでAmazon Bedrock AgentCore Runtimeにデプロイできます。

Strandsは、AIエージェントを構築するための軽量でプロダクションレディなPythonフレームワークです。主な特徴:

  • 軽量でカスタマイズ可能: シンプルなエージェントループで邪魔にならない設計
  • プロダクションレディ: 完全なオブザーバビリティ、トレーシング、スケール対応のデプロイオプション
  • モデル/プロバイダー中立: 様々なプロバイダーのモデルをサポート
  • コミュニティ駆動のツール: 強力なコミュニティ提供ツールセット
  • マルチエージェントサポート: エージェントチームや自律エージェントなどの高度な手法
  • 柔軟なインタラクションモード: 会話型、ストリーミング/非ストリーミング対応

2つの方法でPython Strandsエージェントを生成できます:

  1. インストール Nx Console VSCode Plugin まだインストールしていない場合
  2. VSCodeでNxコンソールを開く
  3. クリック Generate (UI) "Common Nx Commands"セクションで
  4. 検索 @aws/nx-plugin - py#strands-agent
  5. 必須パラメータを入力
    • クリック Generate
    パラメータ デフォルト 説明
    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

    既存のPythonプロジェクトに以下のファイルが追加されます:

    • Directoryyour-project/
      • Directoryyour_module/
        • Directoryagent/(カスタム名指定時はそれを使用)
          • __init__.py Pythonパッケージ初期化ファイル
          • agent.py サンプルツール付きメインエージェント定義
          • main.py Bedrock AgentCore Runtime用エントリーポイント
          • agentcore_mcp_client.py MCPサーバー呼び出し用クライアントファクトリ
          • Dockerfile エージェントホスティング用Dockerfile(computeTypeNoneの場合は生成されない)
      • pyproject.toml Strands依存関係が追加
      • project.json エージェントサーブターゲットが追加

    このジェネレータは選択した iacProvider に基づいてInfrastructure as Codeを生成するため、packages/common に関連するCDKコンストラクトまたはTerraformモジュールを含むプロジェクトを作成します。

    共通のInfrastructure as Codeプロジェクトは以下の構造を持ちます:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ プロジェクト/ジェネレータ固有のインフラストラクチャ用コンストラクト
        • Directorycore/ app 内のコンストラクトで再利用される汎用コンストラクト
        • index.ts 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コンストラクト

    ツールはAIエージェントが操作を実行するために呼び出す関数です。Strandsフレームワークはデコレータベースのツール定義を採用しています。

    agent.pyファイルに新しいツールを追加できます:

    from strands import Agent, tool
    @tool
    def calculate_sum(numbers: list[int]) -> int:
    """数値リストの合計を計算"""
    return sum(numbers)
    @tool
    def get_weather(city: str) -> str:
    """都市の天気情報を取得"""
    # ここに天気APIの統合を実装
    return f"{city}の天気:晴れ、25°C"
    # エージェントにツールを追加
    agent = Agent(
    system_prompt="様々なツールにアクセスできるヘルプフルアシスタントです。",
    tools=[calculate_sum, get_weather],
    )

    Strandsフレームワークが自動的に処理する機能:

    • 関数の型ヒントに基づく型検証
    • ツール呼び出し用JSONスキーマ生成
    • エラーハンドリングとレスポンスフォーマット

    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 Agent
    from 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)

    Bedrock AgentCore RuntimeにデプロイされたMCPサーバーからツールを追加できます。

    py#mcp-serverまたはts#mcp-serverジェネレータで作成したMCPサーバー(または他でホストされたもの)を使用する場合、agentcore_mcp_client.pyにクライアントファクトリが生成されます。

    agent.pyget_agentメソッドを更新してMCPクライアントを作成しツールを追加。IAM(SigV4)認証の例:

    agent.py
    import os
    from contextlib import contextmanager
    import boto3
    from 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()
    @contextmanager
    def 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つの設定が必要です:

    1. MCPサーバーのAgentCore Runtime ARN用環境変数の追加
    2. エージェントに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);
    }
    }

    Strandsエージェント開発の詳細はStrandsドキュメントを参照。

    ジェネレータはBedrock AgentCore Python SDKを設定し、AgentCore上のエージェントに必要なHTTP契約を管理します。

    SDKの詳細はドキュメントを参照。

    <your-agent-name>-serveターゲットが設定され、ローカルでStrandsエージェントを起動できます:

    Terminal window
    pnpm nx run your-project:agent-serve

    このコマンドはBedrock AgentCore Python SDKを使用してエージェントを実行します。

    Bedrock AgentCore Runtimeへのデプロイ

    Section titled “Bedrock AgentCore Runtimeへのデプロイ”

    インフラストラクチャ即コード

    Section titled “インフラストラクチャ即コード”

    computeTypeBedrockAgentCoreRuntimeを選択した場合、関連する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/*'],
    }),
    );
    }
    }

    Bedrock AgentCore Runtime用ビルドのためにbundleターゲットが追加され:

    • uv exportで依存関係をrequirements.txtにエクスポート
    • uv pip installでターゲットプラットフォーム用依存関係をインストール

    エージェント固有の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);

    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],
    },
    },
    });
    }
    }

    AWS Distro for Open Telemetry(ADOT)を使用したオブザーバビリティがDockerfileの自動計装で設定されます。

    トレースはCloudWatchコンソールの「GenAI Observability」で確認可能。Transaction Searchの有効化が必要です。

    詳細はAgentCoreオブザーバビリティドキュメントを参照。