You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bedrock服务在输入发送至LLM前应用Guardrail并处理PII?

解决方案

输入阶段PII掩码+输出阶段Guardrail检查实现

1. 核心思路

在调用Bedrock模型前,先用AWS Comprehend检测并掩码输入中的PII信息;之后再调用带Guardrail参数的模型接口,同时完成输出内容的合规检查。

2. 完整代码实现

import boto3

# 初始化AWS客户端
bedrock_runtime = boto3.client(
    service_name="bedrock-runtime",
    region_name='us-east-1'
)
comprehend = boto3.client(
    service_name='comprehend',
    region_name='us-east-1'
)

def mask_pii(input_text, language_code='en'):
    # 调用Comprehend检测PII实体
    pii_response = comprehend.detect_pii_entities(
        Text=input_text,
        LanguageCode=language_code
    )
    
    # 从后往前替换实体,避免位置偏移问题
    masked_text = input_text
    for entity in sorted(pii_response['Entities'], key=lambda x: x['BeginOffset'], reverse=True):
        start = entity['BeginOffset']
        end = entity['EndOffset']
        masked_text = masked_text[:start] + '*'*(end - start) + masked_text[end:]
    
    return masked_text

# 1. 先处理输入,掩码PII
cleaned_prompt = mask_pii(input_context_prompt, language_code='zh')  # 根据输入语言调整

# 2. 调用Bedrock模型,同时启用输出Guardrail
model_response = bedrock_runtime.invoke_model(
    modelId=modelId,
    guardrailIdentifier=guardrailIdentifier,
    guardrailVersion=guardrailVersion,
    body=cleaned_prompt
)

关键细节

  • PII掩码逻辑:通过Comprehend识别手机号、邮箱、身份证号等数十种PII实体,用等长*替换,保证输入上下文结构不变的同时隐藏敏感信息
  • 多语言支持:修改language_code参数为zh可适配中文输入,Comprehend支持主流语言的PII检测
  • 输出Guardrail保留:原代码中的guardrailIdentifier和guardrailVersion参数完全保留,继续对LLM生成的内容进行合规校验

内容的提问来源于stack exchange,提问作者Kotesh Nataru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:26:07