bedrock-agentcore

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Amazon Bedrock AgentCore

Amazon Bedrock AgentCore

Overview

概述

Amazon Bedrock AgentCore is an agentic platform for building, deploying, and operating effective AI agents securely at scale—no infrastructure management needed. It provides framework-agnostic primitives that work with popular open-source frameworks (Strands, LangGraph, CrewAI, Autogen) and any model.
Purpose: Transform any AI agent into a production-ready application with enterprise-grade infrastructure
Pattern: Capabilities-based (6 independent service modules)
Key Principles (validated by AWS December 2025):
  1. Framework Agnostic - Works with any agent framework or model
  2. Zero Infrastructure - Fully managed, no ops overhead
  3. Session Isolation - Complete data isolation between sessions
  4. Enterprise Security - VPC, PrivateLink, identity integration
  5. Composable Services - Use only what you need
  6. Production Ready - Built for scale, reliability, and security
Quality Targets:
  • Deployment: < 5 minutes from code to production
  • Latency: Low-latency to 8-hour async workloads
  • Observability: Full CloudWatch integration

Amazon Bedrock AgentCore是一个无需管理基础设施,即可安全、大规模构建、部署和运营高效AI Agent的智能代理平台。它提供与主流开源框架(Strands、LangGraph、CrewAI、Autogen)及任何模型兼容的框架无关原语。
用途:将任意AI Agent转换为具备企业级基础设施的生产就绪型应用
模式:基于能力的架构(6个独立服务模块)
核心原则(经AWS 2025年12月验证):
  1. 框架无关 - 兼容任意Agent框架或模型
  2. 零基础设施 - 全托管,无运维开销
  3. 会话隔离 - 会话间数据完全隔离
  4. 企业级安全 - 支持VPC、PrivateLink、身份集成
  5. 可组合服务 - 按需使用所需服务
  6. 生产就绪 - 为规模、可靠性和安全而构建
质量指标
  • 部署:从代码到生产环境耗时<5分钟
  • 延迟:支持低延迟到8小时异步工作负载
  • 可观测性:完整集成CloudWatch

When to Use

适用场景

Use bedrock-agentcore when:
  • Building production AI agents on AWS
  • Need managed infrastructure for agent deployment
  • Require session isolation and enterprise security
  • Want to use existing agent frameworks (LangGraph, CrewAI, etc.)
  • Need browser automation or code execution capabilities
  • Integrating with existing identity providers
When NOT to Use:
  • Simple Bedrock model invocations (use bedrock-runtime)
  • Standard Bedrock Agents with action groups (use bedrock-agent)
  • Non-AWS deployments

在以下场景中使用bedrock-agentcore:
  • 在AWS上构建生产级AI Agent
  • 需要用于Agent部署的托管基础设施
  • 要求会话隔离和企业级安全
  • 希望使用现有Agent框架(LangGraph、CrewAI等)
  • 需要浏览器自动化或代码执行能力
  • 与现有身份提供商集成
不适用场景
  • 简单的Bedrock模型调用(使用bedrock-runtime)
  • 带操作组的标准Bedrock Agents(使用bedrock-agent)
  • 非AWS部署

Prerequisites

前置条件

Required

必需条件

  • AWS account with Bedrock access
  • IAM permissions for AgentCore services
  • Python 3.10+ (for SDK)
  • 拥有Bedrock访问权限的AWS账户
  • AgentCore服务的IAM权限
  • Python 3.10+(用于SDK)

Recommended

推荐配置

  • bedrock-agentcore-sdk-python
    installed
  • bedrock-agentcore-starter-toolkit
    CLI
  • Foundation model access enabled (Claude, etc.)
  • 已安装
    bedrock-agentcore-sdk-python
  • bedrock-agentcore-starter-toolkit
    CLI
  • 已启用基础模型访问权限(如Claude等)

Installation

安装步骤

bash
undefined
bash
undefined

Install SDK and CLI

安装SDK和CLI

pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit
pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit

Verify installation

验证安装

agentcore --help

---
agentcore --help

---

Core Services

核心服务

1. AgentCore Runtime

1. AgentCore Runtime

Secure, session-isolated compute for running agent code.
Boto3 Client:
python
import boto3
用于运行Agent代码的安全、会话隔离计算环境。
Boto3客户端:
python
import boto3

Data plane operations

数据平面操作

