31.1 Amazon Bedrock 集成
31.1.1 Bedrock 概述
Amazon Bedrock 是 AWS 提供的完全托管服务,可以通过 API 访问基础模型,包括 Anthropic 的 Claude 模型。通过 Bedrock 使用 Claude Code 可以为企业带来以下优势:
Bedrock 的优势
- AWS 原生集成 :与 AWS IAM、CloudTrail、CloudWatch 等服务无缝集成
- 企业级安全 :符合 AWS 安全标准和合规要求
- 灵活的部署 :支持多个 AWS 区域,满足数据驻留要求
- 成本管理 :通过 AWS Cost Explorer 和 Budgets 进行成本控制
- 高可用性 :利用 AWS 的全球基础设施和冗余机制
适用场景
- 已经使用 AWS 基础设施的企业
- 需要符合特定数据驻留法规的组织
- 要求使用 AWS IAM 进行身份验证的场景
- 需要集中监控和日志记录的环境
python
## 31.1.2 Bedrock 配置步骤
### 1\. 前置条件检查
class BedrockPrerequisitesChecker: """Bedrock 前置条件检查器"""
def **init**(self): self.checks = { 'aws_account': False, 'bedrock_enabled': False, 'model_access': False, 'iam_permissions': False, 'cli_configured': False }
def check_all(self) -> PrerequisiteReport: """检查所有前置条件""" report = PrerequisiteReport()
# 检查 AWS 账户
self.checks['aws_account'] = self._check_aws_account()
# 检查 Bedrock 是否启用
self.checks['bedrock_enabled'] = self._check_bedrock_enabled()
# 检查模型访问权限
self.checks['model_access'] = self._check_model_access()
# 检查 IAM 权限
self.checks['iam_permissions'] = self._check_iam_permissions()
# 检查 CLI 配置
self.checks['cli_configured'] = self._check_cli_configured()
# 生成报告
report.checks = self.checks report.all_passed = all(self.checks.values()) report.missing = [ check for check, passed in self.checks.items() if not passed ]return report
python
def _check_aws_account(self) -> bool: """检查 AWS 账户""" try: result = subprocess.run( ['aws', 'sts', 'get-caller-identity'], capture_output=True, text=True ) return result.returncode == 0 except Exception: return False
def _check_bedrock_enabled(self) -> bool: """检查 Bedrock 是否启用""" try: result = subprocess.run( ['aws', 'bedrock', 'list-foundation-models'], capture_output=True, text=True ) return result.returncode == 0 except Exception: return False
def _check_model_access(self) -> bool: """检查模型访问权限""" try: result = subprocess.run( ['aws', 'bedrock', 'list-inference-profiles'], capture_output=True, text=True ) return result.returncode == 0 except Exception: return False
### 2\. 提交用例详情首次使用 Anthropic 模型需要提交用例详情:
python
bash
bash
# 通过 AWS CLI 提交
aws bedrock create-model-customization-job \
--job-name "claude-code-use-case" \
--base-model-identifier "anthropic.claude-sonnet-4-5-20250929-v1:0" \
--customization-type "FINE_TUNING" \
--customization-config '{
"useCase": "Code generation and assistance",
"teamSize": "10-50",
"industry": "Technology"
}'
### 3. 配置 AWS 凭证
#### 选项 A:AWS CLI 配置
# 配置 AWS CLI
aws configure
# 输入您的 AWS 凭证
AWS Access Key ID: [您的访问密钥]
AWS Secret Access Key: [您的秘密密钥]
Default region name: us-east-1
Default output format: json
#### 选项 B:环境变量
bash
bash
# 设置环境变量
export AWS_ACCESS_KEY_ID=your-access-key-id
export AWS_SECRET_ACCESS_KEY=your-secret-access-key
export AWS_SESSION_TOKEN=your-session-token # 如果使用临时凭证
export AWS_REGION=us-east-1
#### 选项 C:AWS SSO
# 配置 SSO 配置文件
aws configure sso
# 登录
aws sso login --profile claude-code
# 使用配置文件
export AWS_PROFILE=claude-code
#### 选项 D:Bedrock API 密钥
bash
bash
# 使用 Bedrock API 密钥(推荐用于简化部署)
export AWS_BEARER_TOKEN_BEDROCK=your-bedrock-api-key
### 4. 启用 Claude Code Bedrock 集成
# 启用 Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
# 设置区域
export AWS_REGION=us-east-1
# 可选:为小型/快速模型设置不同区域
export ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION=us-west-2
### 5\. 配置模型
bash
bash
# 主模型
export ANTHROPIC_MODEL='global.anthropic.claude-sonnet-4-5-20250929-v1:0'
# 小型/快速模型
export ANTHROPIC_SMALL_FAST_MODEL='us.anthropic.claude-haiku-4-5-20251001-v1:0'
# 使用推理配置文件
export ANTHROPIC_MODEL='arn:aws:bedrock:us-east-2:your-account-id:application-inference-profile/your-model-id'
## 31.1.3 IAM 权限配置
### 基础 IAM 策略
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowModelAccess",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
"bedrock:ListInferenceProfiles"
],
"Resource": [
"arn:aws:bedrock:*:*:inference-profile/*",
"arn:aws:bedrock:*:*:application-inference-profile/*",
"arn:aws:bedrock:*:*:foundation-model/*"
]
},
{
"Sid": "AllowMarketplaceAccess",
"Effect": "Allow",
"Action": [
"aws-marketplace:ViewSubscriptions",
"aws-marketplace:Subscribe"
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:CalledViaLast": "bedrock.amazonaws.com"
}
}
}
]
}
### 严格 IAM 策略
bash
json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowSpecificModelAccess",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": [
"arn:aws:bedrock:us-east-1:123456789012:inference-profile/global.anthropic.claude-sonnet-4-5-20250929-v1:0",
"arn:aws:bedrock:us-west-2:123456789012:inference-profile/us.anthropic.claude-haiku-4-5-20251001-v1:0"
]
}
]
}
### IAM 角色创建
# 创建 IAM 角色
aws iam create-role \
--role-name ClaudeCodeBedrockRole \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "bedrock.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'
# 附加策略
aws iam put-role-policy \
--role-name ClaudeCodeBedrockRole \
--policy-name ClaudeCodeBedrockPolicy \
--policy-document file://bedrock-policy.json
## 31.1.4 高级配置
### 自动凭证刷新
bash
json
{
"awsAuthRefresh": "aws sso login --profile myprofile",
"env": {
"AWS_PROFILE": "myprofile",
"CLAUDE_CODE_USE_BEDROCK": "1",
"AWS_REGION": "us-east-1"
}
}
### 输出令牌优化
# Bedrock 推荐的令牌设置
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096
export MAX_THINKING_TOKENS=1024
### 提示缓存配置
bash
bash
# 启用提示缓存(默认启用)
# 如需禁用
export DISABLE_PROMPT_CACHING=1
## 31.1.5 监控和故障排除
### CloudWatch 监控
class BedrockMonitor:
"""Bedrock 监控器"""
def __init__(self):
self.cloudwatch = boto3.client('cloudwatch')
self.metrics = [
'InvokeModel',
'InvokeModelWithResponseStream',
'Latency',
'ErrorCount',
'5XXError',
'4XXError'
]
def setup_alarms(self, config: Dict):
"""设置告警"""
for metric in self.metrics:
alarm = self._create_alarm(metric, config)
self.cloudwatch.put_metric_alarm(**alarm)
def _create_alarm(self, metric: str, config: Dict) -> Dict:
"""创建告警"""
return {
'AlarmName': f'Bedrock{metric}Alarm',
'MetricName': metric,
'Namespace': 'AWS/Bedrock',
'Statistic': 'Sum',
'Period': 300,
'EvaluationPeriods': 1,
'Threshold': config.get('threshold', 100),
'ComparisonOperator': 'GreaterThanThreshold',
'AlarmActions': [config.get('sns_topic')],
'TreatMissingData': 'notBreaching'
}
### 常见问题解决
bash
python
class BedrockTroubleshooter:
"""Bedrock 故障排除器"""
def diagnose(self, error: str) -> DiagnosisResult:
"""诊断问题"""
if 'AccessDenied' in error:
return self._diagnose_access_denied()
elif 'ResourceNotFound' in error:
return self._diagnose_resource_not_found()
elif 'ThrottlingException' in error:
return self._diagnose_throttling()
elif 'ValidationException' in error:
return self._diagnose_validation_error()
else:
return DiagnosisResult(
issue='Unknown',
solution='Check AWS CloudWatch logs for details'
)
def _diagnose_access_denied(self) -> DiagnosisResult:
"""诊断访问拒绝错误"""
return DiagnosisResult(
issue='IAM Permission Denied',
solution='''1. Verify IAM user/role has bedrock:InvokeModel permission
2. Check if the model is accessible in the region
3. Verify the resource ARN in the IAM policy''',
commands=[
'aws iam get-role-policy --role-name <role-name> --policy-name <policy-name>',
'aws bedrock list-inference-profiles --region us-east-1'
]
)
def _diagnose_throttling(self) -> DiagnosisResult:
"""诊断限流错误"""
return DiagnosisResult(
issue='Rate Limit Exceeded',
solution='''1. Implement request queuing
2. Use inference profiles for higher throughput
3. Contact AWS support to increase quota''',
commands=[
'aws service-quotas list-service-quotas --service-code bedrock'
]
)通过正确配置 Amazon Bedrock,企业可以利用 AWS 的强大基础设施,安全、高效地部署 Claude Code。