Amazon Bedrock
6.9.5kata 5 de 5

Guardrails

Filtrar contenido inapropiado y redactar datos sensibles

Guardrails es el sistema de safety y conformidad de Bedrock: configuras políticas (rechaza malware, no generes contenido sexual, anonimiza PII) y Bedrock las aplica automáticamente en inputs y outputs. Guardrails intercepta requests ANTES de llegar al LLM y respuestas DESPUÉS de ser generadas. Es esencial para producción donde necesitas cumplimiento legal (GDPR, CCPA) o control de contenido.

Dos modos de acción: (1) BLOCK — rechaza la request/response completamente ('I cannot help with this'). (2) REDACT — reemplaza contenido sensible ('Phone: [REDACTED]'). Defines cuál usar por tipo de restricción. Ej. PHONE → ANONYMIZE (reemplaza con token), EMAIL → BLOCK (rechaza).

Configuras Guardrails en nivel de modelo: pasa `guardrailIdentifier` y `guardrailVersion` a `invoke_model()`. Los Guardrails aplican en paralelo — si ANY política falla, respuesta es rechazada. Monitorea qué está siendo blocked — puede significar reglas demasiado estrictas.

Costo: $0.0006 por invocación con Guardrails (pequeño overhead). Implementar Guardrails es obligatorio para: (1) aplicaciones públicas (contenido verificado), (2) datos sensibles (GDPR compliance), (3) outputs financieros/legales (auditoría). Sin Guardrails, LLMs pueden alucinar datos sensibles o contenido dañino.

structure.txt
import boto3
bedrock_mgmt = boto3.client('bedrock', region_name='us-west-2')
bedrock_runtime = boto3.client('bedrock-runtime', region_name='us-west-2')

# 1. Create Guardrail
guardrail = bedrock_mgmt.create_guardrail(
    name='gdpr-compliance',
    description='GDPR redaction and malware filtering',
    sensitiveInformationPolicyConfig={
        'piiEntitiesConfig': [
            {'type': 'PHONE', 'action': 'ANONYMIZE'},
            {'type': 'EMAIL', 'action': 'ANONYMIZE'},
            {'type': 'NAME', 'action': 'REDACT'},
            {'type': 'ADDRESS', 'action': 'ANONYMIZE'},
            {'type': 'CREDIT_DEBIT_CARD_NUMBER', 'action': 'BLOCK'}
        ]
    },
    contentPolicyConfig={
        'filtersConfig': [
            {'type': 'SEXUAL', 'inputStrength': 'HIGH', 'outputStrength': 'HIGH'},
            {'type': 'VIOLENCE', 'inputStrength': 'HIGH', 'outputStrength': 'HIGH'},
            {'type': 'HATE_SPEECH', 'inputStrength': 'HIGH', 'outputStrength': 'HIGH'}
        ]
    },
    blockedInputMessaging='This request cannot be processed due to content policies.',
    blockedOutputMessaging='I cannot provide this information.'
)
guardrail_id = guardrail['guardrailId']

# 2. Use Guardrail with invoke_model
response = bedrock_runtime.invoke_model(
    modelId='anthropic.claude-3-sonnet-20240229-v1:0',
    guardrailIdentifier=guardrail_id,
    guardrailVersion='DRAFT',
    body=json.dumps({
        'messages': [{'role': 'user', 'content': 'Customer phone: 555-1234, address: 123 Main'}]
    })
)
# Output redacts phone and address automatically

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # No Guardrails, LLM generates customer data response = bedrock.invoke_model( modelId='anthropic.claude-3-sonnet-20240229-v1:0', body=json.dumps({'messages': [{'role': 'user', 'content': 'List customer 123'}]}) ) output = json.loads(response['body'].read())['content'][0]['text'] print(output) # Shows: 'Name: John Doe, Phone: 555-1234, SSN: 123-45-6789'

  2. 02

    # Guardrail bloquea todas las requests guardrail = bedrock_mgmt.create_guardrail( name='strict-filter', contentPolicyConfig={ 'filtersConfig': [ {'type': 'SEXUAL', 'inputStrength': 'HIGH'}, {'type': 'VIOLENCE', 'inputStrength': 'HIGH'}, {'type': 'HATE_SPEECH', 'inputStrength': 'HIGH'} ] } ) # Every request returns 'Request blocked'

  3. 03

    guardrail = bedrock_mgmt.create_guardrail( name='test', sensitiveInformationPolicyConfig={ 'piiEntitiesConfig': [{'type': 'EMAIL', 'action': 'BLOCK'}] } ) response = bedrock_runtime.invoke_model( guardrailIdentifier='gr-123', guardrailVersion='LIVE', # Published version body=json.dumps({...}) ) # Guardrail rejects ALL requests with emails