Skip to main content
Ameerpet, Hyderabad · Classroom & live online
Cloud Soft Solutions

Amazon Bedrock Guardrails Tutorial: Content Filters, PII, Grounding and ApplyGuardrail with boto3

Hands-on Amazon Bedrock Guardrails tutorial: content filters, prompt attacks, denied topics, word and PII filters, contextual grounding and Automated Reasoning checks, with boto3 code for create, version, Converse, InvokeModel and ApplyGuardrail.

Amazon Bedrock Guardrails tutorial showing content filters, denied topics, PII masking and contextual grounding checks
Last updated · 15 min read · 3,285 words

Amazon Bedrock Guardrails tutorial showing content filters, denied topics, PII masking and contextual grounding checks

Amazon Bedrock Guardrails is the managed safety layer that sits between your users, your prompts and a foundation model. You define the policies once, version them, and then attach the guardrail to model calls or run it on its own against any text. This tutorial walks through every policy type, shows working boto3 code for creating, versioning and applying a guardrail, and covers the testing habits that keep a guardrail from blocking good answers. Every parameter name below comes from the Amazon Bedrock API reference as checked on 5 December 2026.

If you want the vendor-neutral theory first (input checks, output checks and action checks), read our explainer on AI guardrails for LLM applications. This post is the hands-on AWS version.

What a guardrail contains

A guardrail is a named resource with a blocked-input message, a blocked-output message (each 1 to 500 characters) and at least one policy. The documentation lists these policy types:

PolicyWhat it doesAPI field
Content filtersDetects Hate, Insults, Sexual, Violence and Misconduct in text or images, with a strength per categorycontentPolicyConfig
Prompt attacksA content-filter category (PROMPT_ATTACK) for jailbreaks and prompt injection; prompt leakage detection is Standard tier onlycontentPolicyConfig
Denied topicsBlocks subjects you define in natural languagetopicPolicyConfig
Word filtersExact-match custom words and phrases, plus a managed profanity listwordPolicyConfig
Sensitive information filtersBlocks or masks built-in PII types and custom regex patternssensitiveInformationPolicyConfig
Contextual grounding checksScores a response for grounding in a source and relevance to the querycontextualGroundingPolicyConfig
Automated Reasoning checksValidates responses against formal rules extracted from your policy documentsautomatedReasoningPolicyConfig

Classic and Standard safeguard tiers

Content filters, prompt attacks, denied topics and contextual grounding support two safeguard tiers. Classic supports English, French and Spanish. Standard adds wider language support, prompt leakage detection, better handling of harmful content inside code (comments, variable names, string literals), and longer denied-topic definitions (1,000 characters instead of 200). Standard tier requires cross-Region inference for the guardrail, which you switch on by passing a system-defined guardrail profile in crossRegionConfig. AWS states there is no additional cost for guardrail cross-Region inference, and that requests stay within the geography where the data originates, although prompts and outputs may be processed outside your primary Region.

Region detail matters for teams in India. Safeguard tiers are listed as supported in Asia Pacific (Mumbai). Standard tier for contextual grounding is a smaller list, and Mumbai is not on it as of this check; a request that asks for Standard grounding in an unlisted Region fails with a validation error. If you omit tierConfig, the guardrail uses Classic.

Policy-by-policy configuration notes

Content filters

Each filter takes a type (SEXUAL, VIOLENCE, HATE, INSULTS, MISCONDUCT or PROMPT_ATTACK), an inputStrength and an outputStrength (NONE, LOW, MEDIUM, HIGH). Higher strength means more content gets filtered. Optional fields let you set inputAction and outputAction to BLOCK or NONE (detect only, reported in the trace), switch evaluation off per direction with inputEnabled/outputEnabled (disabled evaluations are not charged), and choose modalities (TEXT, IMAGE).

Prompt attacks need input tags with InvokeModel

A system prompt and a malicious user prompt can look alike, so the prompt attack filter needs to know which text came from the user. With InvokeModel and InvokeModelWithResponseStream, the docs say you must wrap user input in guardrail input tags; without tags, prompt attacks are not filtered for those calls. With the Converse API, you mark user content with guardContent blocks instead. The prompt attack filter does not evaluate tool results or tool definitions.

Denied topics

