3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AWS Blocks】CopilotKitとStrandsAgentsを使ってAIエージェントのフロントエンドを作ってみる

3
Posted at

はじめに

お疲れ様です。たけのこです。

少し前にAWS Blocksがプレビュー公開されましたが、今回はAIエージェントのフロントエンド周りのインフラをAWS Blocksで作ってみました。エージェント周りはStrandsAgentsとCopilotKitです。

作成したAIエージェントは以下の構成です。

aws_architecture1.png

コードは以下になります。

1. そもそもAWS Blocksとは

AWS Blocksは、TypeScriptのソースコードを記述することで、AWSの各種サービスや機能を定義できます。

「Blocks」とある通り、イメージとしてはAWSサービスや機能のまとまりを1つのレゴブロックのように扱います。

つまり、インフラ自体がブロックという括りで抽象化されています。

開発者は、このレゴブロックを組み合わせることで、ある程度インフラの知識がなくても認証・データベース・APIといったバックエンド機能を手軽に使えます。

多様なブロックを組み合わせて自分だけアーキテクチャを作れる

AWS Blocksは、様々なブロックが提供されています。

開発者は、これらの中からユースケースに応じて選択し、好きにシステムを構築できます。

カテゴリ Block 説明
認証 AuthBasic 外部サービスを使わず、DynamoDBにユーザー情報を保存してユーザー名とパスワードで認証する。
AuthOIDC Cognitoを介して、外部の認証サービスと連携してサインインできるようにする。
AuthCognito Cognitoを使い、多要素認証・ソーシャルサインイン・パスキーなどに対応した認証ができる。
データ永続化 KVStore DynamoDBを使った、スキーマなし・インデックスなしのシンプルなキー・バリューストレージが使える。
DistributedTable DynamoDBを使い、スキーマ検証・セカンダリインデックスを持つ構造化データを扱える。
Database Aurora Serverless v2を使った、PostgreSQL互換のデータベースが使える。
DistributedDatabase Aurora DSQLを使った、使っていない時はコストがかからず、複数リージョンへの書き込みにも対応したサーバーレスSQLが使える。
FileBucket S3を使い、署名付きURLでファイルをアップロード/ダウンロードできる。
リアルタイム・非同期処理 Realtime API Gateway WebSocketを使い、型のついたメッセージをリアルタイムでやり取りできる。
AsyncJob SQS + Lambdaによる、結果を待たずにバックグラウンドで処理を実行できる。
CronJob EventBridge + Lambdaで、スケジュールに沿ってタスクを実行できる。
AI Agent Bedrockに接続した、ストリーミング・ツール呼び出し・人による承認・会話の保存に対応したAIエージェントが使える。ローカルではキーワードベースの擬似プロバイダを使う(実モデル不要)。
KnowledgeBase Bedrock Knowledge Baseで、意味の近さでドキュメントを検索できる。
コミュニケーション EmailClient SESで、通知や確認メールなどを送信できる。ローカルでは実際に送らず、送信内容をファイルに保存するだけになる。
設定 AppSetting Systems Manager Parameter Storeを使い、APIキーなどの設定値やシークレットを1つ保存できる。
可観測性 Metrics CloudWatchで、カスタムアプリケーションメトリクスを記録できる。
Logger ログレベルや追加の情報を含めて、CloudWatch LogsへJSON形式のログを出力する。
Tracer X-Rayで、リクエストの流れを追跡できる。
Dashboard CloudWatchのメトリクス定義から、ダッシュボードを自動生成する。
ホスティング Hosting CloudFront・S3・API Gateway・Lambdaを使い、SSR対応のフロントエンドをフレームワーク自動検出でデプロイする。
CI/CD Pipeline CodePipeline・CodeBuild・CodeConnectionsによる、自己更新型のCDK Pipelines構成を提供する。

ローカル開発など開発体験が優れている

AWS Blocksでは以下の方法で動作させることができます。

  • ローカル環境(モック)
  • Sandbox環境(AWS環境に使い捨てリソースを構築)
  • 本番環境

ローカル環境では、AWSアカウントなしで各種AWSサービスをモックとして動作させることができます。

