Custom Blocklists with Azure Content Safety
Setup
Install the required packages and configure your Azure credentials.
import os
from getpass import getpass
def ensure_env_var(name: str) -> None:
"""Prompt for an environment variable if not already set."""
if name not in os.environ:
print(f"{name} not found in environment!")
value = getpass(f"Please enter your {name}: ")
os.environ[name] = value
print(f"{name} set for this session!")
else:
print(f"{name} found in environment.")
for var in ["CONTENT_SAFETY_KEY", "CONTENT_SAFETY_ENDPOINT"]:
ensure_env_var(var)Create a Blocklist
Initialize the guardrail and create a new blocklist. Here we're creating one for Gen Alpha slang terms.
##Add Terms to the Blocklist
Add the specific terms you want to filter. These can be individual words or phrases.
Validate Text
Test the blocklist against sample text. The guardrail returns valid=True if no blocked terms are found, and valid=False with details about which terms were matched.
Below, test against a classic novel - Anne of Green Gables from Project Gutenberg. This demonstrates that literature from 1908 contains no Gen Alpha slang (as expected!).
Next Steps
Try adding your own terms to the blocklist
You can use blocklists to filter competitor brand names, profanity, or domain-specific terms
Combine blocklist filtering with other Azure Content Safety features (hate, violence, etc.)
For more information, see the Azure Content Safety blocklist documentation.
Last updated