You can add up to 30 denied topics. Each has a name, a definition (200 characters on Classic, 1,000 on Standard), up to five examples of up to 100 characters each, and type set to DENY. AWS's guidance is specific: describe the topic, don't write instructions ("Block all crypto content" is wrong), don't write negative definitions ("everything except medical information"), and don't use topics to catch individual words or names. Use word filters or sensitive information filters for that. The docs also warn that topic order can change the outcome for borderline prompts, so test after reordering.

Word filters

The managed list type is PROFANITY. Custom words go in wordsConfig, each entry a word or phrase of up to three words, with up to 10,000 items. Matching is case-insensitive and whole-word: competitor does not match competitors. File and S3 uploads of word lists work in the console only; the API accepts text entries.

Sensitive information (PII) filters

Built-in entity types include NAME, EMAIL, PHONE, ADDRESS, PASSWORD, CREDIT_DEBIT_CARD_NUMBER, IP_ADDRESS, AWS_ACCESS_KEY, AWS_SECRET_KEY and country-specific types for the US, Canada and the UK. Each can use BLOCK, ANONYMIZE (mask with a placeholder such as {EMAIL}) or NONE. There is no built-in type for Indian identifiers such as Aadhaar or PAN in the list we checked, so Indian teams normally add custom regex entries (name 1 to 100 characters, pattern 1 to 500 characters). Regex lookarounds are not supported.

Two documented gotchas trip up most teams. First, masking applies only to the prompt sent to the model and the response returned; the input field in model invocation logs keeps the original text, and the guardrail trace's match field contains the unmasked value. Second, in tool-use workloads the filter does not evaluate tool call arguments, tool results or tool definitions.

Contextual grounding checks

Grounding checks whether the response is supported by a reference source; relevance checks whether it answers the user's query. You set a threshold between 0 and 0.99 for GROUNDING and RELEVANCE; responses scoring below it are blocked (or only flagged if the action is NONE). Limits are 100,000 characters for the grounding source, 1,000 for the query and 5,000 for the response. The check runs on output only, because it needs a model response. Classic tier applies strict grounding, so reasonable paraphrases can score low; Standard tier handles conversational and reasoning responses and AWS suggests 0.7 as a starting point for those cases on Standard.

Automated Reasoning checks (generally available, limited Regions)

Automated Reasoning checks are documented as generally available in US East (N. Virginia), US West (Oregon), US East (Ohio), EU (Frankfurt), EU (Paris), EU (Ireland) and Asia Pacific (Sydney). Mumbai is not on the list. You upload a source document (up to 5 MB and 50,000 characters), Bedrock extracts formal rules and variables, you test and version the policy, then attach it to a guardrail through automatedReasoningPolicyConfig. Important limits: English (US) only, no streaming support, no prompt-injection protection, and it runs in detect mode only, returning findings such as VALID, INVALID or TRANSLATION_AMBIGUOUS rather than blocking. Your application decides whether to serve, rewrite or ask for clarification.

Step 1: Create the guardrail with boto3

Guardrail management uses the bedrock control-plane client. The example below targets Mumbai, so it uses Standard tier for content and topics and leaves grounding on Classic.

import boto3

REGION = "ap-south-1"
bedrock = boto3.client("bedrock", region_name=REGION)

