Amazon Bedrock AgentCore で AG-UI プロトコルを活用し、AI エージェントに生成型 UI を構築する方法
AWS は AG-UI プロトコルと Amazon Bedrock AgentCore の統合により、AI エージェントがチャットを超えたインタラクティブな UI や人間との協働を可能にする次世代のアーキテクチャを発表した。
キーポイント
AG-UI プロトコルの標準化と役割
AI エージェントとフロントエンド間の動的イベント通信(生成 UI、共有状態、人間による承認など)を定義するオープンプロトコル「AG-UI」が導入され、バックエンドとフロントエンドのフレームワークを選ばずに結合可能になる。
Amazon Bedrock AgentCore の統合機能
AgentCore Runtime が AG-UI プロトコルをサポートし、認証(SigV4/OAuth 2.0)、セッション分離、スケーリング、観測性を透明なプロキシとして提供することで、セキュアかつ大規模なエージェント運用を可能にする。
CopilotKit と FAST テンプレートによる実装
AWS の「Fullstack AgentCore Solution Template (FAST)」と CopilotKit を組み合わせることで、開発者は React などのフロントエンドを用いて、即時に生成 UI や共有状態を備えたインタラクティブなエージェントアプリケーションを構築できる。
リクエストごとのアイデンティティスコープ
各リクエストごとに新しいエージェントを構築し、呼び出し手のIDに基づいてMCPツールとメモリセッションを動的にスコーピングします。
認証ヘッダーの自動処理
BedrockAgentCoreAppがランタイムヘッダー(WorkloadAccessTokenなど)を読み取り、Gateway認証とメモリ機能をHTTPパターンと同様に動作させます。
LangGraphパターンの柔軟性
各リクエストでグラフを再構築し、MEMORY_IDが未設定の場合はチェックポインターをNoneにすることで、メモリプロビジョニングなしでも実行可能です。
AG-UI プロトコルによるバックエンドの抽象化
AG-UI は Server-Sent Events を介した型付きイベントストリームを定義し、LangGraph や Strands など異なるバックエンドフレームワークを使用してもフロントエンド側のパーサーやロジックを変更する必要がなくなる。
影響分析・編集コメントを表示
影響分析
この発表は、AI エージェント開発における「チャットボックス」から「インタラクティブなアプリケーション」への転換を加速させる重要なマイルストーンです。AG-UI という標準プロトコルと AWS のインフラが統合されることで、開発者は複雑な UI 制御や状態管理の独自実装に悩まされず、より高付加価値なエージェント体験の構築に集中できるようになります。
編集コメント
AI エージェントの実用化において、UI/UX の標準化は長年の課題でしたが、AWS が AG-UI プロトコルをインフラレベルでサポートしたことは業界全体にとって大きな前進です。開発者は今すぐ、より直感的で強力なエージェントアプリケーションの構築に取り掛かれるでしょう。
AI エージェントはチャット以上のことができます。適切なプロトコルがあれば、エージェントは会話の途中でインタラクティブなチャートをインライン表示したり、共有キャンバスをリアルタイムで更新したり、実行中に一時停止して次の手順に進む前に承認を求めることもできます。これらの相互作用(生成 UI、共有状態、人間によるループ処理)には、エージェントバックエンドがフロントエンドに動的イベントを通信するための標準的な方法が必要です。
AG-UI (Agent-User Interaction Protocol) は、この標準を定義するオープンプロトコルです。これは複数のエージェントフレームワーク(Strands Agents, LangGraph, CrewAI)およびフロントエンドライブラリ(React, Angular, Vue)と連携します。AG-UI を使用すれば、エージェントコードとフロントエンドコードは分離された状態を保ちます。バックエンドには最適なフレームワークを、フロントエンドには最適なライブラリを選択し、AG-UI がそれらを接続します。
Amazon Bedrock AgentCore は、生成 AI 向けの Amazon Bedrock サービスファミリーの一部です。AgentCore は、あらゆるフレームワークとモデルを使用して、AI エージェントを安全に大規模で構築・展開・運用するためのエージェントプラットフォームです。
本記事では、AG-UI が Amazon Bedrock AgentCore 上でインタラクティブなエージェントフロントエンドを構築するために、Fullstack AgentCore Solution Template (FAST) にどのように統合されるかを解説します。その後、CopilotKit がこれに生成型 UI(ジェネレーティブ UI)、共有状態、人間を介したループ処理(ヒューマン・イン・ザ・ループ)の機能を追加し、すべてが Amazon Bedrock AgentCore 上でデプロイされる様子を示します。
ソリューションの概要
Amazon Bedrock AgentCore Runtime は、AI エージェントやツールのデプロイおよび実行のための安全でサーバーレスかつ目的に特化したホスティング環境を提供します。AgentCore Runtime は複数のエージェントプロトコルをサポートしています。Model Context Protocol (MCP) はエージェントをツールに接続し、Agent2Agent (A2A) はエージェント同士を接続し、AG-UI はエージェントをユーザーに接続します。AG-UI プロトコルフラグ付きのエージェントコンテナをデプロイすると、AgentCore は透過的なプロキシとして機能します。認証(Amazon Cognito を介した Signature Version 4 [SigV4] または OAuth 2.0)、セッションの分離、スケーリング、観測可能性を処理します。あなたのコンテナは、AG-UI リクエスト用の POST /invocations と、ポート 8080 でのヘルスチェック用の GET /ping を公開します。AgentCore はリクエストを変更せずに通過させます。詳細については、Deploy AGUI servers in AgentCore Runtime をご覧ください。
FAST は、すぐにデプロイ可能なスタータープロジェクトです。これは、React フロントエンドと Amazon Cognito による認証を備え、AWS Cloud Development Kit (AWS CDK) で定義された AgentCore Runtime、Gateway、Identity、Memory、Code Interpreter を接続するものです。Strands Agents、LangGraph、Claude Agent SDK 用のエージェントパターンも同梱されています。FAST v0.4.1 では、単一のフロントエンドパーサーを共有する 2 つの AG-UI パターン (agui-strands-agent および agui-langgraph-agent) が追加されました。FAST のアーキテクチャとデプロイに関する完全なウォークスルーについては、Amazon Bedrock AgentCore 向けのフルスタックスターターテンプレートでエージェント型アプリケーション開発を加速する をご覧ください。
このソリューションには 2 つのレイヤーがあります。FAST 内の AG-UI は、2 つの新しいエージェントパターンと、両方を処理する単一のフロントエンドパーサーを提供し、フロントエンドがどのエージェントフレームワークが実行されているかを知らなくても済むようにします。CopilotKit + FAST は、FAST の組み込みチャット UI を CopilotKit に置き換えたスタンドアロンのサンプルです。これにより、ジェネレーティブ UI(インラインのチャートやコンポーネント)、双方向共有状態(To-Do キャンバス)、人間をループに組み込んだインタラクション(エージェントを一時停止して入力を待つ会議スケジューラー)が追加されます。両方のレイヤーは、Cognito 認証、MCP ツール接続用の AgentCore Gateway、永続的な会話のための AgentCore Memory を備えた AgentCore Runtime でデプロイされます。