AWSアカウントをすぐに準備できない場合や、まだ作り込んでないのでとりあえず動かしたい場合に重宝します。

HostingとPipelineはローカル、Sandboxには対応していないため、AWS本番デプロイのみとなります。

2. AWS Blocksの提供する認証機能を使う

AWS Blocksには、3種類の認証ブロックが用意されています。
今回作ったエージェントですが、AuthCognitoを使用してユーザー認証を行なっています。

  • AuthBasic
  • AuthOIDC
  • AuthCognito 👈今回はこれ

AuthCognitoによる認証機能の追加

AuthCognitoは、以下のように定義します。(感覚的にはAmplifyに近いですかね)

import { Scope } from '@aws-blocks/blocks';
import { AuthCognito } from '@aws-blocks/bb-auth-cognito';

const scope = new Scope('my-app');

const auth = new AuthCognito(scope, 'auth', {
  signInWith: ['email'],
  mfa: 'off',
  logger: { level: 'info' },
});

export const authApi = auth.createApi();

createApi()を使ってフロントエンドから認証情報へアクセス

createApi()は、認証状態を操作するAPIをフロントエンド向けに提供します。
このAPIは内部的にApiNamespaceで作られており、API Gateway + Lambdaで構成されます。

API 機能
getAuthState() 現在の認証状態(未サインイン/サインイン済みなど)と、その状態で可能なアクション一覧を取得する
setAuthState() サインイン・サインアップなどのアクションを実行し、状態を遷移させる

このAPIにより、ブラウザが直接トークンを扱うことはなく、このAPIを叩く形となり、セキュリティ的により安全になります。

Authenticatorで認証UIを手軽に構築

Authenticatorは、サインイン・サインアップなどの画面を自分で実装しなくてもいいように、AWS Blocksが提供してくれるUI部品です。

このAuthenticatorはReactなどのライブラリに依存せず、呼び出すとただのHTMLElement(素のDOM要素)を返すだけの関数となっています。

import { useEffect, useRef } from 'react';
import { Authenticator } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

export default function LoginPage() {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (containerRef.current) {
      const authElement = Authenticator(authApi);
      containerRef.current.appendChild(authElement);
      
      return () => {
        containerRef.current?.removeChild(authElement);
      };
    }
  }, []);

  return <div ref={containerRef} />;
}

3. AWS Blocksの提供するホスティング機能を使う

AWS Blocksは、フロントエンドのホスティングを行うHostingを提供しています。

今回作ったアプリはNext.jsを使用しており、Hostingを使ってAWS環境にデプロイしています。

Hostingを追加する場合、以下のようなコードを書いて、npm run deployを実行すると実際にデプロイされます。

new Hosting(blocksStack, 'Hosting', {
  root: join(__dirname, '..'),
  buildCommand: 'npm run build',
  framework: 'nextjs',
  api: blocksStack,
  compute: {
    memorySize: 1024,
    timeout: 30,
  },
});

Hostingの裏側の話

deployコマンド実行からの流れとして、プロジェクトの状態(package.jsonなど)から、Next.jsなどフレームワークやライブラリの環境が自動検知されます。

環境が決まると、そのフレームワークのビルド成果物を、環境共通のmanifest(デプロイする内容がまとめられた設計図)に変換します。その設計図に沿って、CDKがAWSサービスをデプロイします。

Hostingでデプロイされたフロントエンドの裏側は、以下のサービスで構成されます。

  • Amazon CloudFront
  • Amazon S3
  • Amazon API Gateway
  • AWS Lambda

4. まずはローカルで動作するAIエージェントWebアプリを作る

ここまでAWS Blocksの概要を見てきたので、ここからは実際にAIエージェントアプリを構築してみます。せっかくローカル実行が提供されているので、まずは手元のローカルで動作する状態を目指します。

work1.png

プロジェクトを作る

1. nextjsテンプレートを使って、AWS Blocksのプロジェクトを作ります。

npx @aws-blocks/create-blocks-app my-app --template nextjs

プロジェクトの初期構成について
nextjsのテンプレートの場合、以下のような構成になります。