client = boto3.client('bedrock-agentcore')
client = boto3.client('bedrock-agentcore')

Control plane operations

控制平面操作

control = boto3.client('bedrock-agentcore-control')

**Create Agent Runtime**:
```python
control = boto3.client('bedrock-agentcore-control')

**创建Agent Runtime**:
```python

Using starter toolkit

使用入门工具包

agentcore configure -e main.py -n my-agent

agentcore configure -e main.py -n my-agent

agentcore deploy

agentcore deploy

Using boto3 control plane

使用boto3控制平面

response = control.create_agent_runtime( name='my-production-agent', description='Customer service agent', agentRuntimeArtifact={ 's3': { 'uri': 's3://my-bucket/agent-package.zip' } }, roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole', pythonRuntime='PYTHON_3_13', entryPoint=['main.py'] ) agent_runtime_arn = response['agentRuntimeArn']

**Invoke Agent**:
```python
response = control.create_agent_runtime( name='my-production-agent', description='Customer service agent', agentRuntimeArtifact={ 's3': { 'uri': 's3://my-bucket/agent-package.zip' } }, roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole', pythonRuntime='PYTHON_3_13', entryPoint=['main.py'] ) agent_runtime_arn = response['agentRuntimeArn']

**调用Agent**:
```python

Invoke deployed agent

调用已部署的Agent

response = client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/xxx', runtimeSessionId='session-123', payload={ 'prompt': 'What is my order status?', 'context': {'user_id': 'user-456'} } )
result = response['payload'] print(result)

**Agent Entry Point Structure**:
```python
from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent

app = BedrockAgentCoreApp(debug=True)
agent = Agent()

@app.entrypoint
def invoke(payload):
    """Main agent entry point"""
    user_message = payload.get("prompt", "Hello!")
    app.logger.info(f"Processing: {user_message}")

    result = agent(user_message)
    return {"result": result.message}

if __name__ == "__main__":
    app.run()

response = client.invoke_agent_runtime( agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/xxx', runtimeSessionId='session-123', payload={ 'prompt': 'What is my order status?', 'context': {'user_id': 'user-456'} } )
result = response['payload'] print(result)

**Agent入口点结构**:
```python
from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent

app = BedrockAgentCoreApp(debug=True)
agent = Agent()

@app.entrypoint
def invoke(payload):
    """Main agent entry point"""
    user_message = payload.get("prompt", "Hello!")
    app.logger.info(f"Processing: {user_message}")

    result = agent(user_message)
    return {"result": result.message}

if __name__ == "__main__":
    app.run()

2. AgentCore Gateway

2. AgentCore Gateway

Transforms existing APIs and Lambda functions into agent-compatible tools with semantic search discovery.
Create Gateway:
python
response = control.create_gateway(
    name='customer-service-gateway',
    description='Gateway for customer service tools',
    protocolType='REST'
)
gateway_arn = response['gatewayArn']
Add Gateway Target (Tool):
python
undefined
将现有API和Lambda函数转换为支持语义搜索发现的Agent兼容工具。
创建Gateway:
python
response = control.create_gateway(
    name='customer-service-gateway',
    description='Gateway for customer service tools',
    protocolType='REST'
)
gateway_arn = response['gatewayArn']
添加Gateway目标(工具):
python
undefined

Add an existing Lambda as a tool

添加现有Lambda作为工具

response = control.create_gateway_target( gatewayId='gateway-xxx', name='GetOrderStatus', description='Retrieves order status by order ID', targetConfiguration={ 'lambdaTarget': { 'lambdaArn': 'arn:aws:lambda:us-east-1:123456789012:function:GetOrder' } }, toolSchema={ 'name': 'get_order_status', 'description': 'Get the current status of a customer order', 'inputSchema': { 'type': 'object', 'properties': { 'order_id': { 'type': 'string', 'description': 'The unique order identifier' } }, 'required': ['order_id'] } } )

**Synchronize Tools**:
```python
response = control.create_gateway_target( gatewayId='gateway-xxx', name='GetOrderStatus', description='Retrieves order status by order ID', targetConfiguration={ 'lambdaTarget': { 'lambdaArn': 'arn:aws:lambda:us-east-1:123456789012:function:GetOrder' } }, toolSchema={ 'name': 'get_order_status', 'description': 'Get the current status of a customer order', 'inputSchema': { 'type': 'object', 'properties': { 'order_id': { 'type': 'string', 'description': 'The unique order identifier' } }, 'required': ['order_id'] } } )

**同步工具**:
```python

Sync gateway tools for discovery

同步网关工具以支持发现

control.synchronize_gateway_targets( gatewayId='gateway-xxx' )

---
control.synchronize_gateway_targets( gatewayId='gateway-xxx' )

---

3. Browser Runtime

3. Browser Runtime

Execute complex web-based workflows securely.
Start Browser Session:
python
response = client.start_browser_session(
    browserId='browser-xxx',
    sessionConfiguration={
        'timeout': 300,
        'viewport': {'width': 1920, 'height': 1080}
    }
)
session_id = response['browserSessionId']
Execute Browser Action:
python
undefined
安全执行复杂的基于Web的工作流。
启动浏览器会话:
python
response = client.start_browser_session(
    browserId='browser-xxx',
    sessionConfiguration={
        'timeout': 300,
        'viewport': {'width': 1920, 'height': 1080}
    }
)
session_id = response['browserSessionId']
执行浏览器操作:
python
undefined

Navigate and interact

导航并交互

response = client.update_browser_stream( browserSessionId=session_id, action={ 'navigate': {'url': 'https://example.com'}, 'click': {'selector': '#submit-button'}, 'type': {'selector': '#search', 'text': 'query'} } )

---
response = client.update_browser_stream( browserSessionId=session_id, action={ 'navigate': {'url': 'https://example.com'}, 'click': {'selector': '#submit-button'}, 'type': {'selector': '#search', 'text': 'query'} } )

---

4. Code Interpreter

4. Code Interpreter

Safely execute code for tasks like data analysis and visualization.
Start Code Interpreter Session:
python
response = client.start_code_interpreter_session(
    codeInterpreterId='interpreter-xxx'
)
session_id = response['codeInterpreterSessionId']
Execute Code:
python
response = client.invoke_code_interpreter(
    codeInterpreterSessionId=session_id,
    code='''
import pandas as pd
import matplotlib.pyplot as plt
安全执行代码以完成数据分析、可视化等任务。
启动Code Interpreter会话:
python
response = client.start_code_interpreter_session(
    codeInterpreterId='interpreter-xxx'
)
session_id = response['codeInterpreterSessionId']
执行代码:
python
response = client.invoke_code_interpreter(
    codeInterpreterSessionId=session_id,
    code='''
import pandas as pd
import matplotlib.pyplot as plt

Analyze data

Analyze data

df = pd.DataFrame({'x': [1,2,3,4,5], 'y': [2,4,6,8,10]}) plt.plot(df['x'], df['y']) plt.savefig('output.png') print(df.describe()) ''', language='PYTHON' )
output = response['output'] files = response['files'] # Generated files

---
df = pd.DataFrame({'x': [1,2,3,4,5], 'y': [2,4,6,8,10]}) plt.plot(df['x'], df['y']) plt.savefig('output.png') print(df.describe()) ''', language='PYTHON' )
output = response['output'] files = response['files'] # Generated files

---

5. Identity Integration

5. 身份集成

Native integration with existing identity providers for authentication and permission delegation.
Create OAuth2 Provider:
python
response = control.create_oauth2_credential_provider(
    name='okta-provider',
    credentialProviderVendor='OKTA',
    oauth2ProviderConfig={
        'clientId': 'your-client-id',
        'clientSecret': 'your-client-secret',
        'authorizationServerUrl': 'https://your-domain.okta.com/oauth2/default',
        'scopes': ['openid', 'profile', 'email']
    }
)
Create Workload Identity:
python
response = control.create_workload_identity(
    name='agent-identity',
    allowedRoleArns=['arn:aws:iam::123456789012:role/AgentRole']
)
Get Access Token:
python
undefined
与现有身份提供商原生集成,支持身份验证和权限委托。
创建OAuth2提供商:
python
response = control.create_oauth2_credential_provider(
    name='okta-provider',
    credentialProviderVendor='OKTA',
    oauth2ProviderConfig={
        'clientId': 'your-client-id',
        'clientSecret': 'your-client-secret',
        'authorizationServerUrl': 'https://your-domain.okta.com/oauth2/default',
        'scopes': ['openid', 'profile', 'email']
    }
)
创建工作负载身份:
python
response = control.create_workload_identity(
    name='agent-identity',
    allowedRoleArns=['arn:aws:iam::123456789012:role/AgentRole']
)
获取访问令牌:
python
undefined

Get token for workload

获取工作负载令牌

response = client.get_workload_access_token( workloadIdentityId='identity-xxx' ) access_token = response['accessToken']

---
response = client.get_workload_access_token( workloadIdentityId='identity-xxx' ) access_token = response['accessToken']

---

6. Observability

6. 可观测性

Real-time visibility via CloudWatch and OpenTelemetry.
Enable Observability:
python
undefined
通过CloudWatch和OpenTelemetry实现实时可见性。
启用可观测性:
python
undefined

In your agent entry point

在Agent入口点中

from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider
from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider

Configure tracing

配置追踪

provider = TracerProvider() trace.set_tracer_provider(provider)
provider = TracerProvider() trace.set_tracer_provider(provider)

Entry point with OTel

入口点配置OTel

entryPoint: ['opentelemetry-instrument', 'main.py']

entryPoint: ['opentelemetry-instrument', 'main.py']


**CloudWatch Metrics**:
- Token usage per session
- Latency (p50, p95, p99)
- Session duration
- Error rates
- Tool call success/failure

---

**CloudWatch指标**:
- 每会话令牌使用量
- 延迟(p50、p95、p99)
- 会话时长
- 错误率
- 工具调用成功/失败率

---

Boto3 Client Reference

Boto3客户端参考

Data Plane (
bedrock-agentcore
)

数据平面 (
bedrock-agentcore
)

MethodPurpose
invoke_agent_runtime
Execute agent logic
stop_runtime_session
Halt active session
list_sessions
List all sessions
start_browser_session
Initialize browser
stop_browser_session
End browser session
start_code_interpreter_session
Launch interpreter
invoke_code_interpreter
Execute code
batch_create_memory_records
Create memories
retrieve_memory_records
Fetch memories
get_workload_access_token
Get auth token
evaluate
Run evaluation
方法用途
invoke_agent_runtime
执行Agent逻辑
stop_runtime_session
终止活跃会话
list_sessions
列出所有会话
start_browser_session
初始化浏览器
stop_browser_session
结束浏览器会话
start_code_interpreter_session
启动解释器
invoke_code_interpreter
执行代码
batch_create_memory_records
创建记忆记录
retrieve_memory_records
获取记忆记录
get_workload_access_token
获取身份验证令牌
evaluate
运行评估

Control Plane (
bedrock-agentcore-control
)

控制平面 (
bedrock-agentcore-control
)

MethodPurpose
create_agent_runtime
Create runtime
delete_agent_runtime
Remove runtime
update_agent_runtime
Modify runtime
create_gateway
Create gateway
create_gateway_target
Add tool
create_memory
Create memory store
create_policy
Create policy
create_evaluator
Create evaluator
create_browser
Create browser
create_code_interpreter
Create interpreter

方法用途
create_agent_runtime
创建Runtime
delete_agent_runtime
删除Runtime
update_agent_runtime
修改Runtime
create_gateway
创建Gateway
create_gateway_target
添加工具
create_memory
创建记忆存储
create_policy
创建策略
create_evaluator
创建评估器
create_browser
创建浏览器实例
create_code_interpreter
创建代码解释器

Quick Start: Hello World Agent

快速入门:Hello World Agent

Step 1: Create Agent File

步骤1:创建Agent文件

python
undefined
python
undefined

main.py

main.py

from bedrock_agentcore import BedrockAgentCoreApp from strands import Agent
app = BedrockAgentCoreApp() agent = Agent(model="anthropic.claude-sonnet-4-20250514-v1:0")
@app.entrypoint def invoke(payload): prompt = payload.get("prompt", "Hello!") result = agent(prompt) return {"response": result.message}
if name == "main": app.run()
undefined
from bedrock_agentcore import BedrockAgentCoreApp from strands import Agent
app = BedrockAgentCoreApp() agent = Agent(model="anthropic.claude-sonnet-4-20250514-v1:0")
@app.entrypoint def invoke(payload): prompt = payload.get("prompt", "Hello!") result = agent(prompt) return {"response": result.message}
if name == "main": app.run()
undefined

Step 2: Configure and Deploy

步骤2:配置并部署

bash
undefined
bash
undefined

Configure

配置

agentcore configure -e main.py -n hello-world-agent
agentcore configure -e main.py -n hello-world-agent

Test locally

本地测试

python main.py & curl -X POST http://localhost:8080/invocations
-H "Content-Type: application/json"
-d '{"prompt": "Hello!"}'
python main.py & curl -X POST http://localhost:8080/invocations
-H "Content-Type: application/json"
-d '{"prompt": "Hello!"}'

Deploy to AWS

部署到AWS

agentcore deploy
agentcore deploy

Test deployed

测试已部署的Agent

agentcore invoke '{"prompt": "Hello from production!"}'
undefined
agentcore invoke '{"prompt": "Hello from production!"}'
undefined

Step 3: Invoke Programmatically

步骤3:程序化调用

python
import boto3

client = boto3.client('bedrock-agentcore')

response = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/hello-world',
    runtimeSessionId='test-session-1',
    payload={'prompt': 'What can you help me with?'}
)

