无需使用 AgentCore CLI 即可开始使用
无需使用 AgentCore CLI 即可创建 AgentCore 运行时代理。相反,您可以使用命令行工具组合来配置代理并将其部署到 AgentCore 运行时。
本教程介绍如何在不使用 AgentCore CLI 的情况下部署定制代理。自定义代理是在不使用 AgentCore Python SDK 的情况下构建的代理。在本教程中,自定义代理是使用 FastAPI 和 Docker 构建的。自定义代理遵循AgentCore 运行时要求,这意味着代理必须公开 /invocations POST 和 /ping GET 端点并打包在 Docker 容器中。Amazon Bedrock AgentCore 要求所有已部署的代理都使用 ARM64 架构。
注意
对于使用 AgentCore Python SDK 构建的代理,也可以使用这种方法。
快速入门设置
为代理启用可观察性
Amazon Bedrock 可 AgentCore 观测性可帮助您跟踪、调试和监控您在运行时中 AgentCore 托管的代理。要观察代理,请先按照启用 AgentCore 可观察性中的说明启用 CloudWatch 事务搜索。
安装 uv
在本示例中,我们将使用uv包管理器,但您可以使用任何 Python 实用程序或包管理器。要uv在 macOS 上安装,请执行以下操作:
curl -LsSf https://astral.sh/uv/install.sh | sh
有关其他平台上的安装说明,请参阅 uv 文档
创建您的代理项目
设置你的项目
-
创建并导航到您的项目目录:
mkdir my-custom-agent && cd my-custom-agent -
使用 Python 3.11 初始化项目:
uv init --python 3.11 -
添加所需的依赖关系(uv 会自动创建.venv):
uv add fastapi 'uvicorn[standard]' pydantic httpx strands-agents
代理合同要求
您的定制代理必须满足以下核心要求:
-
/invocations 端点:代理交互的 POST 端点(必填)
-
/ping 终端节点:获取用于运行状况检查的终端节点(必填)
-
Docker 容器:ARM64 容器化部署包
项目结构
注意:为方便起见,以下示例使用 FastAPI 服务器作为处理请求的 Web 服务器框架。
您的项目应具有以下结构:
my-custom-agent/ ├── agent.py # FastAPI application ├── Dockerfile # ARM64 container configuration ├── pyproject.toml # Created by uv init └── uv.lock # Created automatically by uv
完整链路代理示例
使用以下内容agent.py在项目根目录中创建:
示例 agent.py
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Dict, Any from datetime import datetime from strands import Agent app = FastAPI(title="Strands Agent Server", version="1.0.0") # Initialize Strands agent strands_agent = Agent() class InvocationRequest(BaseModel): input: Dict[str, Any] class InvocationResponse(BaseModel): output: Dict[str, Any] @app.post("/invocations", response_model=InvocationResponse) async def invoke_agent(request: InvocationRequest): try: user_message = request.input.get("prompt", "") if not user_message: raise HTTPException( status_code=400, detail="No prompt found in input. Please provide a 'prompt' key in the input." ) result = strands_agent(user_message) response = { "message": result.message, "timestamp": datetime.utcnow().isoformat() } return InvocationResponse(output=response) except Exception as e: raise HTTPException(status_code=500, detail=f"Agent processing failed: {str(e)}") @app.get("/ping") async def ping(): return {"status": "healthy"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8080)
这个实现:
-
创建具有所需端点的 FastAPI 应用程序
-
初始化用于处理用户消息的 Strands 代理
-
实现代理交互的
/invocationsPOST 端点 -
为运行状况检查实现
/pingGET 端点 -
将服务器配置为在主
0.0.0.0机和端口上运行8080
本地测试
测试您的代理
-
运行应用程序:
uv run uvicorn agent:app --host 0.0.0.0 --port 8080 -
测试
/ping端点(在另一个终端中):curl http://localhost:8080/ping -
测试
/invocations端点:curl -X POST http://localhost:8080/invocations \ -H "Content-Type: application/json" \ -d '{ "input": {"prompt": "What is artificial intelligence?"} }'
创建 dockerfile
使用以下内容Dockerfile在项目根目录中创建:
Dockerfile 示例
# Use uv's ARM64 Python base image FROM --platform=linux/arm64 ghcr.io/astral-sh/uv:python3.11-bookworm-slim WORKDIR /app # Copy uv files COPY pyproject.toml uv.lock ./ # Install dependencies (including strands-agents) RUN uv sync --frozen --no-cache # Copy agent file COPY agent.py ./ # Expose port EXPOSE 8080 # Run application CMD ["uv", "run", "uvicorn", "agent:app", "--host", "0.0.0.0", "--port", "8080"]
这个 Dockerfile:
-
使用 ARM64 Python 基础镜像(亚马逊 Bedrock AgentCore 需要)
-
设置工作目录
-
复制依赖文件并安装依赖关系
-
复制代理代码
-
暴露端口 8080
-
配置命令以运行应用程序
构建和部署 ARM64 映像
设置 docker buildx
Docker buildx 允许你为不同的架构构建镜像。使用以下方法进行设置:
docker buildx create --use
为 ARM64 构建并在本地进行测试
构建和测试您的图像
-
在本地构建映像以进行测试:
docker buildx build --platform linux/arm64 -t my-agent:arm64 --load. -
使用凭证进行本地测试(Strands 代理需要 AWS 凭证):
docker run --platform linux/arm64 -p 8080:8080 \ -e AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" \ -e AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" \ -e AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" \ -e AWS_REGION="$AWS_REGION" \ my-agent:arm64
创建 ECR 存储库并部署
部署到 ECR
-
创建 ECR 存储库:
aws ecr create-repository --repository-name my-strands-agent --region us-west-2 -
登录 ECR:
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin account-id.dkr.ecr.us-west-2.amazonaws.com -
构建并推送到 ECR:
docker buildx build --platform linux/arm64 -t account-id.dkr.ecr.us-west-2.amazonaws.com/my-strands-agent:latest --push. -
验证图片已推送:
aws ecr describe-images --repository-name my-strands-agent --region us-west-2
部署代理运行时
使用以下内容创建名为 deploy_agent.py 的文件:
示例 deploy_agent.py
import boto3 client = boto3.client('bedrock-agentcore-control', region_name='us-west-2') response = client.create_agent_runtime( agentRuntimeName='strands_agent', agentRuntimeArtifact={ 'containerConfiguration': { 'containerUri': 'account-id.dkr.ecr.us-west-2.amazonaws.com/my-strands-agent:latest' } }, networkConfiguration={"networkMode": "PUBLIC"}, roleArn='arn:aws:iam::account-id:role/AgentRuntimeRole', lifecycleConfiguration={ 'idleRuntimeSessionTimeout': 300, # 5 min, configurable 'maxLifetime': 1800 # 30 minutes, configurable }, ) print(f"Agent Runtime created successfully!") print(f"Agent Runtime ARN: {response['agentRuntimeArn']}") print(f"Status: {response['status']}")
运行脚本来部署代理:
uv run deploy_agent.py
此脚本使用该create_agent_runtime操作将您的代理部署到 Amazon Bedrock AgentCore。请务必account-id使用您的实际 AWS 账户 ID 进行替换,并确保 IAM 角色具有必要的权限。有关更多信息,请参阅 IAM AgentCore 运行时权限。
调用您的代理
使用以下内容创建名为 invoke_agent.py 的文件:
示例 invoke_agent.py
import boto3 import json agent_core_client = boto3.client('bedrock-agentcore', region_name='us-west-2') payload = json.dumps({ "input": {"prompt": "Explain machine learning in simple terms"} }) response = agent_core_client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:account-id:runtime/myStrandsAgent-suffix', runtimeSessionId='dfmeoagmreaklgmrkleafremoigrmtesogmtrskhmtkrlshmt', # Must be 33+ chars payload=payload, qualifier="DEFAULT" ) response_body = response['response'].read() response_data = json.loads(response_body) print("Agent Response:", response_data)
运行脚本以调用您的代理:
uv run invoke_agent.py
此脚本使用 InvokeAgentRuntime AWS SDK 操作向您部署的代理发送请求。请务必agentArn用您的实际值替换account-id和。
如果您计划将代理与 OAuth 集成,则无法使用 AWS SDK 进行调用。InvokeAgentRuntime相反,请向发出 HTTPS 请求 InvokeAgentRuntime。有关更多信息,请参阅使用入站身份验证和出站身份验证进行身份验证和授权。
预期的响应格式
当你调用代理时,你会收到这样的响应:
示例回复示例
{ "output": { "message": { "role": "assistant", "content": [ { "text": "# Artificial Intelligence in Simple Terms\n\nArtificial Intelligence (AI) is technology that allows computers to do tasks that normally need human intelligence. Think of it as teaching machines to:\n\n- Learn from information (like how you learn from experience)\n- Make decisions based on what they've learned\n- Recognize patterns (like identifying faces in photos)\n- Understand language (like when I respond to your questions)\n\nInstead of following specific step-by-step instructions for every situation, AI systems can adapt to new information and improve over time.\n\nExamples you might use every day include voice assistants like Siri, recommendation systems on streaming services, and email spam filters that learn which messages are unwanted." } ] }, "timestamp": "2025-07-13T01:48:06.740668" } }
停止运行时会话
要在配置之前停止正在运行的会话IdleRuntimeSessionTimeout(默认为 15 分钟)并节省任何潜在的失控成本,请执行:stop_runtime_session
使用以下内容创建名为 stop_runtime_session.py 的文件:
示例 stop_runtime_session.py
import boto3 agent_core_client = boto3.client('bedrock-agentcore', region_name='us-west-2') response = agent_core_client.stop_runtime_session( agentRuntimeArn='arn:aws:bedrock-agentcore:us-west-2:account-id:runtime/myStrandsAgent-suffix', runtimeSessionId='dfmeoagmreaklgmrkleafremoigrmtesogmtrskhmtkrlshmt', qualifier="DEFAULT" )
亚马逊 Bedrock AgentCore 要求摘要
-
平台:必须
linux/arm64 -
端点:
/invocationsPOST 和/pingGET 是必需的 -
ECR:必须将映像部署到 ECR
-
端口:应用程序在端口 8080 上运行
-
Strands 集成:使用 Strands Agent 进行 AI 处理
-
凭证:Strands 代理需要 AWS 凭据才能操作
结论
在本指南中,你已经学会了如何:
-
设置用于构建自定义代理的开发环境
-
创建实现所需端点的 FastAPI 应用程序
-
容器化您的代理,使其适合 ARM64 架构
-
在本地测试您的代理
-
将您的代理部署到 ECR
-
在 Amazon Bedrock 中创建代理运行时 AgentCore
-
调用已部署的代理
-
停止代理运行时会话
通过执行这些步骤,您可以创建和部署自定义代理,这些代理可以利用 Amazon Bedrock 的强大功能, AgentCore 同时保持对代理实施的完全控制。