在 AgentCore 运行时部署 AG-UI 服务器
Amazon Bedrock R AgentCore untime 允许您在运行时中部署和 AgentCore 运行代理用户界面 (AG-UI) 服务器。本指南将引导您创建、测试和部署您的第一 AG-UI 台服务器。
在本部分中,您将学习:
有关更多信息 AG-UI,请参阅AG-UI 协议合约。
Amazon Bedrock AgentCore 如何支持 AG-UI
Amazon Bedrock AgentCore 的 AG-UI 协议支持通过充当代理层来实现与代理用户界面服务器的集成。配置为时 AG-UI,Amazon Bedrock AgentCore 希望容器8080在连接路径 HTTP/SSE 或/ws WebSocket 连接/invocations路径的端口上运行服务器。尽管 AG-UI 使用与 HTTP 协议相同的端口和路径,但运行时会根据部署配置期间指定的--protocol标志来区分它们。
Amazon Bedrock AgentCore 充当客户端和您的 AG-UI 容器之间的代理。来自 InvokeAgentRuntimeAPI 的请求无需修改即可传递到您的容器。Amazon Bedrock AgentCore 负责身份验证 (SigV4/OAuth 2.0)、会话隔离和扩展。
与其他协议的主要区别:
- 端口:
-
AG-UI 服务器在端口 8080 上运行(与 HTTP 相同,而 MCP 为 8000,A2A 为 9000)
- 路径
-
AG-UI 服务器/invocations/ws用于 HTTP/SSE 和用于 WebSocket (与 HTTP 协议相同)
- 消息格式
-
通过事件 (SSE) 使用 Server-Sent 事件流进行流式传输或 WebSocket 双向通信
- 协议焦点
-
Agent-to-User 交互(工具与 MCP 对比,代理对代理的 A2A)
- 身份验证
-
同时支持 Sigv4 和 OAuth 2.0 身份验证方案
有关更多信息,请参阅 https://docs.ag-ui.com/introduction。
AG-UI 与 AgentCore 运行时一起使用
在本教程中,您将创建、测试和部署 AG-UI 服务器。
有关完整的示例和特定于框架的实现,请参阅AG-UI 快速入门文档和 Dojo。AG-UI
先决条件
步骤 1:创建您的 AG-UI 服务器
AG-UI 由多个代理框架支持。选择最适合您需求的框架。 AWS Strands 为 Python 和. 提供了第一方 AG-UI 集成。 TypeScript
安装所需的程序包
安装 AG-UI 支持 AWS Strands 的软件包:
例
- Python
-
-
pip install fastapi
pip install uvicorn
pip install ag-ui-strands
- TypeScript
-
-
创建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 流量和 AgentCore 运行状况检查/invocations的服务器,这是 Runtime 期望从 AG-UI 容器中/ping获得的合约。
例
- Python
-
-
创建一个名为的新文件my_agui_server.py。此示例使用 AWS 带 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
-
-
创建一个名为的新文件my-agui-server.ts。此示例使用 AWS 带 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 事件 (SSE) 将键入的事件流式传输到客户端
- /invocations 端点
-
HTTP/SSE 通信的主要终端节点(与 HTTP 协议相同)
- 端口 8080
-
AG-UI 服务器在运行时默认在端口 8080 上 AgentCore 运行
第 2 步:在本地测试 AG-UI 服务器
在本地开发环境中运行和测试您的 AG-UI 服务器。
启动 AG-UI 服务器
在本地运行 AG-UI 服务器:
例
- Python
-
- TypeScript
-
-
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": {}
}'
您应该 AG-UI 会看到以 SSE 格式返回的事件流RUN_STARTED,包括TEXT_MESSAGE_CONTENT、和RUN_FINISHED事件。
第 3 步:将 AG-UI 服务器部署到 Bedrock AgentCore Runtime
AWS 使用 Amazon Bedrock AgentCore 入门工具包部署您的 AG-UI 服务器。
安装 Amazon Bedrock AgentCore 入门工具包:
pip install bedrock-agentcore-starter-toolkit
首先创建一个具有以下结构的项目文件夹:
例
- Python
-
-
## 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
-
-
## 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 令牌。
设置身份验证后,创建部署配置。传递与您使用的语言相匹配的入口点:
例
- Python
-
-
agentcore configure -e my_agui_server.py --protocol AGUI
- TypeScript
-
-
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 服务器并与事件流进行交互。
设置环境变量
设置环境变量
-
将持有者令牌导出为环境变量。有关不记名令牌设置,请参阅设置 Cognito 用户池进行身份验证。
export BEARER_TOKEN="<BEARER_TOKEN>"
-
导出代理 ARN。
export AGENT_ARN="arn:aws:bedrock-agentcore:us-west-2:accountId:runtime/my_agui_server-xyz123"
调用 AG-UI 服务器
要以编程方式调用 AG-UI 服务器,请选择与您的客户端匹配的语言:
例
- Python
-
-
安装所需的软件包:
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
-
-
安装所需的软件包:
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 客户端 SDK。
附录
设置 Cognito 用户池进行身份验证
有关 Cognito 的详细设置说明,请参阅 MCP 文档中的设置 Cognito 用户池进行身份验证。 AG-UI 服务器的设置过程是相同的。
问题排查
常见 AG-UI-specific 问题
以下是您可能遇到的常见问题:
- 端口冲突
-
AG-UI 在运行 AgentCore 时环境中,服务器必须在端口 8080 上运行
- 授权方法不匹配
-
确保您的请求使用与代理配置相同的身份验证方法(OAuth 或 Sigv4)
- 事件格式错误
-
确保您的事件符合 AG-UI 协议规范。参见AG-UI 活动文档