View a markdown version of this page

在 AgentCore 執行期中部署 AG-UI 伺服器 - Amazon Bedrock AgentCore

在 AgentCore 執行期中部署 AG-UI 伺服器

Amazon Bedrock AgentCore 執行期可讓您在 AgentCore 執行期中部署和執行 Agent User Interface (AG-UI) 伺服器。本指南會逐步解說如何建立、測試和部署您的第一個 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 或 /ws WebSocket 連線/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)

路徑

AG-UI 伺服器/invocations用於 HTTP/SSE 和 WebSocket /ws (與 HTTP 通訊協定相同)

訊息格式

透過伺服器傳送事件 (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 Quickstart 文件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 、公開 /invocations AG-UI 流量和運作狀態檢查/ping的伺服器,這是 AgentCore Runtime 從 AG-UI 容器預期的合約。

範例
Python
  1. 建立名為 my_agui_server.py 的新檔案。此範例使用 AWS Strands 搭配 AG-UI:

    # 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 的新檔案。此範例使用 AWS Strands 搭配 AG-UI:

    // 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 使用 Server-Sent Events (SSE) 將類型事件串流至用戶端

/invocations 端點

HTTP/SSE 通訊的主要端點 (與 HTTP 通訊協定相同)

連接埠 8080

根據預設,AgentCore 執行時間中的 AG-UI 伺服器會在連接埠 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 格式傳回的 AG-UI 事件串流,包括 RUN_STARTEDTEXT_MESSAGE_CONTENTRUN_FINISHED事件。

步驟 3:將您的 AG-UI 伺服器部署到 Bedrock AgentCore 執行期

AWS 使用 Amazon Bedrock AgentCore 入門工具組將 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 應用程式,請參閱 CopilotKitAG-UI TypeScript 用戶端 SDK

附錄

設定 Cognito 使用者集區以進行身分驗證

如需 Cognito 設定說明的詳細資訊,請參閱 MCP 文件中的設定 Cognito 使用者集區以進行身分驗證。AG-UI 伺服器的設定程序完全相同。

疑難排解

常見的 AG-UI-specific問題

以下是您可能遇到的常見問題:

連接埠衝突

AG-UI 伺服器必須在 AgentCore 執行期環境中的連接埠 8080 上執行

授權方法不符

確保您的請求使用與客服人員設定相同的身分驗證方法 (OAuth 或 SigV4)

事件格式錯誤

確保您的事件遵循 AG-UI 通訊協定規格。請參閱 AG-UI 事件文件