print(response['payload'])

python
import boto3

client = boto3.client('bedrock-agentcore')

response = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/hello-world',
    runtimeSessionId='test-session-1',
    payload={'prompt': 'What can you help me with?'}
)

print(response['payload'])

Error Handling

错误处理

python
from botocore.exceptions import ClientError

try:
    response = client.invoke_agent_runtime(
        agentRuntimeArn=agent_arn,
        runtimeSessionId='session-1',
        payload={'prompt': 'test'}
    )
except ClientError as e:
    error_code = e.response['Error']['Code']

    if error_code == 'ResourceNotFoundException':
        print("Agent runtime not found")
    elif error_code == 'ValidationException':
        print("Invalid request parameters")
    elif error_code == 'ThrottlingException':
        print("Rate limited - implement backoff")
    elif error_code == 'AccessDeniedException':
        print("Check IAM permissions")
    else:
        raise

python
from botocore.exceptions import ClientError

try:
    response = client.invoke_agent_runtime(
        agentRuntimeArn=agent_arn,
        runtimeSessionId='session-1',
        payload={'prompt': 'test'}
    )
except ClientError as e:
    error_code = e.response['Error']['Code']

    if error_code == 'ResourceNotFoundException':
        print("Agent runtime未找到")
    elif error_code == 'ValidationException':
        print("请求参数无效")
    elif error_code == 'ThrottlingException':
        print("请求受限 - 实现退避策略")
    elif error_code == 'AccessDeniedException':
        print("检查IAM权限")
    else:
        raise

