Install & Compatibility
Where this runs
tested against v1.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.412s · 23.9MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.4s · import 0.382s · 24MB
22MB installed
● package 22MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
ContentSafetyClient
✓ from azure.ai.contentsafety import ContentSafetyClient
BlocklistClient
✓ from azure.ai.contentsafety import BlocklistClient
AnalyzeTextOptions
✓ from azure.ai.contentsafety.models import AnalyzeTextOptions
TextCategory
✓ from azure.ai.contentsafety.models import TextCategory
AzureKeyCredential
✓ from azure.core.credentials import AzureKeyCredential
Required for API key authentication.
DefaultAzureCredential
✓ from azure.identity import DefaultAzureCredential
Required for Azure Active Directory (Microsoft Entra ID) authentication. Install 'azure-identity' package.
This quickstart demonstrates how to initialize the `ContentSafetyClient` using an API key and analyze a piece of text for harmful content across different categories. Ensure you have your Azure Content Safety resource endpoint and API key configured as environment variables (`CONTENT_SAFETY_ENDPOINT` and `CONTENT_SAFETY_KEY`). The output will show the detected categories and their severity levels.
import os
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
# Set your Azure Content Safety endpoint and key as environment variables
# e.g., export CONTENT_SAFETY_ENDPOINT="https://<your-resource-name>.cognitiveservices.azure.com/"
# e.g., export CONTENT_SAFETY_KEY="<your-api-key>"
endpoint = os.environ.get("CONTENT_SAFETY_ENDPOINT", "").strip()
key = os.environ.get("CONTENT_SAFETY_KEY", "").strip()
if not endpoint or not key:
print("Please set the environment variables CONTENT_SAFETY_ENDPOINT and CONTENT_SAFETY_KEY.")
exit(1)
# Create a Content Safety client
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
# Text to analyze
text_to_analyze = "I hate you. You are an idiot and I will harm you."
# Construct the analysis request
request = AnalyzeTextOptions(text=text_to_analyze)
try:
response = client.analyze_text(request)
print(f"Analyzing text: '{text_to_analyze}'")
for category_result in response.categories_analysis:
if category_result.severity is not None:
print(f" Category: {category_result.category}, Severity: {category_result.severity}")
else:
print(f" Category: {category_result.category}, No severity detected.")
except HttpResponseError as e:
print(f"Analyze text failed: {e.reason}")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print("\nText analysis complete.")
Debug
Known issues
breakingPublic Preview SDKs (versions prior to 1.0.0) were deprecated by March 31, 2024. Applications using older versions must update to the Generally Available (GA) SDK (1.0.0 or later) as API names and return formats have changed significantly.fixUpgrade to `azure-ai-contentsafety==1.0.0` or later and update your code to match the GA API definitions and return formats. Refer to the official migration guides.
affects: <1.0.0
deprecatedAll API versions of the Azure AI Content Safety service prior to '2024-09-01' (excluding specific preview versions like '2024-09-15-preview' and '2024-09-30-preview') are scheduled for deprecation by March 1st, 2025.fixEnsure your client is using an API version supported after March 1st, 2025. The Python SDK's default API version should be kept updated by upgrading the package.
affects: <2024-09-01 (API versions)
gotchaAuthentication requires either an Azure API Key (via `AzureKeyCredential`) or an Azure Active Directory (Microsoft Entra ID) token credential (via `DefaultAzureCredential` from `azure-identity`). Incorrect endpoint, API key, or insufficient role assignments (e.g., 'Cognitive Services User' role) are common causes of authentication failures.fixVerify that `CONTENT_SAFETY_ENDPOINT` and `CONTENT_SAFETY_KEY` environment variables (or other credential sources) are correctly set and correspond to an active Content Safety resource. For Entra ID, ensure the service principal has the necessary 'Cognitive Services User' role. Install `azure-identity` for `DefaultAzureCredential`.
affects: All
gotchaThe library provides two distinct client types: `ContentSafetyClient` for analyzing text and images, and `BlocklistClient` for managing custom blocklists. Ensure you are using the correct client for your intended operation.fixInstantiate `ContentSafetyClient` for content analysis and `BlocklistClient` for blocklist creation, update, and deletion. Do not attempt blocklist operations with the `ContentSafetyClient` and vice-versa.
affects: All
gotchaThe Content Safety service has input limitations for text and images (e.g., maximum text length). Exceeding these limits or providing unsupported content types (e.g., non-image files to image analysis) will result in `HttpResponseError`.fixConsult the official 'Input requirements' documentation for the specific API you are using to ensure your content adheres to size, format, and language support guidelines before sending requests. Handle `HttpResponseError` gracefully to catch validation issues.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'azure.ai.contentsafety'
The 'azure-ai-contentsafety' package is not installed in the Python environment.
fixInstall the package using pip: 'pip install azure-ai-contentsafety'.
ImportError: cannot import name 'ContentSafetyClient' from 'azure.ai.contentsafety'
The 'ContentSafetyClient' class is not available in the installed version of the 'azure-ai-contentsafety' package.
fixEnsure you have the latest version of the package: 'pip install --upgrade azure-ai-contentsafety'.
AttributeError: module 'azure.ai.contentsafety' has no attribute 'analyze_text'
The 'analyze_text' method is not present in the 'azure-ai-contentsafety' package.
fixRefer to the official documentation to use the correct method for text analysis.
TypeError: 'NoneType' object is not callable
An API key or endpoint is missing or incorrect when initializing the 'ContentSafetyClient'.
fixProvide a valid API key and endpoint when creating the client instance.
ValueError: Invalid input data for content analysis
The input data provided to the content analysis method is not in the expected format.
fixEnsure the input data meets the format requirements specified in the documentation.
Upgrade
Version history
1.0.0latest on PyPI · released Dec 12, 2023
Audit
Dependencies
azure-corerequiredProvides core Azure functionalities and shared primitives like AzureKeyCredential for authentication.
azure-identityoptionalRequired for Azure Active Directory (Microsoft Entra ID) token-based authentication using DefaultAzureCredential.