Microsoft Azure AI Content Safety client library for Python providing text and image content analysis APIs with harm category detection and blocklist management
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive text blocklist management capabilities for creating, managing, and maintaining custom lists of prohibited terms. Blocklists enable organizations to screen content for domain-specific terms that should be blocked or flagged, complementing the AI-powered content analysis.
Create, retrieve, update, and delete text blocklists to organize prohibited terms by category, use case, or severity level.
def create_or_update_text_blocklist(
self,
blocklist_name: str,
options: Union[TextBlocklist, dict, IO[bytes]],
**kwargs
) -> TextBlocklist:
"""
Create a new text blocklist or update an existing one.
Parameters:
- blocklist_name: Name of the blocklist to create or update
- options: Blocklist resource with name and optional description
- content_type: Body parameter content-type (default: "application/merge-patch+json")
- stream: Whether to stream the response (default: False)
Returns:
TextBlocklist: The created or updated blocklist resource
Raises:
HttpResponseError: On creation/update failure
"""
def get_text_blocklist(self, blocklist_name: str, **kwargs) -> TextBlocklist:
"""
Get details of a specific text blocklist by name.
Parameters:
- blocklist_name: Name of the blocklist to retrieve
- stream: Whether to stream the response (default: False)
Returns:
TextBlocklist: The blocklist resource with metadata
Raises:
HttpResponseError: On retrieval failure or if blocklist doesn't exist
"""
def list_text_blocklists(self, **kwargs) -> Iterable[TextBlocklist]:
"""
List all text blocklists in the Content Safety resource.
Parameters:
- maxpagesize: Maximum items per page (passed via kwargs)
Returns:
ItemPaged[TextBlocklist]: Paginated list of all blocklists
Raises:
HttpResponseError: On listing failure
"""
def delete_text_blocklist(self, blocklist_name: str, **kwargs) -> None:
"""
Delete a text blocklist and all its items.
Parameters:
- blocklist_name: Name of the blocklist to delete
Returns:
None
Raises:
HttpResponseError: On deletion failure or if blocklist doesn't exist
"""Usage Example:
from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import TextBlocklist
from azure.core.credentials import AzureKeyCredential
client = BlocklistClient(
endpoint="https://your-resource.cognitiveservices.azure.com",
credential=AzureKeyCredential("your-api-key")
)
# Create a new blocklist
blocklist = TextBlocklist(
blocklist_name="profanity-filter",
description="Common profanity and inappropriate terms"
)
created_blocklist = client.create_or_update_text_blocklist("profanity-filter", blocklist)
print(f"Created blocklist: {created_blocklist.blocklist_name}")
# List all blocklists
all_blocklists = client.list_text_blocklists()
for bl in all_blocklists:
print(f"Blocklist: {bl.blocklist_name} - {bl.description}")
# Get specific blocklist
specific_blocklist = client.get_text_blocklist("profanity-filter")
print(f"Retrieved: {specific_blocklist.description}")
# Delete blocklist (when no longer needed)
# client.delete_text_blocklist("profanity-filter")
client.close()Add, update, retrieve, and remove individual terms within blocklists, with support for bulk operations and pagination.
def add_or_update_blocklist_items(
self,
blocklist_name: str,
options: Union[AddOrUpdateTextBlocklistItemsOptions, dict, IO[bytes]],
**kwargs
) -> AddOrUpdateTextBlocklistItemsResult:
"""
Add or update items in a text blocklist (max 100 items per request).
Parameters:
- blocklist_name: Name of the target blocklist
- options: Options containing list of items to add or update
- content_type: Body parameter content-type (default: "application/json")
- stream: Whether to stream the response (default: False)
Returns:
AddOrUpdateTextBlocklistItemsResult: Result with added/updated items
Raises:
HttpResponseError: On operation failure or if blocklist doesn't exist
"""
def get_text_blocklist_item(
self,
blocklist_name: str,
blocklist_item_id: str,
**kwargs
) -> TextBlocklistItem:
"""
Get a specific blocklist item by ID.
Parameters:
- blocklist_name: Name of the containing blocklist
- blocklist_item_id: UUID of the specific item
- stream: Whether to stream the response (default: False)
Returns:
TextBlocklistItem: The requested blocklist item
Raises:
HttpResponseError: On retrieval failure or if item doesn't exist
"""
def list_text_blocklist_items(
self,
blocklist_name: str,
*,
top: Optional[int] = None,
skip: Optional[int] = None,
**kwargs
) -> Iterable[TextBlocklistItem]:
"""
List all items in a text blocklist with pagination support.
Parameters:
- blocklist_name: Name of the blocklist to query
- top: Maximum number of items to return
- skip: Number of items to skip for pagination
- maxpagesize: Maximum items per page (passed via kwargs)
Returns:
ItemPaged[TextBlocklistItem]: Paginated list of blocklist items
Raises:
HttpResponseError: On listing failure or if blocklist doesn't exist
"""
def remove_blocklist_items(
self,
blocklist_name: str,
options: Union[RemoveTextBlocklistItemsOptions, dict, IO[bytes]],
**kwargs
) -> None:
"""
Remove items from a text blocklist (max 100 items per request).
Parameters:
- blocklist_name: Name of the target blocklist
- options: Options containing list of item IDs to remove
- content_type: Body parameter content-type (default: "application/json")
Returns:
None
Raises:
HttpResponseError: On removal failure or if blocklist doesn't exist
"""Usage Example:
from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import (
AddOrUpdateTextBlocklistItemsOptions,
RemoveTextBlocklistItemsOptions,
TextBlocklistItem
)
from azure.core.credentials import AzureKeyCredential
client = BlocklistClient(
endpoint="https://your-resource.cognitiveservices.azure.com",
credential=AzureKeyCredential("your-api-key")
)
# Add items to blocklist
items_to_add = [
TextBlocklistItem(text="inappropriate-term-1"),
TextBlocklistItem(text="inappropriate-term-2"),
TextBlocklistItem(text="inappropriate-term-3")
]
add_request = AddOrUpdateTextBlocklistItemsOptions(blocklist_items=items_to_add)
result = client.add_or_update_blocklist_items("profanity-filter", add_request)
print(f"Added {len(result.blocklist_items)} items to blocklist")
for item in result.blocklist_items:
print(f" - ID: {item.blocklist_item_id}, Text: {item.text}")
# List all items in blocklist
all_items = client.list_text_blocklist_items("profanity-filter")
for item in all_items:
print(f"Item: {item.text} (ID: {item.blocklist_item_id})")
# Get specific item
if result.blocklist_items:
item_id = result.blocklist_items[0].blocklist_item_id
specific_item = client.get_text_blocklist_item("profanity-filter", item_id)
print(f"Retrieved item: {specific_item.text}")
# Remove specific items
items_to_remove = [item.blocklist_item_id for item in result.blocklist_items[:2]]
remove_request = RemoveTextBlocklistItemsOptions(blocklist_item_ids=items_to_remove)
client.remove_blocklist_items("profanity-filter", remove_request)
print(f"Removed {len(items_to_remove)} items from blocklist")
client.close()class TextBlocklist:
"""Text blocklist resource."""
def __init__(
self,
*,
blocklist_name: str,
description: Optional[str] = None
): ...
class TextBlocklistItem:
"""Individual blocklist item."""
def __init__(
self,
*,
text: str,
description: Optional[str] = None
): ...
# Read-only fields set by service
blocklist_item_id: Optional[str] # UUID assigned by service
class AddOrUpdateTextBlocklistItemsOptions:
"""Options for adding or updating blocklist items."""
def __init__(
self,
*,
blocklist_items: List[TextBlocklistItem]
): ...
class AddOrUpdateTextBlocklistItemsResult:
"""Result of adding or updating blocklist items."""
blocklist_items: List[TextBlocklistItem]
class RemoveTextBlocklistItemsOptions:
"""Options for removing blocklist items."""
def __init__(
self,
*,
blocklist_item_ids: List[str]
): ...Blocklists integrate seamlessly with content analysis to provide comprehensive content moderation:
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions
content_client = ContentSafetyClient(
endpoint="https://your-resource.cognitiveservices.azure.com",
credential=AzureKeyCredential("your-api-key")
)
# Analyze text with custom blocklist integration
request = AnalyzeTextOptions(
text="Text content to analyze",
blocklist_names=["profanity-filter", "company-specific-terms"],
halt_on_blocklist_hit=True # Stop analysis if blocklist match found
)
result = content_client.analyze_text(request)
# Check for blocklist matches
if result.blocklists_match:
print("Blocklist matches found:")
for match in result.blocklists_match:
print(f" - Blocklist: {match.blocklist_name}")
print(f" Item: {match.blocklist_item_text}")
print(f" ID: {match.blocklist_item_id}")
content_client.close()Blocklist management operations can raise various Azure Core exceptions:
from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
try:
blocklist = client.get_text_blocklist("non-existent-list")
except ResourceNotFoundError:
print("Blocklist not found")
except HttpResponseError as e:
print(f"Request failed: {e.status_code} - {e.message}")Common error scenarios:
Install with Tessl CLI
npx tessl i tessl/pypi-azure-ai-contentsafety