resp = bedrock.create_guardrail(
    name="support-assistant-guardrail",
    description="Customer support bot: safety, PII masking, grounding",
    blockedInputMessaging="Sorry, I can't help with that request.",
    blockedOutputsMessaging="Sorry, I can't share that answer.",
    contentPolicyConfig={
        "filtersConfig": [
            {"type": "HATE", "inputStrength": "HIGH", "outputStrength": "HIGH"},
            {"type": "INSULTS", "inputStrength": "HIGH", "outputStrength": "HIGH"},
            {"type": "SEXUAL", "inputStrength": "HIGH", "outputStrength": "HIGH"},
            {"type": "VIOLENCE", "inputStrength": "MEDIUM", "outputStrength": "HIGH"},
            {"type": "MISCONDUCT", "inputStrength": "MEDIUM", "outputStrength": "HIGH"},
            # The docs configure PROMPT_ATTACK on input; outputStrength is a
            # required field, so it is set to NONE here.
            {"type": "PROMPT_ATTACK", "inputStrength": "HIGH", "outputStrength": "NONE"},
        ],
        "tierConfig": {"tierName": "STANDARD"},
    },
    topicPolicyConfig={
        "topicsConfig": [
            {
                "name": "Investment Advice",
                "definition": "Guidance or recommendations about allocating money "
                              "or assets to earn returns.",
                "examples": ["Should I buy gold or mutual funds?",
                             "Which stock will double this year?"],
                "type": "DENY",
            }
        ],
        "tierConfig": {"tierName": "STANDARD"},
    },
    wordPolicyConfig={
        "wordsConfig": [{"text": "ExampleCompetitor"}],
        "managedWordListsConfig": [{"type": "PROFANITY"}],
    },
    sensitiveInformationPolicyConfig={
        "piiEntitiesConfig": [
            {"type": "EMAIL", "action": "ANONYMIZE"},
            {"type": "PHONE", "action": "ANONYMIZE"},
            {"type": "CREDIT_DEBIT_CARD_NUMBER", "action": "BLOCK"},
        ],
        "regexesConfig": [
            {
                # Illustrative 12-digit pattern; tune and test on your own data.
                "name": "twelve-digit-id",
                "pattern": r"\b\d{4}\s?\d{4}\s?\d{4}\b",
                "action": "ANONYMIZE",
                "description": "Masks 12-digit identifiers",
            }
        ],
    },
    contextualGroundingPolicyConfig={
        # No tierConfig: Classic tier, because Standard grounding is not
        # listed for ap-south-1 at the time of writing.
        "filtersConfig": [
            {"type": "GROUNDING", "threshold": 0.75},
            {"type": "RELEVANCE", "threshold": 0.5},
        ]
    },
    # Required for STANDARD tier. Use the guardrail profile ID that the docs
    # list for your source Region (the docs show us.guardrail.v1:0 for US).
    crossRegionConfig={"guardrailProfileIdentifier": "<guardrail-profile-id>"},
)

guardrail_id = resp["guardrailId"]
print(guardrail_id, resp["version"])   # version is always DRAFT on create

You can pass kmsKeyId to encrypt the guardrail with your own KMS key; otherwise an AWS managed key is used. One more trap from the docs: UpdateGuardrail replaces the whole policy configuration, so if you omit tierConfig in an update, that policy silently falls back to Classic.

Step 2: Version it

CreateGuardrail always returns DRAFT. The draft changes every time someone edits it, which is useful for testing and risky for production. Create a numbered version and pin your application to it:

v = bedrock.create_guardrail_version(
    guardrailIdentifier=guardrail_id,
    description="Approved after red-team round 1",
)
GUARDRAIL_VERSION = v["version"]   # for example "1"

Runtime APIs accept either a number or DRAFT for guardrailVersion. Promote new versions through the same review you use for code.

Step 3: Apply it with the Converse API

Pass a guardrailConfig object. Wrap the user's latest turn in a guardContent block so the guardrail evaluates that text and not your instructions. Once any guardContent block is present, the guardrail evaluates only content inside such blocks. System prompts are not evaluated unless you also wrap them in guardContent.

runtime = boto3.client("bedrock-runtime", region_name=REGION)

MODEL_ID = "<model ID or inference profile ID that supports guardrails>"

messages = [{
    "role": "user",
    "content": [
        {"text": "Answer as the support assistant for ExampleBank."},
        {"guardContent": {"text": {"text": user_input}}},
    ],
}]

response = runtime.converse(
    modelId=MODEL_ID,
    messages=messages,
    guardrailConfig={
        "guardrailIdentifier": guardrail_id,
        "guardrailVersion": GUARDRAIL_VERSION,
        "trace": "enabled",
    },
)

if response["stopReason"] == "guardrail_intervened":
    trace = response["trace"]["guardrail"]
    # Masking also reports guardrail_intervened. Inspect the trace:
    # sensitiveInformationPolicy entries show ANONYMIZED vs BLOCKED.
    # The trace contains unmasked values, so do not log it casually.
print(response["output"]["message"]["content"][0]["text"])

For ConverseStream, the guardrail config also accepts streamProcessingMode (sync or async). Synchronous mode assesses chunks before releasing them; asynchronous mode streams while the guardrail assesses in the background, which is faster but can briefly show content that is later flagged.