アーキテクチャの概要。フロントエンドは AG-UI イベントを通じて AgentCore Runtime と通信します。AgentCore は認証、スケーリング、セッションの分離を処理します。エージェントランタイムはフレームワーク固有のイベントを AG-UI プロトコルに変換します。
ウォークスルー
このウォークスルーには 2 つの部分があります。まず、AG-UI パターンが FAST でどのように機能するか、および単一のフロントエンドパーサーが Strands および LangGraph の両方のバックエンドをどのように処理するかを示します。次に、CopilotKit サンプルをデプロイして、AgentCore 上の生成型 UI、共有状態、人間をループに組み込んだプロセスを実演します。
ソースコード:
- AG-UI パターンを含む FAST リポジトリ。
- CopilotKit と FAST のサンプル。
前提条件
このウォークスルーでは、以下の前提条件を満たしている必要があります:
- AWS CloudFormation、Amazon Elastic Container Registry (Amazon ECR)、Amazon Bedrock AgentCore、Amazon Cognito、および AWS Amplify に対する権限を持つ AWS アカウント。
- インストールして設定された AWS Command Line Interface (AWS CLI) v2。
- インストールされた AWS CDK。
- Node.js 18 以降および Python 3.11 以降。
- コンテナビルド用の Docker の実行環境。
- エージェントが使用するモデルに対して、Amazon Bedrock コンソールでモデルアクセスが有効になっていること。
AG-UI in FAST: One parser, two frameworks
agui-strands-agent パターンは、ag-ui-strands ライブラリ内の StrandsAgent を用いて Strands Agent をラップします。このラッパーは、Strands のストリーミングイベントを自動的に AG-UI サーバー送信イベントに変換します。
各リクエストごとに、Gateway MCP ツールを備えた新規エージェントが作成されます。AgentCore Memory は、session-manager プロバイダーを通じてスレッドごとにアタッチされるため、会話履歴は AgentCore Runtime のスケーリングを超えて維持されます。メモリ機能はオプトイン方式であり、MEMORY_ID が設定されていない場合、プロバイダーは None を返します:
# patterns/agui-strands-agent/agent.py
from ag_ui_strands import StrandsAgent, StrandsAgentConfig
from bedrock_agentcore.runtime import BedrockAgentCoreApp, RequestContext
from strands import Agent
app = BedrockAgentCoreApp()
モデルとコードインタープリターは、モジュール読み込み時に一度だけ構築する
MODEL = BedrockModel(model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0")
CODE_INTERPRETER = StrandsCodeInterpreterTools(REGION).execute_python_securely
@app.entrypoint
async def invocations(payload: dict, context: RequestContext):
input_data = RunAgentInput.model_validate(payload)
actor_id = extract_user_id_from_context(context)
# Fresh agent per request --- picks up the caller's identity and tools
agent = Agent(
model=MODEL,
system_prompt=SYSTEM_PROMPT,
tools=[create_gateway_mcp_client(actor_id), CODE_INTERPRETER],
session_manager=get_memory_session_manager(actor_id, session_id),
)
agui_agent = StrandsAgent(
agent=agent,
name="agui_strands_agent",
config=StrandsAgentConfig(
session_manager_provider=make_memory_provider(actor_id),
replay_history_into_strands=False,
),
)
async for event in agui_agent.run(input_data):
yield event.model_dump(mode="json", by_alias=True, exclude_none=True)
BedrockAgentCoreApp は、AgentCore Runtime のヘッダー(WorkloadAccessToken, Authorization, Session-Id)を読み取り、コンテキスト変数を設定します。これにより、ゲートウェイ認証とメモリ機能は HTTP パターンと同じように動作します。
agui-langgraph-agent パターンでは、copilotkit ライブラリから LangGraphAGUIAgent を使用します。このパターンは、各リクエストごとにコンパイルされたグラフを新規に構築するため、各呼び出しで呼び出し元にスコープされた MCP ツールが利用可能になります。AgentCore Memory もここではオプトイン方式です:ヘルパー関数は MEMORY_ID が設定されていない場合に None を返すため、メモリのプロビジョニングなしでもこのパターンを実行できます。
patterns/agui-langgraph-agent/agent.py
from copilotkit import CopilotKitMiddleware, LangGraphAGUIAgent
async def build_graph(actor_id: str):
"""Gateway ツールを使用して、新鮮なコンパイル済み LangGraph を構築する。"""
mcp_client = await create_gateway_mcp_client(actor_id)
tools = await mcp_client.get_tools()
tools.append(CODE_INTERPRETER)
return create_agent(
model=MODEL,
tools=tools,
checkpointer=get_memory_saver(), # MEMORY_ID が設定されていない場合は None
middleware=[CopilotKitMiddleware()],
system_prompt=SYSTEM_PROMPT,
)
@app.entrypoint
async def invocations(payload: dict, context: RequestContext):
input_data = RunAgentInput.model_validate(payload)
actor_id = extract_user_id_from_context(context)
graph = await build_graph(actor_id)
agui_agent = LangGraphAGUIAgent(
name="agui_langgraph_agent",
graph=graph,
config={"configurable": {"actor_id": actor_id}},
)
async for event in agui_agent.run(input_data):
yield event.model_dump(mode="json", by_alias=True, exclude_none=True)
両方のパターンは同じ AG-UI イベントを生成します。このプロトコルは、Server-Sent Events (SSE: サーバー送信イベント) 上の型付きイベントストリームを定義しています。例えば、単一のツール呼び出しでは以下のシーケンスが発生します:
data: {"type": "RUN_STARTED", "threadId": "t1", "runId": "r1"}
data: {"type": "TEXT_MESSAGE_START", "messageId": "m1", "role": "assistant"}
data: {"type": "TEXT_MESSAGE_CONTENT", "messageId": "m1", "delta": "Let me check "}
data: {"type": "TEXT_MESSAGE_CONTENT", "messageId": "m1", "delta": "that for you."}
data: {"type": "TEXT_MESSAGE_END", "messageId": "m1"}
data: {"type": "TOOL_CALL_START", "toolCallId": "tc1", "toolCallName": "get_weather"}
data: {"type": "TOOL_CALL_ARGS", "toolCallId": "tc1", "delta": "{\"location\": \"Seattle\"}"}
data: {"type": "TOOL_CALL_END", "toolCallId": "tc1"}
data: {"type": "TOOL_CALL_RESULT", "toolCallId": "tc1", "content": "{\"temp\": 55}"}
data: {"type": "RUN_FINISHED", "threadId": "t1", "runId": "r1"}
フロントエンドのパーサーは、各イベントをフロントエンドアクションにマッピングします:
// frontend/src/lib/agentcore-client/parsers/agui.ts
export const parseAguiChunk: ChunkParser = (line, callback) => {
if (!line.startsWith("data: ")) return;
const json = JSON.parse(line.substring(6).trim());
switch (json.type) {
case "TEXT_MESSAGE_CONTENT":
callback({ type: "text", content: json.delta ?? "" });
break;
case "TOOL_CALL_START":
callback({ type: "tool_use_start", toolUseId: json.toolCallId, name: json.toolCallName });
break;
case "TOOL_CALL_RESULT":
callback({ type: "tool_result", toolUseId: json.toolCallId, result: json.content ?? "" });
break;
case "RUN_FINISHED":
callback({ type: "result", stopReason: "end_turn" });
}
};
HTTP パターンと比較すると、Strands、LangGraph、Claude-agent-sdk のそれぞれは異なるストリーミング形式を処理するために個別のパーサーが必要となります。AG-UI を用いれば、バックエンドフレームワークは抽象化されるため、設定で agui-strands-agent から agui-langgraph-agent に切り替えてもフロントエンドに変更を加える必要はありません。
デプロイするには、infra-cdk/config.yaml でパターンを設定し、CDK を実行します:
backend:
pattern: agui-strands-agent # または agui-langgraph-agent
deployment_type: docker
infra-cdk に移動し、以下のコマンドを実行します。
cdk deploy --require-approval never
python3 ../scripts/deploy-frontend.py
CopilotKit + FAST:生成型 UI、共有状態、および人間を介したループ
ベースとなる FAST フロントエンドは機能的なチャットインターフェースを提供しますが、AG-UI はより豊かなインタラクションをサポートします。具体的には、エージェントがカスタム UI コンポーネントを描画したり、フロントエンドと状態を同期させたり、実行中にユーザー入力を待機したりする機能です。CopilotKit はこれらのパターンに特化して構築された React ライブラリです。CopilotKit チームは、AgentCore 上でこれらの機能をデモンストレーションするために、FAST を基盤とした サンプルアプリケーション を作成しました。このアプリケーションには LangGraph および Strands エージェントパターンが含まれており、デプロイ時にどちらかを選択できます。
生成型 UI は、フロントエンドの制御を重視する側からエージェントの自由度を重視する側まで幅広いスペクトラムにわたります。今回のサンプルは制御が効く側に位置しており、事前に構築された React コンポーネントをフロントエンドが所有し、エージェントはどのコンポーネントを描画するかを選択し、AG-UI イベントを通じてデータを供給します。このスペクトラムのさらに奥では、エージェントが記述的な UI 記述を返してフロントエンドが描画したり、フロントエンドが埋め込む完全な UI サーフェスを返したりすることもあります。AG-UI はこれらすべてをサポートしています。なぜなら、それは UI そのものではなく、イベントと状態ストリームを標準化しているからです。エージェントに任せる自由度が高くなるほど、開発者が負う責任も増えます。オープンエンドのサーフェスにはサンドボックス化や入力検証が必要となるためです。

CopilotKit のサンプルアーキテクチャ。CopilotKit Runtime Lambda は、ブラウザと AgentCore Runtime の間のサーバーサイドの橋渡し役として機能し、AG-UI イベントの解析、生成型 UI ルーティング、認証フォワーディングを処理します。
生成型 UI: エージェントが React コンポーネントを描画する
CopilotKit を使用すると、エージェントはテキストだけでなく、チャット内にカスタム React コンポーネントをインラインで描画できます。フロントエンドでは、AG-UI ツール呼び出しイベントを通じてエージェントが呼び出せるコンポーネントを登録します:
// エージェントが描画できるピートチャートを登録する
useComponent({
name: "pieChart",
description: "データをピートチャートとして表示します。",
parameters: PieChartPropsSchema,
render: PieChart,
});
エージェントが pieChart ツールを呼び出すと、CopilotKit は TOOL_CALL_START および TOOL_CALL_ARGS イベントをインターセプトし、PieChart コンポーネントを会話内に直接描画します。まずエージェントは query_data ツールを呼び出してサンプルのコンマ区切り値 (CSV) ファイルからデータを取得し、その結果をチャートコンポーネントに渡します。
シェアードステート:エージェントと同期する TODO キャンバス
このサンプルには、エージェントと UI の間で双方向に同期される TODO キャンバスが含まれています。ユーザーが「タスクを 3 つ追加して:API の設計、テストの記述、ステージング環境へのデプロイ」と指示すると、エージェントは manage_todos を呼び出し、AG-UI の STATE_SNAPSHOT イベントを通じてキャンバスがリアルタイムで更新されます。また、TODO は UI 上で直接編集することも可能です。Strands パターンによって現在の TODO がシステムプロンプトに注入されるため、エージェントは次のターンで更新されたステートを確認できます:
def state_context_builder(state: dict) -> str:
todos = state.get("todos", [])
if todos:
return f"\nCurrent todos:\n{json.dumps(todos, indent=2)}"
return ""
人間をループに組み込む:エージェントが一時停止して待機する
このサンプルは、実行の途中で一時停止し、タイムピッカーをレンダリングする会議スケジューラーを示しています。ユーザーが時間を選択すると、エージェントはその選択に基づいて処理を続行します:
useHumanInTheLoop({
name: "scheduleTime",
description: "Schedule a meeting with the user.",
parameters: z.object({
reasonForScheduling: z.string(),
meetingDuration: z.number(),
}),
render: ({ respond, status, args }) => (
),
});
これは AG-UI のツール呼び出しフローを通じて機能します。エージェントは scheduleTime に対して TOOL_CALL_START を発行し、CopilotKit がバックエンドツールの実行の代わりにピッカーをレンダリングします。その後、ユーザーからの応答が TOOL_CALL_RESULT として戻ってきます。
CopilotKit サンプルのデプロイ
FAST Samples リポジトリをクローンしてデプロイします:
git clone https://github.com/aws-samples/sample-FAST-applications.git
cd sample-FAST-applications/samples/copilotkit-generative-ui
cp config.yaml.example config.yaml
config.yaml を編集 --- stack_name_base と admin_user_email を設定
./deploy-langgraph.sh # または ./deploy-strands.sh
デプロイスクリプトは、Amazon Cognito ユーザープール、Amazon ECR リポジトリ、AgentCore Runtime(ランタイム)、AgentCore Gateway(ゲートウェイ)、AgentCore Memory(メモリ)、CopilotKit Runtime Lambda と Amazon API Gateway、そして AWS Amplify ホスティングを含むフルスタックをプロビジョニングします。完了したら、最後に表示される Amplify の URL を開いてログインしてください。CopilotKit チャットインターフェースに移動し、デプロイが正常に機能していることを確認するためのいくつかの簡単なチェックを行います:
- サンプルデータから円グラフを作成するようエージェントに依頼します。チャートは会話内にインラインでレンダリングされます。
- TODO キャンバスに 3 つのタスクを追加するよう依頼します。キャンバスがリアルタイムで更新されます。
- 会議のスケジュールを設定するよう依頼します。エージェントは一時的に停止し、時刻選択ウィジェットを表示します。
クリーンアップ
このウォークスルーでは、2 つの別々の s
原文を表示
AI agents can do more than chat. With the right protocol, an agent can render an interactive chart inline in your conversation, update a shared canvas in real time, or pause mid-execution to ask for your approval before proceeding. These interactions (generative UI, shared state, and human-in-the-loop) need a standard way for agent backends to communicate dynamic events to frontends.
AG-UI (Agent-User Interaction Protocol) is an open protocol that defines this standard. It works with multiple agent frameworks (Strands Agents, LangGraph, CrewAI) and frontend libraries (React, Angular, Vue). With AG-UI, your agent code and your frontend code stay decoupled. You pick the best framework for your backend and the best library for your frontend, and AG-UI connects them.
Amazon Bedrock AgentCore is part of the Amazon Bedrock family of services for generative AI. AgentCore is an agentic platform for building, deploying, and operating AI agents securely at scale, using any framework and any model.
This post walks through how AG-UI integrates into the Fullstack AgentCore Solution Template (FAST) to build interactive agent frontends on Amazon Bedrock AgentCore. We then show how CopilotKit extends this with generative UI, shared state, and human-in-the-loop interactions, all deployed on Amazon Bedrock AgentCore.
Overview of solution
Amazon Bedrock AgentCore Runtime provides a secure, serverless, and purpose-built hosting environment for deploying and running AI agents or tools. AgentCore Runtime supports several agent protocols. Model Context Protocol (MCP) connects agents to tools, Agent2Agent (A2A) connects agents to other agents, and AG-UI connects agents to users. When you deploy an agent container with the AG-UI protocol flag, AgentCore acts as a transparent proxy. It handles authentication (Signature Version 4 [SigV4] or OAuth 2.0 through Amazon Cognito), session isolation, scaling, and observability. Your container exposes POST /invocations for AG-UI requests and GET /ping for health checks on port 8080. AgentCore passes requests through unchanged. For more details, see Deploy AGUI servers in AgentCore Runtime.
FAST is a ready-to-deploy starter project. It connects AgentCore Runtime, Gateway, Identity, Memory, and Code Interpreter with a React frontend and Amazon Cognito authentication, all defined with AWS Cloud Development Kit (AWS CDK). It ships with agent patterns for Strands Agents, LangGraph, and the Claude Agent SDK. FAST v0.4.1 added two AG-UI patterns (agui-strands-agent and agui-langgraph-agent) that share a single frontend parser. For a full walkthrough of FAST’s architecture and deployment, see Accelerate agentic application development with a full-stack starter template for Amazon Bedrock AgentCore.
The solution has two layers. AG-UI in FAST provides two new agent patterns and a single frontend parser that handles both, so the frontend doesn’t need to know which agent framework is running. CopilotKit + FAST is a standalone sample that replaces FAST’s built-in chat UI with CopilotKit. It adds generative UI (inline charts and components), bidirectional shared state (a todo canvas), and human-in-the-loop interactions (a meeting scheduler that pauses the agent and waits for your input). Both layers deploy on AgentCore Runtime with Cognito authentication, AgentCore Gateway for MCP tool connectivity, and AgentCore Memory for persistent conversations.

Architecture overview. The frontend communicates with AgentCore Runtime through AG-UI events. AgentCore handles auth, scaling, and session isolation. The agent runtime translates framework-specific events into the AG-UI protocol.
Walkthrough
This walkthrough has two parts. First, we show how the AG-UI patterns work in FAST and how a single frontend parser handles both Strands and LangGraph backends. Second, we deploy the CopilotKit sample to demonstrate generative UI, shared state, and human-in-the-loop on AgentCore.
Source code:
- FAST repository (with AG-UI patterns).
- CopilotKit + FAST sample.
Prerequisites
For this walkthrough, you should have the following prerequisites:
- An AWS account with permissions for AWS CloudFormation, Amazon Elastic Container Registry (Amazon ECR), Amazon Bedrock AgentCore, Amazon Cognito, and AWS Amplify.
- AWS Command Line Interface (AWS CLI) v2 installed and configured.
- AWS CDK installed.
- Node.js 18 or later and Python 3.11 or later.
- Docker running, for container builds.
- Model access enabled in the Amazon Bedrock console for the model the agent uses.
AG-UI in FAST: One parser, two frameworks
The agui-strands-agent pattern wraps a Strands Agent in StrandsAgent from the ag-ui-strands library. The wrapper translates Strands streaming events into AG-UI Server-Sent Events automatically.
Each request creates a fresh agent with Gateway MCP tools. AgentCore Memory is attached per thread through a session-manager provider, so conversation history persists across AgentCore Runtime scaling. Memory is opt-in: the provider returns None when MEMORY_ID is unset:
# patterns/agui-strands-agent/agent.py
from ag_ui_strands import StrandsAgent, StrandsAgentConfig
from bedrock_agentcore.runtime import BedrockAgentCoreApp, RequestContext
from strands import Agent
app = BedrockAgentCoreApp()
# Build the model and Code Interpreter once at module load
MODEL = BedrockModel(model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0")
CODE_INTERPRETER = StrandsCodeInterpreterTools(REGION).execute_python_securely
@app.entrypoint
async def invocations(payload: dict, context: RequestContext):
input_data = RunAgentInput.model_validate(payload)
actor_id = extract_user_id_from_context(context)
# Fresh agent per request --- picks up the caller's identity and tools
agent = Agent(
model=MODEL,
system_prompt=SYSTEM_PROMPT,
tools=[create_gateway_mcp_client(actor_id), CODE_INTERPRETER],
session_manager=get_memory_session_manager(actor_id, session_id),
)
agui_agent = StrandsAgent(
agent=agent,
name="agui_strands_agent",
config=StrandsAgentConfig(
session_manager_provider=make_memory_provider(actor_id),
replay_history_into_strands=False,
),
)
async for event in agui_agent.run(input_data):
yield event.model_dump(mode="json", by_alias=True, exclude_none=True)BedrockAgentCoreApp reads the AgentCore Runtime headers (WorkloadAccessToken, Authorization, Session-Id) and populates context variables, so Gateway authentication and Memory work the same way as the HTTP patterns.
The agui-langgraph-agent pattern uses LangGraphAGUIAgent from the copilotkit library. It builds the compiled graph fresh on every request, so each invocation gets MCP tools scoped to the caller. AgentCore Memory is opt-in here too: the helper returns None when MEMORY_ID is unset, so you can run the pattern without provisioning Memory:
# patterns/agui-langgraph-agent/agent.py
from copilotkit import CopilotKitMiddleware, LangGraphAGUIAgent
async def build_graph(actor_id: str):
"""Build a fresh LangGraph compiled graph with Gateway tools."""
mcp_client = await create_gateway_mcp_client(actor_id)
tools = await mcp_client.get_tools()
tools.append(CODE_INTERPRETER)
return create_agent(
model=MODEL,
tools=tools,
checkpointer=get_memory_saver(), # None when MEMORY_ID is unset
middleware=[CopilotKitMiddleware()],
system_prompt=SYSTEM_PROMPT,
)
@app.entrypoint
async def invocations(payload: dict, context: RequestContext):
input_data = RunAgentInput.model_validate(payload)
actor_id = extract_user_id_from_context(context)
graph = await build_graph(actor_id)
agui_agent = LangGraphAGUIAgent(
name="agui_langgraph_agent",
graph=graph,
config={"configurable": {"actor_id": actor_id}},
)
async for event in agui_agent.run(input_data):
yield event.model_dump(mode="json", by_alias=True, exclude_none=True)Both patterns produce the same AG-UI events. The protocol defines a typed event stream over Server-Sent Events. For example, a single tool call produces this sequence:
data: {"type": "RUN_STARTED", "threadId": "t1", "runId": "r1"}
data: {"type": "TEXT_MESSAGE_START", "messageId": "m1", "role": "assistant"}
data: {"type": "TEXT_MESSAGE_CONTENT", "messageId": "m1", "delta": "Let me check "}
data: {"type": "TEXT_MESSAGE_CONTENT", "messageId": "m1", "delta": "that for you."}
data: {"type": "TEXT_MESSAGE_END", "messageId": "m1"}
data: {"type": "TOOL_CALL_START", "toolCallId": "tc1", "toolCallName": "get_weather"}
data: {"type": "TOOL_CALL_ARGS", "toolCallId": "tc1", "delta": "{\"location\": \"Seattle\"}"}
data: {"type": "TOOL_CALL_END", "toolCallId": "tc1"}
data: {"type": "TOOL_CALL_RESULT", "toolCallId": "tc1", "content": "{\"temp\": 55}"}
data: {"type": "RUN_FINISHED", "threadId": "t1", "runId": "r1"}The frontend parser maps each event to a frontend action:
// frontend/src/lib/agentcore-client/parsers/agui.ts
export const parseAguiChunk: ChunkParser = (line, callback) => {
if (!line.startsWith("data: ")) return;
const json = JSON.parse(line.substring(6).trim());
switch (json.type) {
case "TEXT_MESSAGE_CONTENT":
callback({ type: "text", content: json.delta ?? "" });
break;
case "TOOL_CALL_START":
callback({ type: "tool_use_start", toolUseId: json.toolCallId, name: json.toolCallName });
break;
case "TOOL_CALL_RESULT":
callback({ type: "tool_result", toolUseId: json.toolCallId, result: json.content ?? "" });
break;
case "RUN_FINISHED":
callback({ type: "result", stopReason: "end_turn" });
}
};Compare this to the HTTP patterns, where Strands, LangGraph, and Claude-agent-sdk each need a separate parser to handle their different streaming formats. With AG-UI, the backend framework is abstracted away. You can swap agui-strands-agent for agui-langgraph-agent in your configuration and the frontend doesn’t change.
To deploy, set the pattern in infra-cdk/config.yaml and run CDK:
backend:
pattern: agui-strands-agent # or agui-langgraph-agent
deployment_type: dockercd infra-cdk
cdk deploy --require-approval never
python3 ../scripts/deploy-frontend.pyCopilotKit + FAST: Generative UI, shared state, and human-in-the-loop
The base FAST frontend provides a functional chat interface, but AG-UI supports much richer interactions: agents rendering custom UI components, syncing state with the frontend, and pausing for user input mid-execution. CopilotKit is a React library built specifically for these patterns. The CopilotKit team built a sample application on top of FAST that demonstrates these capabilities on AgentCore. It includes both LangGraph and Strands agent patterns, and you pick one at deploy time.
Generative UI spans a spectrum from high frontend control to high agent freedom. This sample sits at the controlled end: the frontend owns prebuilt React components, and the agent chooses which to render and supplies the data over AG-UI events. Further along the spectrum, agents return declarative UI descriptions that the frontend renders, or full UI surfaces that the frontend embeds. AG-UI carries all three, because it standardizes the event and state stream rather than the UI itself. The more freedom you hand the agent, the more you take on: open-ended surfaces need sandboxing and input validation.

The CopilotKit sample architecture. The CopilotKit Runtime Lambda acts as a server-side bridge between the browser and AgentCore Runtime, handling AG-UI event parsing, generative UI routing, and authentication forwarding.
Generative UI: Agents render React components
With CopilotKit, the agent renders custom React components inline in the chat, not only text. The frontend registers components that the agent can invoke through AG-UI tool call events:
// Register a pie chart the agent can render
useComponent({
name: "pieChart",
description: "Displays data as a pie chart.",
parameters: PieChartPropsSchema,
render: PieChart,
});When the agent calls the pieChart tool, CopilotKit intercepts the TOOL_CALL_START and TOOL_CALL_ARGS events and renders the PieChart component directly in the conversation. The agent first calls a query_data tool to fetch data from a sample comma-separated values (CSV) file, then passes the results to the chart component.
Shared state: A todo canvas synced with the agent
The sample includes a todo canvas that stays in sync between the agent and the UI bidirectionally. When you tell the agent “Add three tasks: design the API, write tests, and deploy to staging,” the agent calls manage_todos and the canvas updates in real time through AG-UI STATE_SNAPSHOT events. You can also edit todos directly in the UI. The agent sees the updated state on its next turn because the Strands pattern injects the current todos into the system prompt:
def state_context_builder(state: dict) -> str:
todos = state.get("todos", [])
if todos:
return f"\nCurrent todos:\n{json.dumps(todos, indent=2)}"
return ""Human-in-the-loop: The agent pauses and waits
The sample demonstrates a meeting scheduler where the agent pauses mid-execution and renders a time picker. The user selects a time, and the agent continues with that selection:
useHumanInTheLoop({
name: "scheduleTime",
description: "Schedule a meeting with the user.",
parameters: z.object({
reasonForScheduling: z.string(),
meetingDuration: z.number(),
}),
render: ({ respond, status, args }) => (
),
});This works through AG-UI’s tool call flow: the agent emits TOOL_CALL_START for scheduleTime, CopilotKit renders the picker instead of executing a backend tool, and the user’s response flows back as a TOOL_CALL_RESULT.
Deploying the CopilotKit sample
Clone the FAST Samples repository and deploy:
git clone https://github.com/aws-samples/sample-FAST-applications.git
cd sample-FAST-applications/samples/copilotkit-generative-ui
cp config.yaml.example config.yaml
# Edit config.yaml --- set stack_name_base and admin_user_email
./deploy-langgraph.sh # or ./deploy-strands.shThe deploy script provisions the full stack: Amazon Cognito user pool, Amazon ECR repository, AgentCore Runtime, AgentCore Gateway, AgentCore Memory, the CopilotKit Runtime Lambda with Amazon API Gateway, and AWS Amplify hosting. When it finishes, open the Amplify URL printed at the end and log in. You’ll land on the CopilotKit chat interface, where a few quick checks confirm the deployment works:
- Ask the agent for a pie chart from the sample data. It renders inline in the conversation.
- Ask to add three tasks to the todo canvas. The canvas updates in real time.
- Ask to schedule a meeting. The agent pauses and shows a time picker.
Cleaning up
The walkthrough deploys two separate s
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み