View a markdown version of this page

AgentCore ランタイムに AG-UI サーバーをデプロイする - Amazon Bedrock AgentCore

AgentCore ランタイムに AG-UI サーバーをデプロイする

Amazon Bedrock AgentCore ランタイムを使用すると、AgentCore ランタイムでエージェントユーザーインターフェイス (AG-UI) AgentCore サーバーをデプロイして実行できます。このガイドでは、最初の AG-UI サーバーの作成、テスト、デプロイについて説明します。

このセクションでは、以下を行います。

  • Amazon Bedrock AgentCore が AG-UI をサポートする方法

  • AG-UI サーバーを作成する方法

  • サーバーをローカルでテストする方法

  • サーバーを にデプロイする方法 AWS

  • デプロイされたサーバーを呼び出す方法

AG-UI の詳細については、「AG-UI プロトコル契約」を参照してください。

Amazon Bedrock AgentCore が AG-UI をサポートする方法

Amazon Bedrock AgentCore の AG-UI プロトコルサポートにより、プロキシレイヤーとして機能することで、エージェントのユーザーインターフェイスサーバーとの統合が可能になります。AG-UI 用に設定されている場合、Amazon Bedrock AgentCore はコンテナが HTTP/SSE または WebSocket 接続/ws/invocationsパスのポート8080でサーバーを実行することを期待します。AG-UI は HTTP プロトコルと同じポートとパスを使用しますが、ランタイムはデプロイ設定中に指定された--protocolフラグに基づいてそれらを区別します。

Amazon Bedrock AgentCore は、クライアントと AG-UI コンテナ間のプロキシとして機能します。InvokeAgentRuntime API からのリクエストは、変更なしでコンテナに渡されます。Amazon Bedrock AgentCore は、認証 (SigV4/OAuth 2.0)、セッション分離、スケーリングを処理します。

他のプロトコルとの主な違い:

[ポート]

AG-UI サーバーはポート 8080 で実行されます (HTTP と同じ、MCP の場合は 8000、A2A の場合は 9000)

[Path] (パス)

AG-UI サーバー/invocationsが HTTP/SSE および WebSocket /wsに を使用する (HTTP プロトコルと同じ)

メッセージ形式

ストリーミングには Server-Sent Events (SSE)、双方向通信には WebSocket 経由でイベントストリームを使用します

プロトコルフォーカス

Agent-to-Userインタラクション (ツールの場合は MCP、agent-to-agentの場合は A2A)

認証

SigV4 認証スキームと OAuth 2.0 認証スキームの両方をサポート

詳細については、「https://docs.ag-ui.com/introduction」を参照してください。

AgentCore ランタイムでの AG-UI の使用

このチュートリアルでは、AG-UI サーバーを作成、テスト、デプロイします。

完全な例とフレームワーク固有の実装については、「AG-UI クイックスタートドキュメント」と「AG-UI Dojo」を参照してください。

前提条件

  • 選択した言語の基本的な理解に基づいてインストールされた Python 3.12 以降、または Node.js 18+ for TypeScript

  • 適切なアクセス許可とローカル認証情報が設定されている AWS アカウント

  • AG-UI プロトコルとイベントベースのagent-to-user通信の概念を理解する

ステップ 1: AG-UI サーバーを作成する

AG-UI は複数のエージェントフレームワークでサポートされています。ニーズに最適なフレームワークを選択します。 AWS Strands は、Python と TypeScript の両方にファーストパーティー AG-UI 統合を提供します。

必要なパッケージをインストールする

AG-UI AWS をサポートする Strands のパッケージをインストールします。

Python
  1. pip install fastapi pip install uvicorn pip install ag-ui-strands
TypeScript
  1. package.json 最初に を作成します。

    { "name": "my-agui-server", "type": "module", "scripts": { "build": "tsc" }, "dependencies": { "@ag-ui/aws-strands": "^0.1.0", "@strands-agents/sdk": "^1.1.0" }, "devDependencies": { "@types/express": "^5.0.0", "@types/node": "^22.0.0", "tsx": "^4.0.0", "typescript": "^5.0.0" } }

    次に、依存関係をインストールします。

    npm install

その他のフレームワークについては、「AG-UI フレームワークの統合」を参照してください。

最初の AG-UI サーバーを作成する

選択した言語で AG-UI サーバーファイルを作成します。以下のどちらの例も、ポート 8080 をリッスンし、AG-UI /invocations トラフィックとヘルスチェック/pingのために公開するサーバーを生成します。これは、AgentCore Runtime が AG-UI コンテナに期待する契約です。

