Home / AI & GenAI

AI & GenAIHow-toIntermediate

Azure OpenAI custom blocklists: block specific terms, attach them to a content filter and test the result

Create a custom blocklist with az rest, add exact and regex terms, attach it to a deployment's content filter for prompts and completions, and confirm hits from the 400 error body.

Deepak Bhardwaj7 min read

Applies toAzure OpenAI in Microsoft Foundry (Cognitive Services management API 2024-10-01), az CLI 2.x

When you need a blocklist

The built-in content filters score hate, sexual, violence and self-harm content by severity. They do not know your business. Sometimes you need to block exact strings:

  • Internal project code names, customer names or ticket prefixes that must not leave the assistant.
  • Competitor product names your legal team doesn't want in generated text.
  • Patterns such as internal hostnames (*.corp.contoso.local) or employee ID formats.
  • A term from an active incident, for example a leaked phrase people are pasting into the chat.

A custom blocklist is attached to a content filter configuration (an "RAI policy"). That configuration is assigned to one or more deployments. When a prompt or a completion matches a term, the request is filtered the same way as a built-in filter hit.

Warning

A blocklist changes behaviour for every app that calls the deployment. A broad regex such as .*admin.* can block legitimate traffic across production. Test new terms on a non-production deployment first, and get sign-off from the app owners.

Before you start

Requirement Check
Role on the Azure OpenAI or Foundry resource Cognitive Services Contributor or Owner. Without it you get 403 on the management calls
A non-production deployment to test on az cognitiveservices account deployment list -g $RG -n $ACCOUNT -o table
The content filter currently assigned See the next section

Set the variables used by every command below. These are bash commands. In PowerShell, use $env: variables and backtick line continuation instead.

SUB=$(az account show --query id -o tsv)
RG=rg-genai-prod
ACCOUNT=aoai-prod-weu
DEPLOYMENT=gpt-chat-test
API=2024-10-01
BASE="https://management.azure.com/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.CognitiveServices/accounts/$ACCOUNT"

az rest gets the management token for you, so you don't need to call az account get-access-token.

Find the current content filter

az cognitiveservices account deployment show -g $RG -n $ACCOUNT \
  --deployment-name $DEPLOYMENT --query properties.raiPolicyName -o tsv

az rest --method get --url "$BASE/raiPolicies?api-version=$API" \
  --query "value[].{name:name, base:properties.basePolicyName, mode:properties.mode}" -o table

If the deployment uses Microsoft.Default or Microsoft.DefaultV2, you cannot attach a blocklist to it. Create a custom content filter configuration first. The easiest way is in the Foundry portal under Guardrails + controls → Content filters. Copy the default thresholds, give it a name such as cf-chat-prod, then use the steps below.

Step 1: Create the blocklist

Blocklist names may contain letters, digits and - . _ ~.

az rest --method put \
  --url "$BASE/raiBlocklists/bl-internal-terms?api-version=$API" \
  --body '{"properties": {"description": "Internal code names and hostnames. Owner: platform-ai team"}}'

The call returns 201 when it creates the list and 200 when it updates it. Put the owner in the description. In six months someone will need to know who to ask before removing a term.

Step 2: Add terms

Each item has a name, a pattern and an isRegex flag. Name each item after what it blocks, so the audit trail makes sense.

# Exact term
az rest --method put \
  --url "$BASE/raiBlocklists/bl-internal-terms/raiBlocklistItems/project-falcon?api-version=$API" \
  --body '{"properties": {"pattern": "Project Falcon", "isRegex": false}}'

# Regex: internal hostnames
az rest --method put \
  --url "$BASE/raiBlocklists/bl-internal-terms/raiBlocklistItems/corp-hostnames?api-version=$API" \
  --body '{"properties": {"pattern": "[A-Za-z0-9-]+\\.corp\\.contoso\\.local", "isRegex": true}}'

To load many terms from a file, loop over it:

while IFS=, read -r name pattern; do
  az rest --method put \
    --url "$BASE/raiBlocklists/bl-internal-terms/raiBlocklistItems/$name?api-version=$API" \
    --body "{\"properties\": {\"pattern\": \"$pattern\", \"isRegex\": false}}" -o none
done < terms.csv

Check what is in the list:

az rest --method get \
  --url "$BASE/raiBlocklists/bl-internal-terms/raiBlocklistItems?api-version=$API" \
  --query "value[].{item:name, pattern:properties.pattern, regex:properties.isRegex}" -o table

