(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisbon

How to moderate text with Azure AI Content Safety in Python

João Barros 07 de July de 2026 4 min read

Content moderation is no longer optional in any application that accepts text written by users. Azure AI Content Safety analyzes a sentence and returns a severity level for four risk categories — hate, violence, sexual content and self-harm — without you having to train any model or maintain lists of banned words. You will learn to configure the service and moderate text with Python in a few minutes, with a working example you can adapt to your product.

Prerequisites

  • An active Azure subscription (the service has a free tier for testing).
  • Python 3.8 or higher installed.
  • Permissions to create resources in the Azure portal.
  • Basic command-line and Python knowledge.

Step 1: Create the Azure AI Content Safety resource

In the Azure portal, create a Content Safety resource (also available as part of a multi-service Azure AI Services resource). Choose the subscription, a resource group, a region close to your users and a name. The region matters for two reasons: it reduces call latency and helps meet data residency requirements. Once created, open the Keys and Endpoint section and copy one of the keys and the endpoint — you will need both in the code.

Step 2: Install the SDK and store the credentials

Install the official library with pip. It is good practice to keep the key and endpoint in environment variables, so you do not leave secrets written in the code or in repositories.

pip install azure-ai-contentsafety

# Linux / macOS
export CONTENT_SAFETY_KEY="a-tua-chave"
export CONTENT_SAFETY_ENDPOINT="https://SEU-RECURSO.cognitiveservices.azure.com/"

On Windows use setx instead of export and reopen the terminal so the variables become available.

Step 3: Analyze text in Python

Create a moderar.py file. The code creates a ContentSafetyClient, sends a sentence and receives the analysis of the four content categories.

import os
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions
from azure.core.credentials import AzureKeyCredential

endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
key = os.environ["CONTENT_SAFETY_KEY"]

client = ContentSafetyClient(endpoint, AzureKeyCredential(key))

texto = "Bom dia! Alguem me pode ajudar com uma duvida?"
resposta = client.analyze_text(AnalyzeTextOptions(text=texto))

for item in resposta.categories_analysis:
    print(f"{item.category}: severidade {item.severity}")

Run it with python moderar.py. Each line shows a category — Hate, SelfHarm, Sexual and Violence — and the corresponding severity level returned by the service. Each category is evaluated independently, so the same sentence can have high severity in one and 0 in the others.

Step 4: Decide what to block with a threshold

The service does not decide for you whether content is acceptable: it only returns severities. It is your application that sets the threshold above which it rejects the text. A threshold of 4 is usually a good starting point.

LIMIAR = 4

bloquear = any(item.severity >= LIMIAR for item in resposta.categories_analysis)
print("Conteudo bloqueado" if bloquear else "Conteudo aprovado")

Adjust the value to the context: a forum for children needs a lower threshold than a platform for adults. You can also apply different thresholds per category.

Never rely on automated moderation alone for high-risk decisions: combine it with human review whenever the severity is borderline.

Verify the result

To confirm the integration works, test with clearly safe and clearly problematic sentences. A neutral sentence should return severity 0 in every category, while an offensive sentence should raise the severity in the matching category. The scale goes from 0 (safe) to 6 (high risk), with default values 0, 2, 4 and 6. If you get an authentication error, check the endpoint and the key; if the result is always 0, make sure you are actually sending the correct test text.

Conclusion

With a few lines of Python you now have text moderation ready to plug into forms, chats or comments, without training models or maintaining word lists by hand. The natural next step is to analyze images too with the analyze_image method, create custom blocklists for terms specific to your domain, and log decisions for auditing. Which threshold makes sense for your product — do you prefer to over-block, or risk letting something through?