TypeScript Strands エージェント
TypeScript Strands Agent を生成し、ツールを使用したAIエージェントを構築します。オプションで Amazon Bedrock AgentCore Runtime にデプロイできます。このジェネレーターは、WebSocket 上の tRPC を使用して、AgentCore の双方向ストリーミングサポートを活用し、リアルタイムで型安全な通信を実現します。
Strands とは?
Section titled “Strands とは?”Strands は、AIエージェントを構築するための軽量なフレームワークです。主な機能は次のとおりです:
- 軽量でカスタマイズ可能: シンプルなエージェントループで邪魔にならない
- 本番環境対応: 完全な可観測性、トレーシング、スケールのためのデプロイオプション
- モデルとプロバイダーに依存しない: さまざまなプロバイダーの多くの異なるモデルをサポート
- コミュニティ主導のツール: コミュニティが提供する強力なツールセット
- マルチエージェントサポート: エージェントチームや自律エージェントなどの高度な技術
- 柔軟な対話モード: 会話、ストリーミング、非ストリーミングサポート
Strands Agent の生成
Section titled “Strands Agent の生成”TypeScript Strands Agent は2つの方法で生成できます:
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - ts#strands-agent - 必須パラメータを入力
- クリック
Generate
pnpm nx g @aws/nx-plugin:ts#strands-agentyarn nx g @aws/nx-plugin:ts#strands-agentnpx nx g @aws/nx-plugin:ts#strands-agentbunx nx g @aws/nx-plugin:ts#strands-agent変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @aws/nx-plugin:ts#strands-agent --dry-runyarn nx g @aws/nx-plugin:ts#strands-agent --dry-runnpx nx g @aws/nx-plugin:ts#strands-agent --dry-runbunx nx g @aws/nx-plugin:ts#strands-agent --dry-run| パラメータ | 型 | デフォルト | 説明 |
|---|---|---|---|
| project 必須 | string | - | Strands Agentを追加するプロジェクト |
| computeType | string | BedrockAgentCoreRuntime | Strands Agentをホストするコンピュートのタイプ |
| name | string | - | Strands Agentの名前(デフォルト: agent) |
| auth | string | IAM | Strands Agentとの認証に使用する方法。IAM(デフォルト)またはCognitoから選択します。 |
| iacProvider | string | Inherit | 優先するIaCプロバイダー。デフォルトでは初期選択から継承されます。 |
ジェネレーター出力
Section titled “ジェネレーター出力”ジェネレーターは、既存の TypeScript プロジェクトに次のファイルを追加します:
Directoryyour-project/
Directorysrc/
Directoryagent/ (指定した場合はカスタム名)
- index.ts Bedrock AgentCore Runtime のエントリーポイント
- init.ts tRPC の初期化
- router.ts エージェントプロシージャを含む tRPC ルーター
- agent.ts サンプルツールを含むメインエージェント定義
- client.ts エージェントを呼び出すための提供されたクライアント
- agent-core-trpc-client.ts AgentCore Runtime 上のエージェントに接続するためのクライアントファクトリー
- Dockerfile エージェントをホストするためのエントリーポイント (
computeTypeがNoneに設定されている場合は除外)
- package.json Strands 依存関係で更新
- project.json エージェント serve ターゲットで更新
インフラストラクチャ
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 Agent をデプロイするために、次のファイルが生成されます:
Directorypackages/common/constructs/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.ts エージェントをデプロイするための CDK コンストラクト
- Dockerfile CDK コンストラクトで使用されるパススルー docker ファイル
Directorypackages/common/terraform/src
Directoryapp
Directoryagents
Directory<project-name>
- <project-name>.tf エージェントをデプロイするためのモジュール
Directorycore
Directoryagent-core
- runtime.tf Bedrock AgentCore Runtime にデプロイするための汎用モジュール
Strands Agent の操作
Section titled “Strands Agent の操作”WebSocket 上の tRPC
Section titled “WebSocket 上の tRPC”TypeScript Strands Agent は、WebSocket 上の tRPC を使用し、AgentCore の双方向ストリーミングサポートを活用して、クライアントとエージェント間のリアルタイムで型安全な通信を実現します。
tRPC は WebSocket 上で Query、Mutation、Subscription プロシージャをサポートしているため、任意の数のプロシージャを定義できます。デフォルトでは、router.ts に invoke という名前の単一のサブスクリプションプロシージャが定義されています。
ツールの追加
Section titled “ツールの追加”ツールは、AIエージェントがアクションを実行するために呼び出すことができる関数です。agent.ts ファイルに新しいツールを追加できます:
import { Agent, tool } from '@strands-agents/sdk';import { z } from 'zod';
const letterCounter = tool({ name: 'letter_counter', description: 'Count occurrences of a specific letter in a word', inputSchema: z.object({ word: z.string().describe('The input word to search in'), letter: z.string().length(1).describe('The specific letter to count'), }), callback: (input) => { const { word, letter } = input; const count = word.toLowerCase().split(letter.toLowerCase()).length - 1; return `The letter '${letter}' appears ${count} time(s) in '${word}'`; },});
// エージェントにツールを追加export const getAgent = async (sessionId: string) => { return new Agent({ systemPrompt: 'You are a helpful assistant with access to various tools.', tools: [letterCounter], });};Strands フレームワークは次を自動的に処理します:
- Zod スキーマを使用した入力検証
- ツール呼び出しのための JSON スキーマ生成
- エラー処理とレスポンスのフォーマット
デフォルトでは、Strands エージェントは Claude 4 Sonnet を使用しますが、モデルプロバイダー間を簡単に切り替えることができます:
import { Agent } from '@strands-agents/sdk';import { BedrockModel } from '@strands-agents/sdk/models/bedrock';import { OpenAIModel } from '@strands-agents/sdk/models/openai';
// Bedrock を使用const bedrockModel = new BedrockModel({ modelId: 'anthropic.claude-sonnet-4-20250514-v1:0',});let agent = new Agent({ model: bedrockModel });let response = await agent.invoke('What can you help me with?');
// または、モデルプロバイダーを切り替えるだけで OpenAI を使用const openaiModel = new OpenAIModel({ apiKey: process.env.OPENAI_API_KEY, modelId: 'gpt-4o',});agent = new Agent({ model: openaiModel });response = await agent.invoke('What can you help me with?');詳細な設定オプションについては、モデルプロバイダーに関する Strands ドキュメントを参照してください。
MCP サーバーの使用
Section titled “MCP サーバーの使用”Strands エージェントに MCP サーバーからツールを追加できます。
py#mcp-server または ts#mcp-server ジェネレーターを使用して作成した MCP サーバーを使用する場合、connection ジェネレーターを利用できます。
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - connection - 必須パラメータを入力
- クリック
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connection接続の設定方法の詳細については、connection ジェネレーターガイドを参照してください。
その他の MCP サーバーについては、Strands ドキュメントを参照してください。
Strands エージェントの作成に関する詳細なガイドについては、Strands ドキュメントを参照してください。
Strands Agent の実行
Section titled “Strands Agent の実行”ローカル開発
Section titled “ローカル開発”ジェネレーターは <your-agent-name>-serve という名前のターゲットを設定し、開発とテストのために Strands Agent をローカルで起動します。
pnpm nx agent-serve your-projectyarn nx agent-serve your-projectnpx nx agent-serve your-projectbunx nx agent-serve your-projectこのコマンドは tsx --watch を使用して、ファイルが変更されたときにサーバーを自動的に再起動します。エージェントは http://localhost:8081 (または複数のエージェントがある場合は割り当てられたポート) で利用可能になります。
Strands Agent を Bedrock AgentCore Runtime にデプロイ
Section titled “Strands Agent を Bedrock AgentCore Runtime にデプロイ”Infrastructure as Code
Section titled “Infrastructure as Code”computeTypeにBedrockAgentCoreRuntimeを選択した場合、関連するCDKまたはTerraformインフラストラクチャが生成され、Strands AgentをAmazon Bedrock AgentCore Runtimeにデプロイするために使用できます。
エージェント用のCDKコンストラクトが生成されます。名前はジェネレーター実行時に選択したnameに基づくか、デフォルトでは<ProjectName>Agentになります。
このCDKコンストラクトをCDKアプリケーションで使用できます:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { // Add the agent to your stack const agent = new MyProjectAgent(this, 'MyProjectAgent');
// Grant permissions to invoke the relevant models in bedrock agent.agentCoreRuntime.addToRolePolicy( new PolicyStatement({ actions: [ 'bedrock:InvokeModel', 'bedrock:InvokeModelWithResponseStream', ], // You can scope the below down to the specific models you use resources: [ 'arn:aws:bedrock:*:*:foundation-model/*', 'arn:aws:bedrock:*:*:inference-profile/*', ], }), ); }}Terraformモジュールが生成されます。名前はジェネレーター実行時に選択したnameに基づくか、デフォルトでは<ProjectName>-agentになります。
このTerraformモジュールをTerraformプロジェクトで使用できます:
# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"
# Grant permissions to invoke the relevant models in bedrock additional_iam_policy_statements = [ { Effect = "Allow" Action = [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ] # You can scope the below down to the specific models you use Resource = [ "arn:aws:bedrock:*:*:foundation-model/*", "arn:aws:bedrock:*:*:inference-profile/*" ] } ]}ジェネレーターは、Strands Agentの認証を設定するためのauthオプションを提供します。エージェントを生成する際に、IAM(デフォルト)またはCognito認証を選択できます。
デフォルトでは、Strands AgentはIAM認証を使用して保護されます。引数なしで単純にデプロイしてください:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { new MyProjectAgent(this, 'MyProjectAgent'); }}grantInvokeAccessメソッドを使用して、Bedrock AgentCore Runtime上でエージェントを呼び出すアクセス権を付与できます。例:
import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent'); const lambdaFunction = new Function(this, ...);
agent.grantInvokeAccess(lambdaFunction); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}エージェントを呼び出すアクセス権を付与するには、module.my_project_agent.agent_core_runtime_arn出力を参照して、次のようなポリシーを追加する必要があります:
{ Effect = "Allow" Action = [ "bedrock-agentcore:InvokeAgentRuntime" ] Resource = [ module.my_project_agent.agent_core_runtime_arn, "${module.my_project_agent.agent_core_runtime_arn}/*" ]}Cognito認証
Section titled “Cognito認証”Cognito認証を選択すると、ジェネレーターはCognito認証を使用するようにエージェントを設定します。
生成されたコンストラクトは、Cognito認証を設定するidentityプロパティを受け入れます:
import { MyProjectAgent, UserIdentity } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const identity = new UserIdentity(this, 'Identity');
new MyProjectAgent(this, 'MyProjectAgent', { identity, }); }}UserIdentityコンストラクトは、ts#react-website#authジェネレーターを使用して生成するか、独自のCDK UserPoolとUserPoolClientを作成できます。
生成されたモジュールは、Cognito認証用のuser_pool_idとuser_pool_client_ids変数を受け入れます:
module "user_identity" { source = "../../common/terraform/src/core/user-identity"}
module "my_project_agent" { source = "../../common/terraform/src/app/agents/my-project-agent"
user_pool_id = module.user_identity.user_pool_id user_pool_client_ids = [module.user_identity.user_pool_client_id]}Bundle ターゲット
Section titled “Bundle ターゲット”ジェネレーターは自動的に Rolldown を使用する bundle ターゲットを設定します。このターゲットはデプロイメントパッケージの作成に使用されます:
pnpm nx bundle <project-name>yarn nx bundle <project-name>npx nx bundle <project-name>bunx nx bundle <project-name>Rolldownの設定はrolldown.config.tsに記述され、生成するバンドルごとにエントリを定義します。Rolldownは定義された複数のバンドルを並行して作成する処理を管理します。
bundle ターゲットは、Bedrock AgentCore Runtime でホストする WebSocket サーバーのエントリーポイントとして index.ts を使用します。
Docker ターゲット
Section titled “Docker ターゲット”ジェネレーターは <your-agent-name>-docker ターゲットを設定し、AgentCore ランタイムコントラクトに従ってポート 8080 でバンドルされた WebSocket サーバーを実行します。
複数のエージェントが定義されている場合、すべてのエージェントに対して docker ビルドを実行する docker ターゲットも生成されます。
エージェントは、Dockerfile で自動計装を設定することにより、AWS Distro for Open Telemetry (ADOT) を使用した可観測性で自動的に構成されます。
CloudWatch AWS コンソールでトレースを見つけるには、メニューで “GenAI Observability” を選択します。トレースを入力するには、Transaction Search を有効にする必要があることに注意してください。
詳細については、可観測性に関する AgentCore ドキュメントを参照してください。
Strands Agent の呼び出し
Section titled “Strands Agent の呼び出し”エージェント通信は、WebSocket 上の tRPC を介して送信されます。そのため、client.ts で生成された型安全なクライアントファクトリーを使用することをお勧めします。
ローカルサーバーの呼び出し
Section titled “ローカルサーバーの呼び出し”クライアントファクトリーの .local ファクトリーメソッドを使用して、ローカルで実行されているエージェントを呼び出すことができます。
たとえば、ワークスペースに scripts/test.ts という名前のファイルを作成し、クライアントをインポートできます:
import { AgentClient } from '../packages/<project>/src/agent/client.js';
const client = AgentClient.local({ url: 'http://localhost:8081/ws' });
client.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: console.log });デプロイされたエージェントの呼び出し
Section titled “デプロイされたエージェントの呼び出し”Bedrock AgentCore Runtimeにデプロイされたエージェントを呼び出すには、URLエンコードされたランタイムARNを使用して、Bedrock AgentCore RuntimeデータプレーンエンドポイントにPOSTリクエストを送信します。
ランタイムARNは、以下のようにインフラストラクチャから取得できます:
import { CfnOutput } from 'aws-cdk-lib';import { MyProjectAgent } from ':my-scope/common-constructs';
export class ExampleStack extends Stack { constructor(scope: Construct, id: string) { const agent = new MyProjectAgent(this, 'MyProjectAgent');
new CfnOutput(this, 'AgentArn', { value: agent.agentCoreRuntime.agentRuntimeArn, }); }}# Agentmodule "my_project_agent" { # Relative path to the generated module in the common/terraform project source = "../../common/terraform/src/app/agents/my-project-agent"}
output "agent_arn" { value = module.my_project_agent.agent_core_runtime_arn}ARNは次の形式になります: arn:aws:bedrock-agentcore:<region>:<account>:runtime/<agent-runtime-id>
次に、:を%3Aに、/を%2Fに置き換えることで、ARNをURLエンコードできます。
エージェントを呼び出すためのBedrock AgentCore RuntimeデータプレーンURLは次のとおりです:
https://bedrock-agentcore.<region>.amazonaws.com/runtimes/<url-encoded-arn>/invocationsこのURLを呼び出す正確な方法は、使用する認証方法によって異なります。
NodeJS
Section titled “NodeJS”生成された client.ts ファイルには、デプロイされたエージェントを呼び出すために使用できる型安全なクライアントファクトリーが含まれています。
IAM 認証
Section titled “IAM 認証”withIamAuth ファクトリーメソッドに ARN を渡すことで、デプロイされたエージェントを呼び出すことができます:
import { AgentClient } from './agent/client.js';
const client = AgentClient.withIamAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent',});
client.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: (message) => console.log(message), onError: (error) => console.error(error), onComplete: () => console.log('Done'),});JWT / Cognito 認証
Section titled “JWT / Cognito 認証”JWT / Cognito アクセストークンで認証するには、withJwtAuth ファクトリーメソッドを使用します。
const client = AgentClient.withJwtAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', accessTokenProvider: async () => `<access-token>`,});
client.invoke.subscribe({ message: 'what is 1 plus 1?' }, { onData: console.log,});accessTokenProvider は、リクエストの認証に使用されるトークンを返す必要があります。たとえば、tRPC が WebSocket 接続を再起動するときに新しい認証情報が再利用されるように、このメソッド内でトークンを取得できます。以下は、AWS SDK を使用して Cognito からトークンを取得する方法を示しています:
import { CognitoIdentityProvider } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProvider();
const jwtClient = AgentClient.withJwtAuth({ agentRuntimeArn: 'arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/my-agent', accessTokenProvider: async () => { const response = await cognito.adminInitiateAuth({ UserPoolId: '<user-pool-id>', ClientId: '<user-pool-client-id>', AuthFlow: 'ADMIN_NO_SRP_AUTH', AuthParameters: { USERNAME: '<username>', PASSWORD: '<password>', }, }); return response.AuthenticationResult!.AccessToken!; },});ブラウザ / React ウェブサイト
Section titled “ブラウザ / React ウェブサイト”React ウェブサイトから Strands Agent を呼び出す場合は、connection ジェネレーターを利用できます。これにより、正しい認証 (IAM または Cognito) を使用した tRPC WebSocket クライアントが自動的にセットアップされます。
- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - connection - 必須パラメータを入力
- クリック
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connection接続の設定方法の詳細については、connection ジェネレーターガイドを参照してください。