Python
  1. という名前の新しいファイルを作成しますmy_agui_server.py。この例では、AG-UI AWS で Strands を使用します。

    # my_agui_server.py import uvicorn from fastapi import FastAPI, Request from fastapi.responses import StreamingResponse, JSONResponse from ag_ui_strands import StrandsAgent from ag_ui.core import RunAgentInput from ag_ui.encoder import EventEncoder from strands import Agent # Create a simple Strands agent strands_agent = Agent( system_prompt="You are a helpful assistant.", ) # Wrap with AG-UI protocol support agui_agent = StrandsAgent( agent=strands_agent, name="my_agent", description="A helpful assistant", ) # FastAPI server app = FastAPI() @app.post("/invocations") async def invocations(input_data: dict, request: Request): """Main AG-UI endpoint that returns event streams.""" accept_header = request.headers.get("accept") encoder = EventEncoder(accept=accept_header) async def event_generator(): run_input = RunAgentInput(**input_data) async for event in agui_agent.run(run_input): yield encoder.encode(event) return StreamingResponse( event_generator(), media_type=encoder.get_content_type() ) @app.get("/ping") async def ping(): return JSONResponse({"status": "Healthy"}) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8080)
TypeScript
  1. という名前の新しいファイルを作成しますmy-agui-server.ts。この例では、AG-UI AWS で Strands を使用します。

    // my-agui-server.ts import { Agent } from "@strands-agents/sdk"; import { StrandsAgent } from "@ag-ui/aws-strands"; import { createStrandsApp } from "@ag-ui/aws-strands/server"; async function main(): Promise<void> { // Create a simple Strands agent const strandsAgent = new Agent({ systemPrompt: "You are a helpful assistant.", }); // Wrap with AG-UI protocol support const aguiAgent = new StrandsAgent({ agent: strandsAgent, name: "my_agent", description: "A helpful assistant", }); // Express app exposing the AgentCore-required paths on port 8080 const app = await createStrandsApp(aguiAgent, { path: "/invocations", pingPath: "/ping", }); app.listen(8080, () => { console.log("AG-UI server running on port 8080"); }); } void main();

フレームワーク固有の完全な例については、以下を参照してください。

コードについて

イベントストリーム

AG-UI はサーバー送信イベント (SSE) を使用して、型付きイベントをクライアントにストリーミングします。

/invocations エンドポイント

HTTP/SSE 通信のプライマリエンドポイント (HTTP プロトコルと同じ)

ポート 8080

AG-UI サーバーは、デフォルトで AgentCore ランタイムでポート 8080 で実行されます。

ステップ 2: AG-UI サーバーをローカルでテストする

ローカル開発環境で AG-UI サーバーを実行してテストします。

AG-UI サーバーを起動する

AG-UI サーバーをローカルで実行します。

Python
  1. python my_agui_server.py
TypeScript
  1. npx tsx my-agui-server.ts

サーバーがポート で実行されていることを示す出力が表示されます8080

エンドポイントのテスト

適切にフォーマットされた AG-UI リクエストを使用して SSE エンドポイントをテストします。

curl -N -X POST http://localhost:8080/invocations \ -H "Content-Type: application/json" \ -d '{ "threadId": "test-123", "runId": "run-456", "state": {}, "messages": [{"role": "user", "content": "Hello, agent!", "id": "msg-1"}], "tools": [], "context": [], "forwardedProps": {} }'

、、 イベントなど、SSE 形式で返される RUN_STARTED AG-UI TEXT_MESSAGE_CONTENT RUN_FINISHEDイベントストリームが表示されます。

ステップ 3: AG-UI サーバーを Bedrock AgentCore ランタイムにデプロイする

Amazon Bedrock AgentCore スターターツールキット AWS を使用して、AG-UI サーバーを にデプロイします。

デプロイツールをインストールする

Amazon Bedrock AgentCore スターターツールキットをインストールします。

pip install bedrock-agentcore-starter-toolkit

まず、次の構造でプロジェクトフォルダを作成します。

Python
  1. ## Project Folder Structure your_project_directory/ ├── my_agui_server.py # Your main agent code ├── requirements.txt # Dependencies for your agent

    依存関係requirements.txtを使用して という名前の新しいファイルを作成します。

    fastapi uvicorn ag-ui-strands
TypeScript
  1. ## Project Folder Structure your_project_directory/ ├── my-agui-server.ts # Your main agent code ├── package.json # Dependencies for your agent └── tsconfig.json # TypeScript compiler configuration

    を作成するtsconfig.json:

    { "compilerOptions": { "target": "ES2022", "lib": ["ES2022", "DOM"], "module": "NodeNext", "moduleResolution": "NodeNext", "outDir": "./dist", "strict": true, "esModuleInterop": true }, "include": ["*.ts"] }

認証用に Cognito ユーザープールを設定する

デプロイされたサーバーへの安全なアクセスのための認証を設定します。Cognito のセットアップ手順の詳細については、「認証用の Cognito ユーザープールのセットアップ」を参照してください。これにより、デプロイされたサーバーへの安全なアクセスに必要な OAuth トークンが提供されます。