my-app/
├── aws-blocks/
│   ├── index.ts            # 認証やAPIなど、実際の「ブロック」を定義
│   ├── index.cdk.ts        # CDK Appを起動し、Hostingなどインフラ寄りの構成を追加
│   └── index.handler.ts    # Lambda実行時に index.ts を読み込んで動作
├── src/app/                # Next.js App Router本体(page.tsx・layout.tsx等)
├── test/                   # E2Eテスト
├── .blocks/
│   └── config.json         # プロジェクト固有の stackId を持つCLI管理設定ファイル
└── AGENTS.md               # AIコーディングエージェント向け説明ファイル(全テンプレート共通)

AuthCognitoで認証機能を組み込む

1. index.tsにAuthCognitoを追加します。

my-app/aws-blocks/index.ts
import { ApiNamespace, Scope } from '@aws-blocks/blocks';
import { AuthCognito } from '@aws-blocks/bb-auth-cognito';

const scope = new Scope('my-app');

const auth = new AuthCognito(scope, 'auth', {
  signInWith: ['email'],
  mfa: 'off',
  logger: { level: 'info' },
});

export const authApi = auth.createApi();

サインアップ時の検証コード送信先について(ローカル実行時)

Amazon Cognitoでサインアップする際には、ユーザーが検証コードを入力する必要があります。
AWS環境にデプロイする場合は、メールなどで届きますが、ローカル実行の場合は以下の方法で検証コードを確認します。
1. npm run devを実行したコマンドプロンプト
2. .bb-data/<fullId>/last-code.jsonファイルの中身

今回は1で確認します。
しかし、INFOログで検証コードが表示されるため、loggerを指定する必要があります。
(デフォルトだとログレベルがERRORなので検証コードが見えない)

AuthCognitoの設定について

AuthCognitoは、Amazon Cognitoを使用した認証機能を提供します。今回の設定値は以下のようになります。

設定 値 説明
signInWith ['email'] メールアドレスを使って認証する
mfa 'off' 多要素認証を無効にする
logger { level: 'info' } ログレベルをinfoにする。

2. さらにApiNamespaceでアクセストークンを返すAPIを追加します。

my-app/aws-blocks/index.ts
export const agentAuth = new ApiNamespace(scope, 'agentAuth', (context) => ({
  async getAccessToken() {
    const session = await auth.fetchAuthSession(context);
    return { accessToken: session.tokens?.accessToken?.toString() };
  },
}));

ApiNamespaceとは

前提として、AWS BlocksはデフォルトでAmazon API Gateway + AWS LambdaによるバックエンドAPIが用意されています。
ApiNamespaceは、このAPIの中身を定義するためのものです。
なお、このLambdaは、Lambdalithで構築され、1つのLambdaが複数の役割を担います。

ログイン画面を実装する

1. my-app/src/app/login/page.tsxを作成します。

mkdir -p src/app/login && touch src/app/login/page.tsx

2. Authenticatorを使って、ログイン画面を実装します。

my-app/src/app/login/page.tsx
"use client";

import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { Authenticator, onAuthChange } from '@aws-blocks/auth-common/ui';
import { authApi } from 'aws-blocks';

export default function LoginPage() {
  const containerRef = useRef<HTMLDivElement>(null);
  const router = useRouter();

  useEffect(() => {
    if (containerRef.current) {
      const authElement = Authenticator(authApi);
      containerRef.current.appendChild(authElement);
      return () => {
        containerRef.current?.removeChild(authElement);
      };
    }
  }, []);

  useEffect(() => {
    return onAuthChange(authApi, (user) => {
      if (user) {
        router.push('/');
      }
    });
  }, [router]);

  return <div ref={containerRef} />;
}

page.tsxでやってること

page.tsxでやってることは大きく以下の2つです。
1. 認証画面の表示(ログイン、サインアップ、パスワード変更機能)
2. メイン画面へのリダイレクト

認証画面は、Blocksが提供するAuthenticatorを使用して構成してます。
リダイレクトは、onAuthChange(api, callback)でログイン状態の変化を監視し、signedInになったタイミングで/へrouter.pushしています。

3. AuthGuard.tsxを作成します。

touch src/app/AuthGuard.tsx

