参考Blog:aws.amazon.com/blogs/aws/i…
AWS AgentCore是一系列服务的组合,包括:
- AgentCore Runtime – 提供具有会话隔离功能的低延迟无服务器环境,支持任何代理框架(包括流行的开源框架、工具和模型),并处理多模式工作负载和长时间运行的代理。
- AgentCore Memory - 管理会话和长期记忆,为模型提供相关上下文,同时帮助代理从过去的交互中学习。
- AgentCore Observability — 通过元数据标记、自定义评分、轨迹检查和故障排除/调试过滤器提供代理执行的逐步可视化。
- AgentCore Identity – 使 AI 代理能够代表用户或在预先授权的用户同意下自行安全地访问 AWS 服务以及第三方工具和服务,例如 GitHub、Salesforce 和 Slack。
- AgentCore Gateway – 将现有 API 和 AWS Lambda 函数转换为代理就绪工具,提供跨协议(包括 MCP)和运行时发现的统一访问。
- AgentCore Browser – 提供托管的 Web 浏览器实例来扩展代理的 Web 自动化工作流程。
- AgentCore 代码解释器 - 提供一个隔离的环境来运行代理生成的代码。
AgentCore Runtime
AgentCore Runtime用于安全地部署、运行和扩展 AI 代理,提供隔离,以便每个用户会话在其自己的受保护环境中运行,以帮助防止数据泄漏 - 这是处理敏感数据的应用程序的关键要求。 其通过aws开源的轻量化firecracker VM,作为runtime的操作系统,类似lambda一样,可以快速拉起用于agent运行的serverless操作系统环境,做到VM级别的隔离。VM最长运行时间可以持续8小时,在15分钟没有请求后回收。
支持HTTP和MCP协议。端口分别为8080和8000.
示例代码如下:
import json
from strands import Agent, tool
from strands_tools import calculator, current_time
# Import the AgentCore SDK
from bedrock_agentcore.runtime import BedrockAgentCoreApp
WELCOME_MESSAGE = """
Welcome to the Customer Support Assistant! How can I help you today?
"""
SYSTEM_PROMPT = """
You are an helpful customer support assistant.
When provided with a customer email, gather all necessary info and prepare the response email.
When asked about an order, look for it and tell the full description and date of the order to the customer.
Don't mention the customer ID in your reply.
"""
@tool
def get_customer_id(email_address: str) -> str:
"Get customer ID from email address"
if email_address == "me@example.net":
response = { "customer_id": 123 }
else:
response = { "message": "customer not found" }
try:
return json.dumps(response)
except Exception as e:
return str(e)
@tool
def get_orders(customer_id: int) -> str:
"Get orders from customer ID"
if customer_id == 123:
response = [{
"order_id": 1234,
"items": [ "smartphone", "smartphone USB-C charger", "smartphone black cover"],
"date": "20250607"
}]
else:
response = { "message": "no order found" }
try:
return json.dumps(response)
except Exception as e:
return str(e)
@tool
def get_knowledge_base_info(topic: str) -> str:
"Get knowledge base info from topic"
response = []
if "smartphone" in topic:
if "cover" in topic:
response.append("To put on the cover, insert the bottom first, then push from the back up to the top.")
response.append("To remove the cover, push the top and bottom of the cover at the same time.")
if "charger" in topic:
response.append("Input: 100-240V AC, 50/60Hz")
response.append("Includes US/UK/EU plug adapters")
if len(response) == 0:
response = { "message": "no info found" }
try:
return json.dumps(response)
except Exception as e:
return str(e)
# Create an AgentCore app
app = BedrockAgentCoreApp()
agent = Agent(
model="us.anthropic.claude-sonnet-4-20250514-v1:0",
system_prompt=SYSTEM_PROMPT,
tools=[calculator, current_time, get_customer_id, get_orders, get_knowledge_base_info]
)
# Specify the entry point function invoking the agent
@app.entrypoint
def invoke(payload):
"""Handler for agent invocation"""
user_message = payload.get(
"prompt", "No prompt found in input, please guide customer to create a json payload with prompt key"
)
response = agent(user_message)
return response.message['content'][0]['text']
if __name__ == "__main__":
app.run()
Python
以上代码:
- 通过strands sdk,创建了三个tool,分别用于查询用户id,查询订单,和查询知识库;
- 创建了一个agent,底层模型为claude4 sonnet
- 创建了入口点函数
部署Agent runtime
代理初始配置:
(.venv) agent_core_demo % agentcore configure --entrypoint my_agent.py
Configuring Bedrock AgentCore...
Entrypoint parsed: file=/Users/seanmeng/Documents/demo_code/agent_core_demo/my_agent.py, bedrock_agentcore_name=my_agent
Agent name: my_agent
🔐 Execution Role
Press Enter to auto-create execution role, or provide execution role ARN/name to use existing
Execution role ARN/name (or press Enter to auto-create):
✓ Will auto-create execution role
🏗️ ECR Repository
Press Enter to auto-create ECR repository, or provide ECR Repository URI to use existing
ECR Repository URI (or press Enter to auto-create):
✓ Will auto-create ECR repository
🔍 Detected dependency file: requirements.txt
Press Enter to use this file, or type a different path (use Tab for autocomplete):
Path or Press Enter to use detected dependency file:
✓ Using detected file: requirements.txt
🔐 Authorization Configuration
By default, Bedrock AgentCore uses IAM authorization.
Configure OAuth authorizer instead? (yes/no) [no]: no
✓ Using default IAM authorization
Configuring BedrockAgentCore agent: my_agent
Generated .dockerignore
Generated Dockerfile: /Users/seanmeng/Documents/demo_code/agent_core_demo/Dockerfile
Generated .dockerignore: /Users/seanmeng/Documents/demo_code/agent_core_demo/.dockerignore
Setting 'my_agent' as default agent
╭────────────────────────────────────────────────────────────── Bedrock AgentCore Configured ───────────────────────────────────────────────────────────────╮
│ Configuration Summary │
│ │
│ Name: my_agent │
│ Runtime: Docker │
│ Region: us-east-1 │
│ Account: 436103886277 │
│ Execution Role: None │
│ ECR: Auto-create │
│ Authorization: IAM (default) │
│ │
│ Configuration saved to: /Users/seanmeng/Documents/demo_code/agent_core_demo/.bedrock_agentcore.yaml │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
可以看到,agentcore sdk自动为我们配置了sdk的执行iam role,ecr镜像仓库,并检查依赖文件。另外,还自动生成了dockerfile如下:
FROM public.ecr.aws/docker/library/python:3.13-slim
WORKDIR /app
COPY requirements.txt requirements.txt
# Install from requirements file
RUN pip install -r requirements.txt
RUN pip install aws-opentelemetry-distro>=0.10.1
# Set AWS region environment variable
ENV AWS_REGION=us-east-1
ENV AWS_DEFAULT_REGION=us-east-1
# Signal that this is running in Docker for host binding logic
ENV DOCKER_CONTAINER=1
# Create non-root user
RUN useradd -m -u 1000 bedrock_agentcore
USER bedrock_agentcore
EXPOSE 8080
EXPOSE 8000
# Copy entire project (respecting .dockerignore)
COPY . .
# Use the full module path
CMD ["opentelemetry-instrument", "python", "-m", "my_agent"]
部署agent runtime
(.venv) agent_core_demo % agentcore launch 130 ↵
🚀 Launching Bedrock AgentCore (codebuild mode - RECOMMENDED)...
• Build ARM64 containers in the cloud with CodeBuild
• No local Docker required (DEFAULT behavior)
• Production-ready deployment
💡 Deployment options:
• agentcore launch → CodeBuild (current)
• agentcore launch --local → Local development
• agentcore launch --local-build → Local build + cloud deploy
Starting CodeBuild ARM64 deployment for agent 'my_agent' to account 436103886277 (us-east-1)
Starting CodeBuild ARM64 deployment for agent 'my_agent' to account 436103886277 (us-east-1)
Setting up AWS resources (ECR repository, execution roles)...
Getting or creating ECR repository for agent: my_agent
Repository doesn't exist, creating new ECR repository: bedrock-agentcore-my_agent
⠹ Launching Bedrock AgentCore...✅ ECR repository available: 436103886277.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-my_agent
Getting or creating execution role for agent: my_agent
Using AWS region: us-east-1, account ID: 436103886277
Role name: AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
⠦ Launching Bedrock AgentCore...Role doesn't exist, creating new execution role: AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
Starting execution role creation process for agent: my_agent
✓ Role creating: AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
Creating IAM role: AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
⠏ Launching Bedrock AgentCore...✓ Role created: arn:aws:iam::436103886277:role/AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
⠼ Launching Bedrock AgentCore...✓ Execution policy attached: BedrockAgentCoreRuntimeExecutionPolicy-my_agent
Role creation complete and ready for use with Bedrock AgentCore
✅ Execution role available: arn:aws:iam::436103886277:role/AmazonBedrockAgentCoreSDKRuntime-us-east-1-e72c1a7c7a
Preparing CodeBuild project and uploading source...
⠦ Launching Bedrock AgentCore...Getting or creating CodeBuild execution role for agent: my_agent
Role name: AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
⠦ Launching Bedrock AgentCore...CodeBuild role doesn't exist, creating new role: AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
Creating IAM role: AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
⠧ Launching Bedrock AgentCore...✓ Role created: arn:aws:iam::436103886277:role/AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
Attaching inline policy: CodeBuildExecutionPolicy to role: AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
⠹ Launching Bedrock AgentCore...✓ Policy attached: CodeBuildExecutionPolicy
Waiting for IAM role propagation...
⠏ Launching Bedrock AgentCore...CodeBuild execution role creation complete: arn:aws:iam::436103886277:role/AmazonBedrockAgentCoreSDKCodeBuild-us-east-1-e72c1a7c7a
⠙ Launching Bedrock AgentCore...Created S3 bucket: bedrock-agentcore-codebuild-sources-436103886277-us-east-1
Using .dockerignore with 44 patterns
⠇ Launching Bedrock AgentCore...Uploaded source to S3: my_agent/20250811-124432.zip
⠸ Launching Bedrock AgentCore...Created CodeBuild project: bedrock-agentcore-my_agent-builder
Starting CodeBuild build (this may take several minutes)...
⠏ Launching Bedrock AgentCore...Starting CodeBuild monitoring...
⠧ Launching Bedrock AgentCore...🔄 QUEUED started (total: 1s)
⠏ Launching Bedrock AgentCore...✅ QUEUED completed in 5.9s
🔄 PROVISIONING started (total: 6s)
⠦ Launching Bedrock AgentCore...✅ PROVISIONING completed in 5.3s
🔄 PRE_BUILD started (total: 12s)
⠇ Launching Bedrock AgentCore...✅ PRE_BUILD completed in 11.3s
🔄 BUILD started (total: 23s)
⠦ Launching Bedrock AgentCore...✅ BUILD completed in 50.2s
🔄 POST_BUILD started (total: 73s)
⠙ Launching Bedrock AgentCore...✅ POST_BUILD completed in 10.8s
🔄 COMPLETED started (total: 84s)
✅ COMPLETED completed in 0.0s
🎉 CodeBuild completed successfully in 1m 24s
CodeBuild completed successfully
⠹ Launching Bedrock AgentCore...✅ CodeBuild project configuration saved
Deploying to Bedrock AgentCore...
⠼ Launching Bedrock AgentCore...✅ Agent created/updated: arn:aws:bedrock-agentcore:us-east-1:436103886277:runtime/my_agent-FPxnyk939t
Polling for endpoint to be ready...
⠧ Launching Bedrock AgentCore...Agent endpoint: arn:aws:bedrock-agentcore:us-east-1:436103886277:runtime/my_agent-FPxnyk939t/runtime-endpoint/DEFAULT
Deployment completed successfully - Agent: arn:aws:bedrock-agentcore:us-east-1:436103886277:runtime/my_agent-FPxnyk939t
✓ CodeBuild completed: bedrock-agentcore-my_agent-builder:2bc9fed7-3ffd-4b74-a3bd-7bbc53bd6986
✓ ARM64 image pushed to ECR: 436103886277.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-my_agent:latest
╭────────────────────────────────────────────────────────────── CodeBuild Deployment Complete ──────────────────────────────────────────────────────────────╮
│ CodeBuild ARM64 Deployment Successful! │
│ │
│ Agent Name: my_agent │
│ CodeBuild ID: bedrock-agentcore-my_agent-builder:2bc9fed7-3ffd-4b74-a3bd-7bbc53bd6986 │
│ Agent ARN: arn:aws:bedrock-agentcore:us-east-1:436103886277:runtime/my_agent-FPxnyk939t │
│ ECR URI: 436103886277.dkr.ecr.us-east-1.amazonaws.com/bedrock-agentcore-my_agent:latest │
│ │
│ ARM64 container deployed to Bedrock AgentCore. │
│ │
│ You can now check the status of your Bedrock AgentCore endpoint with: │
│ agentcore status │
│ │
│ You can now invoke your Bedrock AgentCore endpoint with: │
│ agentcore invoke '{"prompt": "Hello"}' │
│ │
│ 📋 Agent logs available at: │
│ /aws/bedrock-agentcore/runtimes/my_agent-FPxnyk939t-DEFAULT │
│ /aws/bedrock-agentcore/runtimes/my_agent-FPxnyk939t-DEFAULT/runtime-logs │
│ │
│ 💡 Tail logs with: │
│ aws logs tail /aws/bedrock-agentcore/runtimes/my_agent-FPxnyk939t-DEFAULT --follow │
│ aws logs tail /aws/bedrock-agentcore/runtimes/my_agent-FPxnyk939t-DEFAULT --since 1h │
╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
可以看到我们的agent runtime arm64的云端环境已经部署成功。
测试Agent runtime
(.venv) agent_core_demo % agentcore invoke '{"prompt": "From: me@example.net – Hi, I bought a smartphone from your store. I am traveling to Europe next week, will I be able to use the charger? Also, I struggle to remove the cover. Thanks, Danilo"}'
Payload:
{
"prompt": "From: me@example.net – Hi, I bought a smartphone from your store. I am traveling to Europe next week, will I be able to use the charger? Also, I
struggle to remove the cover. Thanks, Danilo"
}
Invoking BedrockAgentCore agent 'my_agent' via cloud endpoint
Session ID: 6f7fc3d3-5cb3-46b5-9e4f-4fc867ea4985
Response:
{
"ResponseMetadata": {
"RequestId": "6000214d-b39b-4434-a1b7-c87531813230",
"HTTPStatusCode": 200,
"HTTPHeaders": {
"date": "Mon, 11 Aug 2025 12:51:36 GMT",
"content-type": "application/json",
"transfer-encoding": "chunked",
"connection": "keep-alive",
"x-amzn-requestid": "6000214d-b39b-4434-a1b7-c87531813230",
"baggage": "Self=1-6899e6f5-73ee6e392484fd7e539c2c28,session.id=6f7fc3d3-5cb3-46b5-9e4f-4fc867ea4985",
"x-amzn-bedrock-agentcore-runtime-session-id": "6f7fc3d3-5cb3-46b5-9e4f-4fc867ea4985",
"x-amzn-trace-id": "Root=1-6899e6f5-112f7765579c90b408d17ba1;Self=1-6899e6f5-73ee6e392484fd7e539c2c28"
},
"RetryAttempts": 0
},
"runtimeSessionId": "6f7fc3d3-5cb3-46b5-9e4f-4fc867ea4985",
"traceId": "Root=1-6899e6f5-112f7765579c90b408d17ba1;Self=1-6899e6f5-73ee6e392484fd7e539c2c28",
"baggage": "Self=1-6899e6f5-73ee6e392484fd7e539c2c28,session.id=6f7fc3d3-5cb3-46b5-9e4f-4fc867ea4985",
"contentType": "application/json",
"statusCode": 200,
"response": [
"b'\"---\\\\n\\\\n**Subject: Re: Smartphone Charger and Cover Questions**\\\\n\\\\nHi Danilo,\\\\n\\\\nThank you for reaching out! I can see you
purchased a smartphone, USB-C charger, and black cover from us on June 7th, 2025.\\\\n\\\\n**Regarding your Europe travel question:**\\\\nGreat news! Your
smartphone charger is fully compatible for European travel. The charger operates on 100-240V AC, 50/60Hz, which covers all international voltage standards.
Additionally, your charger package includes US/UK/EU plug adapters, so you\\'ll have the correct plug adapter for European outlets. You\\'ll be all set for
your trip!\\\\n\\\\n**For the cover removal:**\\\\nI understand you\\'re having trouble removing the cover. Here\\'s the proper technique: push the top and
bottom of the cover simultaneously. This should allow it to come off easily. When you want to put it back on, insert the bottom first, then push from the
back up to the top.\\\\n\\\\nHave a wonderful trip to Europe, and don\\'t hesitate to reach out if you need any further assistance!\\\\n\\\\nBest
regards,\\\\nCustomer'",
"b' Support Team\"'"
]
}
在初次加载时,可以明显感觉到延迟产生。主要原因是因为镜像需要加载到runtime环境,冷启动造成的。