Bedrock AgentCore 托管 Agent 全流程:从本地开发到云端部署

Bedrock AgentCore 托管 Agent 全流程:从本地开发到云端部署,5 分钟跑通

上周折腾了两天 Agent 部署。本地 demo 跑得好好的,一上生产就各种问题——冷启动慢、内存溢出、并发扛不住、版本回滚手忙脚乱。

后来发现 Bedrock AgentCore 的托管运行时能解决大部分问题。它本质上是一个"Agent 专用的 Serverless 运行时"——你只管写 Agent 逻辑,基础设施的事(扩缩容、版本管理、健康检查、日志)全交给平台。

记录一下从本地开发到部署上线的完整流程。

为什么需要托管运行时

自己部署 Agent 服务要操心的事:

  1. 容器编排 — ECS/EKS + Task Definition + Service Discovery
  2. 扩缩容 — 根据请求量自动伸缩,Agent 调用延迟高(等模型响应),worker 数难估
  3. 版本管理 — 灰度发布、回滚、A/B 测试
  4. 健康检查 — Agent 可能"假活"(进程在但模型调不通)
  5. 成本控制 — Agent 空闲时也占着 GPU/CPU 资源

AgentCore 托管运行时把这些全包了。你交付一个 Python 包,它帮你跑起来。

本地开发

先用 Strands SDK 写一个简单的客服 Agent:

# agent.py
from strands import Agent, tool
from strands.models.bedrock import BedrockModel
import boto3

@tool
def query_order(order_id: str) -> dict:
    """根据订单号查询订单状态
    
    Args:
        order_id: 订单编号,如 ORD-20260610-001
    """
    # 实际场景连 DynamoDB
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table("orders")
    response = table.get_item(Key={"order_id": order_id})
    return response.get("Item", {"error": "订单不存在"})


@tool
def create_ticket(customer_id: str, issue: str, priority: str = "normal") -> dict:
    """创建客服工单
    
    Args:
        customer_id: 客户 ID
        issue: 问题描述
        priority: 优先级 (low/normal/high/urgent)
    """
    import uuid
    ticket_id = f"TK-{uuid.uuid4().hex[:8].upper()}"
    # 实际写入数据库
    return {"ticket_id": ticket_id, "status": "created", "priority": priority}


def create_agent():
    """创建客服 Agent 实例"""
    model = BedrockModel(
        model_id="anthropic.claude-sonnet-4-20250514-v1:0",
        region_name="us-east-1"
    )
    
    agent = Agent(
        model=model,
        system_prompt="""你是电商客服助手。职责:
1. 帮用户查询订单状态
2. 处理退款/换货请求(创建工单)
3. 回答常见问题

规则:
- 先确认用户身份(订单号或客户ID)
- 退款/换货必须创建工单,不能口头承诺
- 超出职责范围的问题,告知用户转人工
回答简洁友好,用中文。""",
        tools=[query_order, create_ticket]
    )
    return agent

本地测试:

# test_local.py
from agent import create_agent

agent = create_agent()
print(agent("我的订单 ORD-20260610-001 到哪了?"))
print(agent("快递一周没动了,我要退货"))

部署到 AgentCore

Step 1:创建部署包

# 项目结构
customer-service-agent/
├── agent.py           # Agent 逻辑
├── requirements.txt   # 依赖
└── agentcore.yaml     # 部署配置

requirements.txt

strands-agents>=0.1.0
strands-agents-tools>=0.1.0
boto3>=1.34.0

agentcore.yaml

name: customer-service-agent
runtime: python3.12
entry: agent.py
handler: create_agent

resources:
  memory: 512  # MB
  timeout: 120  # 秒(Agent 对话可能较长)

scaling:
  min_instances: 1    # 保持 1 个热实例避免冷启动
  max_instances: 10
  target_utilization: 0.7

environment:
  AWS_DEFAULT_REGION: us-east-1
  DYNAMODB_TABLE: orders

Step 2:部署

# 安装 AgentCore CLI
pip install agentcore-cli

# 部署(自动打包+上传+发布)
agentcore deploy \
  --config agentcore.yaml \
  --region us-east-1

部署完成后会返回一个 endpoint:

✅ Deployed: customer-service-agent v1
Endpoint: https://agentcore.us-east-1.api.aws/agents/customer-service-agent/invoke

Step 3:调用

import boto3
import json

client = boto3.client("bedrock-agentcore", region_name="us-east-1")

response = client.invoke_agent(
    agentName="customer-service-agent",
    input={
        "message": "我的订单 ORD-20260610-001 发货了吗?"
    },
    sessionId="user-12345-session-001"  # 用于维护多轮对话
)

print(json.loads(response["body"].read())["output"])

版本管理和灰度发布

# 发布新版本
agentcore deploy --config agentcore.yaml --version v2

# 灰度:90% 流量走 v1,10% 走 v2
agentcore traffic set \
  --agent customer-service-agent \
  --split v1=90,v2=10

# 确认无问题,全量切换
agentcore traffic set \
  --agent customer-service-agent \
  --split v2=100

# 发现问题,一键回滚
agentcore rollback --agent customer-service-agent --to v1

监控和日志

AgentCore 自动集成 CloudWatch:

  • 调用延迟 — P50/P95/P99
  • 工具调用成功率 — 每个 @tool 函数的成功/失败比
  • token 消耗 — 每次对话的 input/output token 数
  • 并发数 — 当前活跃会话数
# 查看实时日志
agentcore logs --agent customer-service-agent --follow

# 查看调用统计
agentcore metrics --agent customer-service-agent --period 1h

踩坑记录

  1. timeout 设太短 — Agent 调用模型 + 工具可能要 30-60 秒,默认 30 秒会超时。建议设 120 秒以上。

  2. 冷启动优化 — 如果 min_instances=0,首次请求要等容器启动 + 模型预热(约 5-8 秒)。对延迟敏感的场景保持 min_instances=1。

  3. 会话状态 — AgentCore 用 sessionId 管理多轮对话状态,确保同一用户的请求带相同的 sessionId,否则每次都是新对话。

  4. IAM 权限 — Agent 里调的 AWS 服务(DynamoDB、S3 等)需要在 AgentCore 的执行角色里加对应权限,不然运行时报 AccessDenied。

成本估算

  • 计算费用 — 按实际调用时长计费,空闲不收费(如果 min_instances=0)
  • 模型费用 — 按 Bedrock token 计费(Sonnet 约 $3/百万 input token)
  • 存储费用 — 对话历史存储,按 GB 计

对比自建 ECS 部署:省了 ALB 费用 + 闲时资源费用,月均能省 40-60%。

参考链接

posted @ 2026-06-10 20:09  亚马逊云开发者  阅读(16)  评论(0)    收藏  举报