4. 未認証なら/loginへリダイレクトする処理を実装します。

my-app/src/app/AuthGuard.tsx
"use client";

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { authApi } from 'aws-blocks';

export function AuthGuard({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const [signedIn, setSignedIn] = useState(false);

  useEffect(() => {
    authApi.getAuthState().then((state) => {
      if (state.state === 'signedIn') {
        setSignedIn(true);
      } else {
        router.push('/login');
      }
    });
  }, [router]);

  if (!signedIn) return null;
  return <>{children}</>;
}

ログイン済みかの判定方法

authApi.getAuthState()が返すstate.stateを使います。
この値がsignedInかどうかで判定します。

5.<AuthGuard>コンポーネントで囲みます。これでリダイレクト処理が適用されます。

my-app/src/app/page.tsx
import { AuthGuard } from './AuthGuard';

export default function Home() {
  return (
    <AuthGuard>
      <main>
        {/* 既存のmain要素の中身はそのまま */}
      </main>
    </AuthGuard>
  );
}

認証機能の動作確認

ここまでの実装を動作確認するため、実際にサインアップしてみます。

1. npm run devでローカルサーバーを起動します。

npm run dev

AWS Blocksのローカル実行

npm run devはaws-blocks/scripts/server.ts経由で1つのコマンドが、Blocksのモックバックエンドと、Next.jsの開発サーバー(内部的には別ポート)を両方まとめて起動します。

2. ブラウザでhttp://localhost:3000にアクセスします。(/loginにリダイレクトされます)

3. /loginでメールアドレス、パスワード、検証コードを入力してサインアップします。

4. 以下のような画面が表示されたらOKです。ログインできました。
image.png

ここまででログイン機能の実装が出来ました。次は実際にAI周りの機能を作っていきます。

CopilotKitを導入してAIチャットボットを作る

次にCopilotKitをフロントエンドに追加して、AIチャットボットの機能を追加します。

1. 必要なパッケージをインストールします。

npm install @copilotkit/react-core @copilotkit/runtime @ag-ui/client

2. ランタイムの置き場所を作ります。

mkdir -p "src/app/api/copilotkit/[...path]" && touch "src/app/api/copilotkit/[...path]/route.ts"

3. Next.jsのAPI Routesにroute.tsを実装します。

my-app/src/app/api/copilotkit/[...path]/route.ts
import {
  CopilotRuntime,
  createCopilotRuntimeHandler,
} from "@copilotkit/runtime/v2";
import { HttpAgent } from "@ag-ui/client";

const runtime = new CopilotRuntime({
  agents: {
    default: new HttpAgent({
      url: process.env.STRANDS_URL ?? "http://localhost:8000/invocations",
    }),
  },
});

const handler = createCopilotRuntimeHandler({
  runtime,
  basePath: "/api/copilotkit",
});

export const POST = handler;
export const GET = handler;

フロントエンドとAIエージェントとの接続はAG-UI

フロントエンドとAIエージェントを接続するプロトコルとしてAG-UIというものがあります。
AG-UIは、エージェントとの対話をイベントのストリームとしてやり取りするためのプロトコルです。

RunAgentInput(スレッドID・メッセージ履歴・ツール定義などを含むリクエスト形式)をエージェント側に送り、エージェントはテキスト生成やツール呼び出しの進行状況を、イベントのストリームとして返します。

CopilotKitのHttpAgentは、このAG-UI形式でエージェントと通信するクライアントです。

4. CopilotKitを追加します。

my-app/src/app/page.tsx
import { CopilotKit, CopilotSidebar } from '@copilotkit/react-core/v2';
import '@copilotkit/react-core/v2/styles.css';

export default function Home() {
  return (
    <AuthGuard>
      <CopilotKit runtimeUrl="/api/copilotkit" credentials="include" useSingleEndpoint={false}>
        <main>
          {/* 既存のmain要素の中身はそのまま */}
        </main>
        <CopilotSidebar agentId="default" />
      </CopilotKit>
    </AuthGuard>
  );
}

CopilotSidebar とは

CopilotSidebarは、画面右端に開閉できるチャットパネルを表示するコンポーネントです

StrandsAgents(TypeScript版)のAIエージェントを実装する

1. Strands Agents用にmy-app/agent/ディレクトリを作成します。

mkdir -p agent/src

2. agentディレクトリに移動し、npmプロジェクトとして初期化します。

cd agent && npm init -y

3. agent/package.jsonの"type"を"commonjs"から"module"に、scriptsにbuildを追加します。

my-app/agent/package.json
{
  "scripts": {
    "build": "tsc"
  },
  "type": "module"
}

4. 必要なパッケージをインストールします。

npm install @ag-ui/aws-strands @strands-agents/sdk @ag-ui/core @ag-ui/encoder express cors @modelcontextprotocol/sdk
npm install -D @types/express @types/cors typescript @types/node

5. my-app/agent/tsconfig.jsonを作成します。

touch tsconfig.json

6. tsconfig.jsonを実装します。

my-app/agent/tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

7. my-app/agent/src/server.tsを作成します。

touch src/server.ts

8. server.tsにStrandsAgentsのAIエージェントを実装します。

my-app/agent/src/server.ts
import { Agent } from '@strands-agents/sdk';
import { StrandsAgent } from '@ag-ui/aws-strands';
import { createStrandsApp } from '@ag-ui/aws-strands/server';

const strandsAgent = new Agent({
  systemPrompt: 'You are a helpful assistant.',
});

const aguiAgent = new StrandsAgent({
  agent: strandsAgent,
  name: 'myAgent',
  description: 'A Strands agent exposed via AG-UI',
});

const app = await createStrandsApp(aguiAgent, { path: '/invocations' });
app.listen(8000);

Strands Agentsとは
Strands Agentsは、AWSがオープンソースで公開しているAIエージェントSDKです。
もともとはPython向けに発表されましたが、TypeScript版も提供されています。

StrandsのエージェントをCopilotKit(AG-UI)向けに公開するには、AG-UIプロジェクト側が提供する@ag-ui/aws-strandsパッケージのcreateStrandsAppを使います。

https://github.com/ag-ui-protocol/ag-ui/blob/main/integrations/aws-strands/typescript/README.md

動作確認(ローカル)

1. 別のターミナルで、my-app/agent/ディレクトリの中のサーバーをhttp://localhost:8000で起動します。

cd agent
npx tsx src/server.ts

2. サーバーを起動したまま、別のターミナルからcurlで直接動作確認します。これでAIエージェントがローカル上で動作することを確認します。

curl -N -X POST http://localhost:8000/invocations \
  -H "Content-Type: application/json" \
  -d '{
    "threadId": "test-thread-1",
    "runId": "test-run-1",
    "state": {},
    "messages": [
      { "id": "msg-1", "role": "user", "content": "こんにちは" }
    ],
    "tools": [],
    "context": [],
    "forwardedProps": {}
  }'

