Azure AI Content Safety is a dedicated service that detects harmful content across text and images. Every Azure OpenAI deployment includes built-in content filters, but the standalone Content Safety service provides deeper customization, custom categories, and blocklists for your specific domain.
π Reference: Azure AI Content Safety
Content Safety analyzes text across four harm categories:
| Category | Description | Examples |
|---|---|---|
| Hate | Content targeting identity groups | Slurs, discrimination, stereotypes |
| Violence | Content depicting physical harm | Threats, graphic descriptions |
| Sexual | Sexually explicit content | Explicit descriptions, solicitation |
| Self-Harm | Content related to self-injury | Instructions, glorification |
Each category returns a severity score:
| Level | Range | Meaning | Typical Action |
|---|---|---|---|
| Safe | 0β1 | No harmful content | Allow |
| Low | 2β3 | Mild or contextual | Allow with logging |
| Medium | 4β5 | Moderate harmful content | Block or review |
| High | 6β7 | Severe harmful content | Block immediately |
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.core.credentials import AzureKeyCredential
client = ContentSafetyClient(
endpoint="https://<your-resource>.cognitiveservices.azure.com",
credential=AzureKeyCredential("<your-key>")
)
# Analyze text for harmful content
request = AnalyzeTextOptions(
text="This is a sample text to analyze for safety.",
categories=[
TextCategory.HATE,
TextCategory.VIOLENCE,
TextCategory.SEXUAL,
TextCategory.SELF_HARM
]
)
response = client.analyze_text(request)
for result in response.categories_analysis:
print(f"Category: {result.category}, Severity: {result.severity}")
if result.severity >= 4:
print(f" β οΈ BLOCKED β severity {result.severity} exceeds threshold")
Content Safety also analyzes images using the same four categories and severity scale.
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
# Analyze an image from a URL
request = AnalyzeImageOptions(
image=ImageData(blob_url="https://example.com/image.jpg")
)
response = client.analyze_image(request)
for result in response.categories_analysis:
print(f"Category: {result.category}, Severity: {result.severity}")
π Reference: Image moderation quickstart
For domain-specific moderation, you can create custom blocklists:
from azure.ai.contentsafety.models import (
TextBlocklist,
AddOrUpdateTextBlocklistItemsOptions,
TextBlocklistItem
)
# Create a blocklist
blocklist_name = "financial-terms-blocklist"
client.create_or_update_text_blocklist(
blocklist_name=blocklist_name,
options=TextBlocklist(description="Blocked financial advice terms")
)
# Add terms to the blocklist
items = AddOrUpdateTextBlocklistItemsOptions(
blocklist_items=[
TextBlocklistItem(text="guaranteed returns"),
TextBlocklistItem(text="risk-free investment"),
TextBlocklistItem(text="insider tip"),
]
)
client.add_or_update_blocklist_items(
blocklist_name=blocklist_name,
options=items
)
request = AnalyzeTextOptions(
text="I have an insider tip for a risk-free investment.",
blocklist_names=["financial-terms-blocklist"],
halt_on_blocklist_hit=True
)
response = client.analyze_text(request)
if response.blocklists_match:
for match in response.blocklists_match:
print(f"Blocked term: '{match.blocklist_item_text}' "
f"from list: {match.blocklist_name}")
Azure OpenAI deployments have built-in content filters that you can customize in AI Foundry:
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint="https://<your-resource>.openai.azure.com",
api_key="<your-key>",
api_version="2024-06-01"
)
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me about renewable energy."}
]
)
print(response.choices[0].message.content)
except Exception as e:
# Content filter violations raise exceptions
if "content_filter" in str(e):
print("Content was filtered by Azure AI safety systems.")
else:
raise
π Reference: Configure content filters