To run grounding checks in Converse, tag the retrieved passages and the question with qualifiers: grounding_source and query. Content with only those qualifiers is excluded from the other policies; add guard_content alongside if you also want it filtered.

messages = [{
    "role": "user",
    "content": [
        {"guardContent": {"text": {"text": retrieved_passages,
                                   "qualifiers": ["grounding_source"]}}},
        {"guardContent": {"text": {"text": user_question,
                                   "qualifiers": ["query"]}}},
    ],
}]

Step 4: Apply it with InvokeModel

With InvokeModel, the guardrail ID and version travel as request parameters (HTTP headers X-Amzn-Bedrock-GuardrailIdentifier and X-Amzn-Bedrock-GuardrailVersion), and trace accepts ENABLED, DISABLED or ENABLED_FULL. The body must be JSON. Mark user input with tags that use a suffix you declare in amazon-bedrock-guardrailConfig:

import json

# Anthropic Messages body format, as in the InvokeModel API reference
# example. Other providers use different body fields.
tagged = (
    "You are the ExampleBank assistant. Answer the question: "
    "<amazon-bedrock-guardrails-guardContent_xyz>"
    + user_input +
    "</amazon-bedrock-guardrails-guardContent_xyz>"
)
body = {
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 512,
    "messages": [{"role": "user",
                  "content": [{"type": "text", "text": tagged}]}],
    # Placement of this key inside an Anthropic Messages body is not shown
    # in the docs we checked; the API reference shows it at the body root.
    "amazon-bedrock-guardrailConfig": {"tagSuffix": "xyz"},
}

resp = runtime.invoke_model(
    modelId=MODEL_ID,
    body=json.dumps(body),
    contentType="application/json",
    accept="application/json",
    guardrailIdentifier=guardrail_id,
    guardrailVersion=GUARDRAIL_VERSION,
    trace="ENABLED",
)
result = json.loads(resp["body"].read())
# Per the API reference example, the body carries
# "amazon-bedrock-guardrailAction": "INTERVENED" or "NONE".
print(result.get("amazon-bedrock-guardrailAction"))

Use a random tag suffix per request in production so a user cannot close your tag and smuggle text outside it. Note that if you pass amazon-bedrock-guardrailConfig without a guardrail identifier, the call fails, and a guardrail identifier without a version also fails.

Step 5: Use ApplyGuardrail without calling a model

ApplyGuardrail evaluates any text you send it. Use it for third-party or self-hosted models, for checking retrieved documents before they reach a prompt, for scanning agent tool outputs (which Converse guardrails do not evaluate), or for moderating user content in a non-LLM workflow. The request takes guardrailIdentifier, guardrailVersion, source (INPUT or OUTPUT), content and optional outputScope (INTERVENTIONS or FULL).

check = runtime.apply_guardrail(
    guardrailIdentifier=guardrail_id,
    guardrailVersion=GUARDRAIL_VERSION,
    source="INPUT",
    content=[{"text": {"text": user_input}}],
    outputScope="FULL",   # include non-detected entries while debugging
)

if check["action"] == "GUARDRAIL_INTERVENED":
    print(check["actionReason"])
    safe_text = check["outputs"][0]["text"] if check["outputs"] else None
else:
    safe_text = user_input

for a in check["assessments"]:
    print(a.get("topicPolicy"), a.get("contentPolicy"),
          a.get("sensitiveInformationPolicy"))
print(check["usage"])   # policy units consumed by this call

For a grounding check on an answer you already have, send three blocks with source="OUTPUT": the source qualified as grounding_source, the question qualified as query, and the answer with no qualifier (or guard_content). The response's contextualGroundingPolicy filters report score, threshold and action.

Step 6: Test before you block

A guardrail that blocks too much is as harmful to adoption as one that blocks too little. A practical rollout looks like this:

  1. Detect mode first. Set inputAction/outputAction to NONE on new filters. Traffic flows normally and the trace records what would have been blocked.
  2. Build a labelled test set. Collect real user questions, known attack prompts, PII-heavy samples and borderline-but-legitimate questions. Run them through ApplyGuardrail against DRAFT with outputScope="FULL".
  3. Measure both error types. Count harmful prompts that passed and legitimate prompts that were blocked. Adjust strengths, rewrite topic definitions, add sample phrases.
  4. Tune grounding thresholds on your own data. AWS notes that Classic and Standard tiers score differently, so retest thresholds after a tier change.
  5. Version and pin. Create a numbered version only after the test set passes, then switch actions to BLOCK.
  6. Monitor. Track the rate of guardrail_intervened stops and read samples weekly.