3. ブラウザでアクセスし、サインインした後にエージェントとチャットできることを確認します。

image2.png

5. (実装!)AWSで動作するエージェントアプリケーションを作ろう

ローカルで一通り動くものができたので、ここからはAWS上で動かすところまで進めます。

StrandsAgentsをAgentCore Runtime向けに修正する

1. /pingのパスを追加し、ポートを8080に変更します。

my-app/agent/src/server.ts
const app = await createStrandsApp(aguiAgent, {
  path: '/invocations',
  pingPath: '/ping',
});

app.listen(8080);

2. コンテナ化するためのDockerfileを作成します。

touch Dockerfile

3. Dockerfileを実装します。

my-app/agent/Dockerfile
FROM node:22-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package*.json ./
EXPOSE 8080
CMD ["node", "dist/server.js"]

CDKでAgentCore Runtimeを定義する

1. 必要なimportを追加します。

my-app/aws-blocks/index.cdk.ts
import * as agentcore from 'aws-cdk-lib/aws-bedrockagentcore';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as path from 'node:path';
import type { AuthCognito } from '@aws-blocks/bb-auth-cognito';

2. スコープからauthを取り出します。

my-app/aws-blocks/index.cdk.ts
const appScope = blocksStack.node.findChild('my-app');
const auth = appScope.node.findChild('auth') as unknown as AuthCognito;