IAM Permissions

IAM权限

Minimum Execution Role

最小执行角色

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:InvokeAgentRuntime",
        "bedrock-agentcore:StartBrowserSession",
        "bedrock-agentcore:InvokeCodeInterpreter"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": "arn:aws:bedrock:*::foundation-model/*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}

json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:InvokeAgentRuntime",
        "bedrock-agentcore:StartBrowserSession",
        "bedrock-agentcore:InvokeCodeInterpreter"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": "arn:aws:bedrock:*::foundation-model/*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}

Related Skills

相关技能

  • bedrock-agentcore-policy: Cedar policy authoring and enforcement
  • bedrock-agentcore-evaluations: Agent testing and quality evaluation
  • bedrock-agentcore-memory: Episodic and short-term memory management
  • bedrock-agentcore-deployment: Production deployment patterns
  • bedrock-agentcore-multi-agent: Multi-agent orchestration (A2A protocol)
  • boto3-eks: For EKS-hosted agents
  • terraform-aws: Infrastructure as code

  • bedrock-agentcore-policy: Cedar策略编写与执行
  • bedrock-agentcore-evaluations: Agent测试与质量评估
  • bedrock-agentcore-memory: 情景记忆与短期记忆管理
  • bedrock-agentcore-deployment: 生产环境部署模式
  • bedrock-agentcore-multi-agent: 多Agent编排(A2A协议)
  • boto3-eks: 用于EKS托管的Agent
  • terraform-aws: 基础设施即代码

References

参考资料

  • references/gateway-configuration.md
    - Detailed gateway setup
  • references/identity-integration.md
    - OAuth and workload identity
  • references/troubleshooting.md
    - Common issues and solutions

  • references/gateway-configuration.md
    - 详细网关设置指南
  • references/identity-integration.md
    - OAuth与工作负载身份集成
  • references/troubleshooting.md
    - 常见问题与解决方案

Sources

来源