AG-UI サーバーをデプロイ用に設定する

認証を設定したら、デプロイ設定を作成します。使用した言語に一致するエントリポイントを渡します。

Python
  1. agentcore configure -e my_agui_server.py --protocol AGUI
TypeScript
  1. agentcore configure -e my-agui-server.ts --protocol AGUI
  • AGUI としてプロトコルを選択する

  • 前のステップでセットアップとして OAuth 設定を使用して を設定する

にデプロイする AWS

エージェントをデプロイします。

agentcore deploy

デプロイ後、エージェントランタイム ARN は次のようになります。

arn:aws:bedrock-agentcore:us-west-2:accountId:runtime/my_agui_server-xyz123

ステップ 4: デプロイされた AG-UI サーバーを呼び出す

デプロイされた Amazon Bedrock AgentCore AG-UI サーバーを呼び出し、イベントストリームとやり取りします。

環境変数をセットアップする

環境変数をセットアップする

  1. ベアラートークンを環境変数としてエクスポートします。ベアラートークンのセットアップについては、「認証用に Cognito ユーザープールを設定する」を参照してください。

    export BEARER_TOKEN="<BEARER_TOKEN>"
  2. エージェント ARN をエクスポートします。

    export AGENT_ARN="arn:aws:bedrock-agentcore:us-west-2:accountId:runtime/my_agui_server-xyz123"

AG-UI サーバーを呼び出す

プログラムで AG-UI サーバーを呼び出すには、クライアントに一致する言語を選択します。

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

    pip install httpx httpx-sse

    次に、次のクライアントコードを使用します。

    import asyncio import json import os from urllib.parse import quote from uuid import uuid4 import httpx from httpx_sse import aconnect_sse async def invoke_agui_agent(message: str): agent_arn = os.environ.get('AGENT_ARN') bearer_token = os.environ.get('BEARER_TOKEN') escaped_arn = quote(agent_arn, safe='') url = f"https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/{escaped_arn}/invocations?qualifier=DEFAULT" headers = { "Authorization": f"Bearer {bearer_token}", "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id": str(uuid4()), } payload = { "threadId": str(uuid4()), "runId": str(uuid4()), "messages": [{"id": str(uuid4()), "role": "user", "content": message}], "state": {}, "tools": [], "context": [], "forwardedProps": {}, } async with httpx.AsyncClient(timeout=300) as client: async with aconnect_sse(client, "POST", url, headers=headers, json=payload) as sse: async for event in sse.aiter_sse(): data = json.loads(event.data) event_type = data.get("type") if event_type == "TEXT_MESSAGE_CONTENT": print(data.get("delta", ""), end="", flush=True) elif event_type == "RUN_ERROR": print(f"Error: {data.get('code')} - {data.get('message')}") asyncio.run(invoke_agui_agent("Hello!"))
TypeScript
  1. 必要なパッケージをインストールします。

    npm install @ag-ui/client

    次に、次のクライアントコードを使用します。

    import { HttpAgent, AgentSubscriber } from "@ag-ui/client"; import { randomUUID } from "crypto"; async function invokeAguiAgent(message: string): Promise<void> { const agentArn = process.env.AGENT_ARN!; const bearerToken = process.env.BEARER_TOKEN!; const escapedArn = encodeURIComponent(agentArn); const agent = new HttpAgent({ url: `https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/${escapedArn}/invocations?qualifier=DEFAULT`, headers: { Authorization: `Bearer ${bearerToken}`, "X-Amzn-Bedrock-AgentCore-Runtime-Session-Id": randomUUID(), }, }); agent.messages = [{ id: randomUUID(), role: "user", content: message }]; const subscriber: AgentSubscriber = { onTextMessageContentEvent: ({ event }) => { process.stdout.write(event.delta); }, onRunErrorEvent: ({ event }) => { console.error(`Error: ${event.code ?? "RUN_ERROR"} - ${event.message}`); }, }; await agent.runAgent({}, subscriber); } void invokeAguiAgent("Hello!");

完全な UI アプリケーションの構築については、CopilotKit」または「AG-UI TypeScript client SDK」を参照してください。

付録

認証用に Cognito ユーザープールを設定する

Cognito のセットアップ手順の詳細については、MCP ドキュメントの「認証用に Cognito ユーザープールを設定する」を参照してください。AG-UI サーバーのセットアッププロセスは同じです。

トラブルシューティング

AG-UI-specific一般的な問題

以下は、発生する可能性のある一般的な問題です。

ポートの競合

AG-UI サーバーは AgentCore ランタイム環境のポート 8080 で実行する必要があります

認可方法の不一致

リクエストで、エージェントが設定されたのと同じ認証方法 (OAuth または SigV4) を使用していることを確認します。

イベント形式のエラー

イベントが AG-UI プロトコル仕様に従っていることを確認します。「AG-UI イベントのドキュメント」を参照してください。