3. CDK L2コンストラクタのagentcore.Runtimeを追加します。

my-app/aws-blocks/index.cdk.ts
const runtime = new agentcore.Runtime(blocksStack, "MyAgentRuntime", {
  runtimeName: "myAgent",
  agentRuntimeArtifact: agentcore.AgentRuntimeArtifact.fromAsset(
    path.join(__dirname, "..", "agent")
  ),
  authorizerConfiguration: agentcore.RuntimeAuthorizerConfiguration.usingCognito(
    auth.userPool,
    [auth.userPoolClient],
  ),
});

AgentCore Runtimeの設定値

AgentCore Runtimeの設定値は以下になります。

設定 値 説明
runtimeName myAgent 自分でつけたRuntimeの名前
agentRuntimeArtifact fromAsset(agent/) agent/のDockerfileからビルドしたコンテナイメージを使うよう指定
authorizerConfiguration usingCognito(auth.userPool, [auth.userPoolClient]) AuthCognitoで定義したCognitoのアクセストークンで認可する

4. sandbox実行向けにCfnOutputを追加して、outputs.jsonが生成されるようにします。

my-app/aws-blocks/index.cdk.ts
new cdk.CfnOutput(blocksStack, 'AgentRuntimeArn', {
  value: runtime.agentRuntimeArn,
});

5. Bedrockモデルを呼び出すIAM権限を追加します。

my-app/aws-blocks/index.cdk.ts
runtime.addToRolePolicy(
  new iam.PolicyStatement({
    actions: [
      'bedrock:InvokeModel',
      'bedrock:InvokeModelWithResponseStream',
    ],
    resources: [
      'arn:aws:bedrock:*::foundation-model/*',
      'arn:aws:bedrock:*:*:inference-profile/*',
    ],
  })
);

バックエンドをAgentCore Runtime向けに修正する

1. 必要なimportを追加します。

my-app/src/app/api/copilotkit/[...path]/route.ts
import { withAuth } from "@aws-blocks/blocks/server";
import { agentAuth } from "aws-blocks";
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";

2. 新たにresolveAgentRuntimeArn関数を追加します。

my-app/src/app/api/copilotkit/[...path]/route.ts
function resolveAgentRuntimeArn(): string {
  const config = JSON.parse(process.env.BLOCKS_CONFIG ?? "{}");
  if (config.agentRuntimeArn) {
    return config.agentRuntimeArn;
  }
  const outputs = JSON.parse(readFileSync(".blocks-sandbox/outputs.json", "utf-8"));
  const stackOutputs = Object.values(outputs)[0] as Record<string, string>;
  return stackOutputs.AgentRuntimeArn;
}

resolveAgentRuntimeArnについて

環境変数BLOCKS_CONFIGは、HostingのbackendConfig経由でLambdaに渡ります。
しかし、Sandboxでは、Hostingがデプロイされないため、BLOCKS_CONFIGが渡ってきません。
よって、BLOCKS_CONFIG経由ではAgentCore RuntimeのARNを取得できません。

そのためresolveAgentRuntimeArn関数にて、BLOCKS_CONFIGが無い場合に、.blocks-sandbox/outputs.jsonを直接読み込むようにしています。

3. 向き先をAgentCore RuntimeのARNにして、アクセストークンとセッションIDを各種ヘッダーに追加します。

my-app/src/app/api/copilotkit/[...path]/route.ts
const runtime = new CopilotRuntime({
  agents: async () => {
    const { accessToken } = await withAuth(() => agentAuth.getAccessToken());
    const agentRuntimeArn = resolveAgentRuntimeArn();
    const region = process.env.AWS_REGION ?? "us-east-1";
    const url = `https://bedrock-agentcore.${region}.amazonaws.com/runtimes/${encodeURIComponent(agentRuntimeArn)}/invocations?qualifier=DEFAULT`;

    return {
      default: new HttpAgent({
        url,
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id": randomUUID(),
        },
      }),
    };
  },
});

withAuthとは

AuthCognitoでは、認証後にトークンをKVStoreに保存します。
このとき、トークンを取り出すためのセッションIDが発行され、そのセッションIDをキーとしてトークンが保存されます。
このセッションIDはクッキーとして管理されます。