Regex rules that catch people out

Behaviour What to do
Regex matching is case-sensitive by default Use character classes ([Ff]alcon) or an inline flag if your pattern engine accepts it, then test
^ and $ anchors can behave unexpectedly on streamed output Avoid anchors, or test with streaming turned on
Each pattern has a length limit, and each list has a term limit Check the current limits in the docs. When a list is full, create a second list and attach both
Backslashes need escaping twice in a JSON body inside a shell string Run a GET after the PUT and confirm the stored pattern is what you meant

Step 3: Attach the blocklist to the content filter

Don't write the policy body from scratch. A PUT replaces the whole policy, so a body that leaves out contentFilters can reset your thresholds. Use GET, change the copy, then PUT it back:

POLICY=cf-chat-prod
az rest --method get --url "$BASE/raiPolicies/$POLICY?api-version=$API" > policy.json
cp policy.json policy.backup.json

jq '{properties: (.properties
     | .customBlocklists = ((.customBlocklists // [])
        + [{"blocklistName":"bl-internal-terms","blocking":true,"source":"Prompt"},
           {"blocklistName":"bl-internal-terms","blocking":true,"source":"Completion"}]))}' \
   policy.json > policy.new.json

diff <(jq -S . policy.json) <(jq -S . policy.new.json)
az rest --method put --url "$BASE/raiPolicies/$POLICY?api-version=$API" --body @policy.new.json

source: Prompt checks user input. source: Completion checks model output. Use both when the goal is "this term must never appear". With blocking: false, the term is only annotated, which is useful for a trial run.

Note

The policy schema varies by API version. Some older examples use separate promptBlocklists and completionBlocklists arrays instead of customBlocklists with a source field. Follow the shape your GET returns for the API version you call.

If the filter isn't assigned to the deployment yet, assign it in the portal (Models + endpoints → deployment → Edit → content filter), or set raiPolicyName in your Bicep or Terraform deployment resource. Put it in IaC either way. If you don't, the next pipeline run can put the deployment back on the default filter.

Step 4: Test the hit

New terms can take about five minutes to take effect. Wait before you conclude they don't work.

ENDPOINT=$(az cognitiveservices account show -g $RG -n $ACCOUNT --query properties.endpoint -o tsv)
TOKEN=$(az account get-access-token --resource https://cognitiveservices.azure.com --query accessToken -o tsv)

curl -s "${ENDPOINT}openai/deployments/$DEPLOYMENT/chat/completions?api-version=2024-10-21" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"What is the status of Project Falcon?"}]}' | jq .error

A prompt-side hit returns HTTP 400 with code: content_filter and innererror.code: ResponsibleAIPolicyViolation. The blocklist shows up under content_filter_result.custom_blocklists:

"custom_blocklists": {
  "filtered": true,
  "details": [{ "filtered": true, "id": "bl-internal-terms" }]
}

A completion-side hit returns HTTP 200 with finish_reason: "content_filter" and content_filter_results.custom_blocklists on the choice. Your app should already handle both cases, as it does for built-in filter hits.

Troubleshooting

Symptom Likely cause Fix
Term never blocks Less than ~5 minutes since the add, wrong case on a regex, or the list was attached with only one source Wait, test the exact casing, check customBlocklists in the policy
Blocks in one app but not another The apps call different deployments with different filters Compare raiPolicyName across deployments
403 on raiBlocklists calls Missing Cognitive Services Contributor on the resource Grant the role at resource scope
Policy thresholds changed after the attach PUT with a partial body Restore with --body @policy.backup.json
Legitimate traffic suddenly blocked Regex too broad Delete the item (below), then redesign the pattern

Remove a bad term quickly:

az rest --method delete \
  --url "$BASE/raiBlocklists/bl-internal-terms/raiBlocklistItems/corp-hostnames?api-version=$API"

Prevent it next time

  • Keep blocklists and items in source control and apply them from a pipeline, the same way you apply deployments. Review each new term like a firewall rule.
  • Keep a test set of prompts that must pass and prompts that must be blocked. Run it after every blocklist change.
  • Alert on a sudden rise in content_filter responses for a deployment. That is usually the first sign of an over-broad term.
  • A blocklist is not a data loss prevention system. Spelling variants and paraphrases get through. Pair it with PII redaction and output checks for anything sensitive.