mcpField
A
aws-cloudformation-bedrock

aws-cloudformation-bedrock

github.com/giuseppe-trisciuoglio云与 DevOps36566 次安装7 周前更新
代码仓库

关于 aws-cloudformation-bedrock

面向使用 CloudFormation 构建 Amazon Bedrock AI 基础设施的开发者,提供 Agent、RAG 知识库、数据源、护栏和工作流等资源的模板指引。内容也包括部署验证与运行状态检查。

主要功能

  1. 01定义 Bedrock Agent 和操作组
  2. 02构建 RAG 知识库与数据源
  3. 03配置内容审核护栏
  4. 04管理提示词和 Flows 工作流
  5. 05配置推理配置文件及模板参数

适用场景

  1. 01部署连接知识库的 Bedrock Agent
  2. 02为数据源设置内容安全护栏
  3. 03编排 Bedrock AI 工作流

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-cloudformation-bedrock

安装后在 Claude Code 中输入/aws-cloudformation-bedrock确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
constraints.md
examples.md
reference.md

详细介绍

AWS CloudFormation Amazon Bedrock

概述

使用适用于 Amazon Bedrock 的 AWS CloudFormation 模板创建可用于生产环境的 AI 基础设施。涵盖 Bedrock Agent、用于 RAG 实现的知识库、数据源连接器、用于内容审核的护栏、提示词管理、使用流程进行工作流编排,以及用于优化模型访问的推理配置文件。

适用场景

  • 创建带有操作组的 Bedrock Agent
  • 使用知识库实现 RAG
  • 配置 S3 或 Web 爬取数据源
  • 设置内容审核护栏
  • 管理提示词模板
  • 使用 Bedrock Flows 编排 AI 工作流
  • 配置用于访问多个模型的推理配置文件
  • 使用 Parameters 和跨堆栈引用组织模板

说明

1. 定义参数
Parameters:
  FoundationModel:
    Type: String
    Default: anthropic.claude-3-sonnet-20240229-v1:0
    AllowedValues:
      - anthropic.claude-3-sonnet-20240229-v1:0
      - anthropic.claude-3-haiku-20240307-v1:0
      - amazon.titan-text-express-v1
    Description: Foundation model for agent
2. 创建 Agent 角色
Resources:
  AgentRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: bedrock.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: BedrockPermissions
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - bedrock:InvokeModel
                Resource: !Sub "arn:aws:bedrock:${AWS::Region}:${AWS::AccountId}:foundation-model/${FoundationModel}"
3. 创建 Agent
  BedrockAgent:
    Type: AWS::Bedrock::Agent
    Properties:
      AgentName: !Sub "${AWS::StackName}-agent"
      AgentResourceRoleArn: !GetAtt AgentRole.Arn
      FoundationModelArn: !Sub "arn:aws:bedrock:${AWS::Region}::foundation-model/${FoundationModel}"
      AutoPrepare: true
      Instruction: |
        You are a helpful assistant. Use the knowledge base to answer questions.
4. 创建知识库
  KnowledgeBaseRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: bedrock.amazonaws.com
            Action: sts:AssumeRole

  KnowledgeBase:
    Type: AWS::Bedrock::KnowledgeBase
    Properties:
      Name: !Sub "${AWS::StackName}-kb"
      RoleArn: !GetAtt KnowledgeBaseRole.Arn
      KnowledgeBaseConfiguration:
        Type: VECTOR
        VectorKnowledgeBaseConfiguration:
          EmbeddingModelArn: !Sub "arn:aws:bedrock:${AWS::Region}::embedding-model/amazon.titan-embed-text-v1"
5. 创建数据源
  DataBucket:
    Type: AWS::S3::Bucket

  S3DataSource:
    Type: AWS::Bedrock::DataSource
    Properties:
      KnowledgeBaseId: !Ref KnowledgeBase
      Name: s3-data-source
      Type: S3
      DataSourceConfiguration:
        S3Configuration:
          BucketArn: !GetAtt DataBucket.Arn
          InclusionPrefixes:
            - documents/