route.tsのバックエンドは、Lambdaで動作します。
以前に作ったagentAuthAPIもLambdaで動作します。
これらは別々のLambdaで動作します。
つまり、route.tsからagentAuthAPIを呼び出すことは、HTTPリクエストになります。

このとき、そのリクエストが誰のセッションかを識別するためにクッキーが必要となり、ヘッダーなどに埋め込む処理が必要になります。

つまり、APIへの新しいリクエストに自動でクッキーを付け直してくれる関数がwithAuthになります。

Sandbox環境で動作確認

本番デプロイの前に、Sandbox環境で動作確認をします。

1. AWS_REGIONを設定します。

echo "AWS_REGION=ap-northeast-1" >> .env.local

2. sandboxコマンドを実行してデプロイします。

npm run sandbox

3. 公開されたURLにアクセスし、サインアップした上でエージェントとチャットできることを確認します。

本番環境で動作確認

1. 既存のHostingの設定にbackendConfigを追加します。

my-app/aws-blocks/index.cdk.ts
new Hosting(blocksStack, 'Hosting', {
  root: join(__dirname, '..'),
  buildCommand: 'npm run build',
  framework: 'nextjs',
  api: blocksStack,
  compute: {
    memorySize: 1024,
    timeout: 30,
  },
  backendConfig: { agentRuntimeArn: runtime.agentRuntimeArn },
});

backendConfigについて

backendConfigに渡した値は、LambdaのBLOCKS_CONFIG環境変数に設定されます。
デプロイ後、Next.jsのAPI Routesにあたるバックエンド内で接続先のAgentCore RuntimeのARNを参照するために設定します。

2. Next.jsの設定にoutputFileTracingIncludesを設定します。

my-app/next.config.ts
import type { NextConfig } from 'next';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);

function resolveTransitiveDeps(pkg: string, seen = new Set<string>()): Set<string> {
  if (seen.has(pkg)) return seen;
  seen.add(pkg);
  try {
    const pkgJson = require(`${pkg}/package.json`);
    for (const dep of Object.keys(pkgJson.dependencies ?? {})) {
      resolveTransitiveDeps(dep, seen);
    }
  } catch {
    // 解決できない依存は無視する
  }
  return seen;
}

const expressDeps = [...resolveTransitiveDeps('express')];

const nextConfig: NextConfig = {
  // Enable standalone output for Lambda deployment
  output: 'standalone',
  outputFileTracingIncludes: {
    '/*': expressDeps.map((pkg) => `node_modules/${pkg}/**/*`),
  },
};

export default nextConfig;

outputFileTracingIncludesについて

本番ビルドは、Next.js 16のビルドツールであるTurbopackがソースコードをビルドします。
このビルド時に実際に使うファイルだけを自動的に選んでLambdaにデプロイします。

Next.jsのoutputFileTracingIncludesは、ビルド時の対象に指定したファイルを含めることができる設定です。

この自動選択が、@copilotkit/runtimeが内部で使っているexpressの依存先(body-parserなど)を見落としてエラーになるため、今回は設定しています。

3. 本番デプロイを実行します。

npm run deploy

4. 公開されたURLにアクセスし、サインアップした上でエージェントとチャットできることを確認します。

環境の後片付け

動作確認が終わったら、忘れずに不要なAWSリソースを削除します。

1. sandbox環境を削除します。

npm run sandbox:destroy

2. 本番環境を削除します。

npm run destroy

まとめ

今回、AIエージェントアプリを題材にして、AWS Blocksを触ってみました。

使ってみた感触としては、ローカル実行とHostingが便利に感じました。

AmplifyのSandboxもですが実AWS環境へデプロイしようとすると、どうしても時間がかかります。その点、ローカル実行なら手軽に試せるので体験が良かったです。

またAIエージェントとの親和性ですと、HostingでデプロイしたNext.jsがストリーミングで動いたのが良かったです。

前はよくAmplifyのHostingを使ってましたが、制約上ストリーミングはできなかったので...

AWS Blocksのごく一部の機能しか使えなかったので、今後は他のブロックも試していきたいと思います。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?