Azure AI Content Safety Client Library for Python

1.0.0 · active · verified Mon Apr 13

The Microsoft Azure AI Content Safety Client Library for Python (version 1.0.0) provides a robust solution for detecting harmful user-generated and AI-generated content in applications and services. It offers APIs for analyzing text and images across categories such as sexual content, violence, hate, and self-harm, with multi-severity levels. The library is actively developed and maintained as part of the broader Azure SDK for Python, with frequent updates and a focus on enterprise-grade content moderation.

Warnings

Install

Imports

Quickstart

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.")

view raw JSON →