6. 添加护栏
  Guardrail:
    Type: AWS::Bedrock::Guardrail
    Properties:
      Name: !Sub "${AWS::StackName}-guardrail"
      BlockedInputMessaging: "I cannot help with that request."
      ContentPolicyConfig:
        filtersConfig:
          - type: PROFANITY
          - type: MISCONDUCT
7. 创建操作组
  ActionLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.12
      Handler: index.handler
      Role: !GetAtt ActionLambdaRole.Arn
      Code:
        ZipFile: |
          def handler(event, context):
              return {"statusCode": 200, "body": "{\"result\": \"success\"}"}

  ActionGroup:
    Type: AWS::Bedrock::AgentActionGroup
    Properties:
      ActionGroupName: api-operations
      ActionGroupState: ENABLED
      AgentId: !GetAtt BedrockAgent.AgentId
      ActionGroupExecutor:
        Lambda: !Ref ActionLambdaFunction
      FunctionSchema:
        functionConfigurations:
          - function: |
              { "name": "get_inventory", "description": "Get current inventory status", "parameters": { "type": "object", "properties": { "sku": { "type": "string" } }, "required": [] } }
8. 部署前验证

部署前务必验证模板:

aws cloudformation validate-template --template-body file://bedrock-template.yaml
9. 部署后验证
# Check agent status
aws bedrock-agent get-agent --agent-id $(aws cloudformation describe-stacks --stack-name STACK_NAME --query 'Stacks[0].Outputs[?OutputKey==`AgentId`].OutputValue' --output text)

# Check knowledge base sync status
aws bedrock-agent list-knowledge-bases --agent-id AGENT_ID

# Test guardrail
aws bedrock-runtime apply_guardrail --guardrail-identifier GUARDRAIL_ID --source SOURCE

示例

最简 RAG Agent 模板

用于支持 RAG 的 Agent 的完整可运行模板:

AWSTemplateFormatVersion: "2010-09-09"
Description: "Bedrock RAG Agent with Knowledge Base"

Parameters:
  FoundationModel:
    Type: String
    Default: anthropic.claude-3-sonnet-20240229-v1:0

Resources:
  # IAM Role for Agent
  AgentRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${AWS::StackName}-agent-role"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: bedrock.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: InvokeModel
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: bedrock:InvokeModel
                Resource: "*"

  # IAM Role for Knowledge Base
  KnowledgeBaseRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${AWS::StackName}-kb-role"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: bedrock.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: S3Access
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: s3:GetObject
                Resource: !Sub "${DataBucket.Arn}/*"

  # S3 Bucket for Documents
  DataBucket:
    Type: AWS::S3::Bucket

  # Knowledge Base
  KnowledgeBase:
    Type: AWS::Bedrock::KnowledgeBase
    Properties:
      Name: !Sub "${AWS::StackName}-kb"
      RoleArn: !GetAtt KnowledgeBaseRole.Arn
      KnowledgeBaseConfiguration:
        Type: VECTOR
        VectorKnowledgeBaseConfiguration:
          EmbeddingModelArn: !Sub "arn:aws:bedrock:${AWS::Region}::embedding-model/amazon.titan-embed-text-v1"

  # Data Source
  DataSource:
    Type: AWS::Bedrock::DataSource
    Properties:
      KnowledgeBaseId: !Ref KnowledgeBase
      Name: !Sub "${AWS::StackName}-ds"
      Type: S3
      DataSourceConfiguration:
        S3Configuration:
          BucketArn: !GetAtt DataBucket.Arn

  # Bedrock Agent
  BedrockAgent:
    Type: AWS::Bedrock::Agent
    Properties:
      AgentName: !Sub "${AWS::StackName}-agent"
      AgentResourceRoleArn: !GetAtt AgentRole.Arn
      FoundationModelArn: !Sub "arn:aws:bedrock:${AWS::Region}::foundation-model/${FoundationModel}"
      AutoPrepare: true
      Instruction: |
        You are a helpful assistant. Use the knowledge base to answer user questions accurately.