Enforcing guardrails for every caller

The IAM condition key bedrock:GuardrailIdentifier lets you deny InvokeModel and InvokeModelWithResponseStream unless a specific guardrail (and optionally version) is included. The value format is the guardrail ARN, with :1 appended for a numbered version. Read the documented limits before relying on it: roles that also call RetrieveAndGenerate or agent APIs can hit access-denied errors because those services make internal model calls without a guardrail, input tags can be used to skip guardrail evaluation of the prompt (the response is always evaluated), and the guardrail and role must be in the same AWS organization. For CloudTrail, ApplyGuardrail activity, including evaluations made during model invocation, is a data event on the AWS::Bedrock::Guardrail resource type that you must opt into.

Limits and caveats worth knowing

  • Guardrails work with InvokeModel, InvokeModelWithResponseStream, Converse and ConverseStream on the bedrock-runtime endpoint. The bedrock-mantle endpoint does not support them.
  • Some models reject guardrails with ValidationException: Guardrail is not supported with the chosen model, including the Titan and Cohere embedding models and the rerank models. Check the model card, or use ApplyGuardrail.
  • Blocked content still appears as plain text in model invocation logs if logging is enabled. Use CloudWatch Logs data protection or restrict log access.
  • In tool-use flows, toolResult content, tool definitions and model-generated tool arguments are not evaluated by a guardrail passed in guardrailConfig.

Guardrails come up in Bedrock interviews often. Our Bedrock interview questions and answers post covers the conceptual side, and the Knowledge Bases RAG tutorial shows how to attach this guardrail to RetrieveAndGenerate. For network and IAM controls around the same workload, see the Bedrock security and private networking guide.

Practise this at Cloud Soft Solutions

You can build, version and red-team a guardrail like this one in the hands-on labs of our AI, GenAI and Agentic AI course, alongside the core AWS skills in our AWS training in Hyderabad. Classes run in the classroom in Ameerpet or online, and you work in your own AWS account so the setup carries over to real projects. More preparation material is in our AWS interview questions hub.

Sources

📞 Call +91 96660 19191 · +91 99496 16388 · WhatsApp
Cloud Soft Solutions, 513, 5th Floor, Aditya Enclave, Nilagiri Block, beside Ameerpet Metro Station, Ameerpet, Hyderabad 500016, Telangana, India

Frequently Asked Questions

Which policies can an Amazon Bedrock guardrail include?
Content filters (including a prompt attack category), denied topics, word filters, sensitive information (PII and regex) filters, contextual grounding checks and Automated Reasoning checks. A guardrail needs at least one policy plus blocked-input and blocked-output messages.

Are Automated Reasoning checks generally available?
Yes. AWS documents them as generally available in US East (N. Virginia), US West (Oregon), US East (Ohio), EU (Frankfurt), EU (Paris), EU (Ireland) and Asia Pacific (Sydney). They support English (US) only, do not support streaming, and run in detect mode rather than blocking.

What is the difference between Classic and Standard guardrail tiers?
Classic supports English, French and Spanish. Standard adds wider language support, prompt leakage detection, better handling of code, and 1,000-character denied-topic definitions instead of 200. Standard requires cross-Region inference through a guardrail profile.

When should I use the ApplyGuardrail API?
Use ApplyGuardrail to evaluate text without invoking a Bedrock model, for example with self-hosted or third-party models, to check retrieved documents or tool outputs, or to test a guardrail against a labelled dataset.

Does PII masking also mask model invocation logs?
No. Masking applies to the prompt sent to the model and the response returned. The input field in model invocation logs keeps the original text, and the guardrail trace's match field contains the detected value.

Why should production code use a numbered guardrail version?
CreateGuardrail always produces a DRAFT that changes whenever someone edits it. Creating a numbered version with CreateGuardrailVersion and referencing that number keeps production behaviour stable while you test changes on the draft.

Share𝕏inf✉
EnrollWhatsAppCall us