Outputs:
  AgentId:
    Description: Bedrock Agent ID
    Value: !GetAtt BedrockAgent.AgentId
  KnowledgeBaseId:
    Description: Knowledge Base ID
    Value: !Ref KnowledgeBase
带内容过滤的护栏
Resources:
  Guardrail:
    Type: AWS::Bedrock::Guardrail
    Properties:
      Name: !Sub "${AWS::StackName}-guardrail"
      blockedInputMessaging: "Content blocked by safety filters."
      blockedOutputMessaging: "Response filtered for safety."
      contentPolicyConfig:
        filtersConfig:
          - type: PROFANITY
            inputStrength: HIGH
            outputStrength: HIGH
          - type: MISCONDUCT
            inputStrength: HIGH
            outputStrength: HIGH
      sensitiveInformationPolicyConfig:
        piiEntitiesConfig:
          - type: EMAIL
            action: ANONYMIZE
          - type: SSN
            action: BLOCK

最佳实践

安全性
  • 为 Agent 和知识库角色使用最小权限 IAM 策略
  • 将 Web 爬取数据源限制为受信任的内部域名
  • 加密知识库中的敏感数据
  • 将所有 TemplateURL 值参数化,用于嵌套堆栈
成本优化
  • 根据任务复杂度选择合适的模型大小
  • 配置检索过滤以减少令牌用量
  • 设置分块大小限制以控制存储成本
  • 使用 CloudWatch 控制面板监控用量
性能
  • 优化分块大小以提升嵌入质量
  • 为高流量向量存储使用预置吞吐量
  • 配置适当的知识库同步间隔
  • 为频繁访问的内容实现缓存
验证
  • 部署前务必运行 aws cloudformation validate-template
  • 堆栈创建完成后验证 Agent 状态
  • 使用示例输入测试护栏
  • 在 CloudWatch 中监控知识库同步状态

限制和警告

有关详细限制,请参阅 constraints.md:

  • 区域限制:并非所有模型都在所有区域提供
  • Agent 初始化:AutoPrepare 可能需要几分钟
  • 知识库同步:S3 同步近乎即时;Web 爬取需要更长时间
  • Web 爬取安全性:务必限制为受信任的域名,以防止提示词注入
  • 令牌限制:根据使用场景配置 MaxTokens 参数
  • 配额管理:如有需要,通过 AWS Support 申请提高配额
安全性
  • 仅将 Web 爬取数据源限制为受信任的内部域名
  • 将内容导入知识库前先进行验证
  • 对嵌套堆栈使用参数化的 TemplateURL 值
  • 实施内容审核护栏
  • 为 Agent 角色应用最小权限 IAM 策略
  • 加密知识库中的敏感数据
  • 监控通过 Web 爬取内容中的提示词注入
成本优化
  • 根据任务复杂度选择合适的模型
  • 实施知识库检索过滤
  • 设置分块大小限制以控制令牌用量
  • 使用 CloudWatch 监控令牌消耗
  • 有策略地使用自动准备的 Agent
  • 为非实时工作负载实施批处理
  • 使用知识库过滤以降低成本
性能
  • 优化分块大小,在嵌入质量和成本之间取得平衡
  • 优化向量存储(OpenSearch、Pinecone)
  • 为频繁访问的知识库内容实现缓存
  • 配置适当的知识库同步间隔
  • 为向量数据库使用预置吞吐量
  • 监控 Agent 初始化和冷启动时间
  • 实施限流时的平稳降级
数据管理
  • 为数据源使用合适的包含/排除筛选条件
  • 在索引之前验证文档
  • 对知识库更新进行版本控制
  • 为数据源配置合适的同步间隔
  • 在知识库中实现内容去重
  • 使用元数据筛选来提高检索准确性
  • 监控知识库大小和文档数量限制

参考资料

相关资源

评论

支持 Markdown