opción
HogarHogar Skill Seguridad azure-ai-contentsafety-py

azure-ai-contentsafety-py

microsoft/skills microsoft/skills

Detecta contenidos nocivos generados por los usuarios y por IA, tanto en texto como en imágenes, mediante el SDK de Azure AI Content Safety para Python.

...Expandir todo
1
Tiempo actualizado 14 de septiembre de 2026

SDK de Azure AI Content Safety para Python

Detecta contenido perjudicial generado por los usuarios y por la IA en las aplicaciones.

Instalación

pip install azure-ai-contentsafety

Variables de entorno

CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com  # Obligatorio para todos los métodos de autenticación
AZURE_TOKEN_CREDENTIALS=prod # Solo se requiere si se utiliza DefaultAzureCredential en producción
CONTENT_SAFETY_KEY= # Solo se requiere para la ruta de autenticación con clave de API heredada que se indica a continuación

Autenticación y ciclo de vida

🔑 Hay dos reglas que se aplican a todos los ejemplos de código que aparecen a continuación:

  1. Da preferencia a DefaultAzureCredential. Funciona tanto a nivel local (Azure CLI / VS Code / Developer CLI) como en Azure (identidad gestionada, identidad de carga de trabajo) sin necesidad de modificar el código. Evita las cadenas de conexión y las claves de cuenta o API, ya que eluden la auditoría y la rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establece AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=) para restringir la cadena de credenciales a aquellas seguras para producción.
  2. Envuelve cada cliente en un gestor de contexto para que los transportes HTTP, los sockets y las cachés de tokens se liberen de forma determinista:
    • Sincrónico: con (...) como cliente:
    • Asíncrono: async con (...) como cliente: y async con DefaultAzureCredential() como credencial: (de azure.identity.aio)

Los fragmentos de código pueden abreviar esta configuración, pero el código de producción siempre debe seguir ambas reglas.

import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

# Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# O bien, utiliza una credencial específica directamente en producción:
# Consulta https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=credential,
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))

Antiguo: clave de API (implementaciones con clave existentes)

El código nuevo debe utilizar DefaultAzureCredential, tal y como se indica arriba. Utilice AzureKeyCredential solo si tiene una implementación con clave ya existente que aún no se haya migrado a Entra ID; por ejemplo, entornos regulados que aún estén completando su implantación de Entra.

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

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["CONTENT_SAFETY_KEY"]),
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="¡Hola, mundo!"))

BlocklistClient acepta la misma AzureKeyCredential si también necesitas gestionar listas de bloqueo con una clave.

Analizar texto

from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.identity import DefaultAzureCredential

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    request = AnalyzeTextOptions(text="Tu contenido de texto para analizar")
    response = client.analyze_text(request)

    # Comprobar cada categoría
    for category in [TextCategory.HATE, TextCategory.SELF_HARM, 
                     TextCategory.SEXUAL, TextCategory.VIOLENCE]:
        result = next((r for r in response.categories_analysis 
                       if r.category == category), None)
        if result:
            print(f"{category}: gravedad {result.severity}")

Analizar imagen

from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
from azure.identity import DefaultAzureCredential
import base64

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    # Desde un archivo
    with open("image.jpg", "rb") as f:
        image_data = base64.b64encode(f.read()).decode("utf-8")

    request = AnalyzeImageOptions(
        image=ImageData(content=image_data)
    )

    response = client.analyze_image(request)

    for result in response.categories_analysis:
        print(f"{result.category}: gravedad {result.severity}")

Imagen desde una URL

from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData

solicitud = AnalyzeImageOptions(
    imagen = ImageData(blob_url = "https://example.com/image.jpg")
)

respuesta = client.analyze_image(solicitud)

Gestión de la lista de bloques de texto

Crear lista de bloqueados

from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import TextBlocklist
from azure.identity import DefaultAzureCredential

with BlocklistClient(endpoint, DefaultAzureCredential()) as blocklist_client:
    lista_de_bloqueo = TextBlocklist(
        nombre_de_la_lista_de_bloqueo="my-blocklist",
        descripción="Términos personalizados para bloquear"
    )

    result = blocklist_client.create_or_update_text_blocklist(
        blocklist_name="my-blocklist",
        options=blocklist
    )

Añadir elementos a la lista de bloqueo

from azure.ai.contentsafety.models import AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem

items = AddOrUpdateTextBlocklistItemsOptions(
    blocklist_items=[
        TextBlocklistItem(text="término-bloqueado-1"),
        TextBlocklistItem(text="término-bloqueado-2")
    ]
)

resultado = blocklist_client.add_or_update_blocklist_items(
    nombre_de_la_lista_de_bloqueo="mi-lista-de-bloqueo",
    opciones=elementos
)

Analizar con la lista de bloqueados

from azure.ai.contentsafety.models import AnalyzeTextOptions

solicitud = AnalyzeTextOptions(
    texto = "Texto que contiene término-bloqueado-1",
    nombres_de_listas_de_bloqueo = ["mi-lista-de-bloqueo"],
    detener_al_encontrar_coincidencia_en_lista_de_bloqueo = True
)

response = client.analyze_text(request)

if response.blocklists_match:
    for match in response.blocklists_match:
        print(f"Bloqueado: {match.blocklist_item_text}")

Niveles de gravedad

El análisis de texto devuelve 4 niveles de gravedad (0, 2, 4, 6) de forma predeterminada. Para 8 niveles (0-7):

from azure.ai.contentsafety.models import AnalyzeTextOptions, AnalyzeTextOutputType

solicitud = AnalyzeTextOptions(
    texto = "Tu texto",
    tipo_de_salida = AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS
)

Categorías de daño

Categoría Descripción
Odio Ataques basados en la identidad (raza, religión, género, etc.)
Sexuales Contenido sexual, relaciones, anatomía
Violencia Daño físico, armas, lesiones
Autolesiones Autolesiones, suicidio, trastornos alimentarios

Escala de gravedad

Nivel Rango de texto Rango de la imagen Significado
0 Seguro Seguro Sin contenido perjudicial
2 Bajo Bajo Referencias leves
4 Medio Medio Contenido moderado
6 Alto Alto Contenido grave

Tipos de clientes

Cliente Finalidad
ContenidoSeguridadCliente Analizar texto e imágenes
BlocklistClient Gestionar listas de bloqueo personalizadas

Prácticas recomendadas

  1. Elige entre sincrónico o asíncrono y mantén la coherencia. No mezcles clientes sincrónicos de azure.ai.contentsafety con clientes asíncronos de azure.ai.contentsafety.aio en la misma ruta de llamada. Elige un modo por módulo.
  2. Utilice siempre gestores de contexto para los clientes y las credenciales asíncronas. Envuelva cada cliente con ContentSafetyClient(...) como cliente: (sincrónico) o asíncrono con ContentSafetyClient(...) como cliente: (asíncrono). Para DefaultAzureCredential asíncrono de azure.identity.aio, utilice también async con credential: para que se eliminen los tokens y los transportes.
  3. Utiliza listas de bloqueo para términos específicos del dominio
  4. Establece umbrales de gravedad adecuados para tu caso de uso
  5. Gestiona múltiples categorías: el contenido puede ser perjudicial de diversas formas
  6. Utilice halt_on_blocklist_hit para el rechazo inmediato
  7. Registra los resultados del análisis para auditorías y mejoras
  8. Considera el modo de 8 niveles de gravedad para un control más preciso
  9. Modera previamente los resultados de la IA antes de mostrárselos a los usuarios
Ver en GitHub
---
name: azure-ai-contentsafety-py
description: Detect harmful user-generated and AI-generated content in text and images using Azure AI Content Safety SDK for Python.
license: MIT
---

# Azure AI Content Safety SDK for Python

Detect harmful user-generated and AI-generated content in applications.

## Installation

```bash
pip install azure-ai-contentsafety
```

## Environment Variables

```bash
CONTENT_SAFETY_ENDPOINT=https://<resource>.cognitiveservices.azure.com  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
CONTENT_SAFETY_KEY=<your-api-key>  # Only required for the legacy API-key auth path below
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
import os
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=credential,
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))
```

### Legacy: API Key (existing keyed deployments)

New code should use `DefaultAzureCredential` above. Use `AzureKeyCredential` only if you have an existing keyed deployment that hasn't been migrated to Entra ID yet — for example, regulated environments still completing their Entra rollout.

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

with ContentSafetyClient(
    endpoint=os.environ["CONTENT_SAFETY_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["CONTENT_SAFETY_KEY"]),
) as client:
    response = client.analyze_text(AnalyzeTextOptions(text="Hello, world!"))
```

The `BlocklistClient` accepts the same `AzureKeyCredential` if you also need to manage blocklists with a key.

## Analyze Text

```python
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeTextOptions, TextCategory
from azure.identity import DefaultAzureCredential

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    request = AnalyzeTextOptions(text="Your text content to analyze")
    response = client.analyze_text(request)

    # Check each category
    for category in [TextCategory.HATE, TextCategory.SELF_HARM, 
                     TextCategory.SEXUAL, TextCategory.VIOLENCE]:
        result = next((r for r in response.categories_analysis 
                       if r.category == category), None)
        if result:
            print(f"{category}: severity {result.severity}")
```

## Analyze Image

```python
from azure.ai.contentsafety import ContentSafetyClient
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData
from azure.identity import DefaultAzureCredential
import base64

with ContentSafetyClient(endpoint, DefaultAzureCredential()) as client:
    # From file
    with open("image.jpg", "rb") as f:
        image_data = base64.b64encode(f.read()).decode("utf-8")

    request = AnalyzeImageOptions(
        image=ImageData(content=image_data)
    )

    response = client.analyze_image(request)

    for result in response.categories_analysis:
        print(f"{result.category}: severity {result.severity}")
```

### Image from URL

```python
from azure.ai.contentsafety.models import AnalyzeImageOptions, ImageData

request = AnalyzeImageOptions(
    image=ImageData(blob_url="https://example.com/image.jpg")
)

response = client.analyze_image(request)
```

## Text Blocklist Management

### Create Blocklist

```python
from azure.ai.contentsafety import BlocklistClient
from azure.ai.contentsafety.models import TextBlocklist
from azure.identity import DefaultAzureCredential

with BlocklistClient(endpoint, DefaultAzureCredential()) as blocklist_client:
    blocklist = TextBlocklist(
        blocklist_name="my-blocklist",
        description="Custom terms to block"
    )

    result = blocklist_client.create_or_update_text_blocklist(
        blocklist_name="my-blocklist",
        options=blocklist
    )
```

### Add Block Items

```python
from azure.ai.contentsafety.models import AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem

items = AddOrUpdateTextBlocklistItemsOptions(
    blocklist_items=[
        TextBlocklistItem(text="blocked-term-1"),
        TextBlocklistItem(text="blocked-term-2")
    ]
)

result = blocklist_client.add_or_update_blocklist_items(
    blocklist_name="my-blocklist",
    options=items
)
```

### Analyze with Blocklist

```python
from azure.ai.contentsafety.models import AnalyzeTextOptions

request = AnalyzeTextOptions(
    text="Text containing blocked-term-1",
    blocklist_names=["my-blocklist"],
    halt_on_blocklist_hit=True
)

response = client.analyze_text(request)

if response.blocklists_match:
    for match in response.blocklists_match:
        print(f"Blocked: {match.blocklist_item_text}")
```

## Severity Levels

Text analysis returns 4 severity levels (0, 2, 4, 6) by default. For 8 levels (0-7):

```python
from azure.ai.contentsafety.models import AnalyzeTextOptions, AnalyzeTextOutputType

request = AnalyzeTextOptions(
    text="Your text",
    output_type=AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS
)
```

## Harm Categories

| Category | Description |
|----------|-------------|
| `Hate` | Attacks based on identity (race, religion, gender, etc.) |
| `Sexual` | Sexual content, relationships, anatomy |
| `Violence` | Physical harm, weapons, injury |
| `SelfHarm` | Self-injury, suicide, eating disorders |

## Severity Scale

| Level | Text Range | Image Range | Meaning |
|-------|------------|-------------|---------|
| 0 | Safe | Safe | No harmful content |
| 2 | Low | Low | Mild references |
| 4 | Medium | Medium | Moderate content |
| 6 | High | High | Severe content |

## Client Types

| Client | Purpose |
|--------|---------|
| `ContentSafetyClient` | Analyze text and images |
| `BlocklistClient` | Manage custom blocklists |

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.ai.contentsafety` sync clients with `azure.ai.contentsafety.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with ContentSafetyClient(...) as client:` (sync) or `async with ContentSafetyClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use blocklists** for domain-specific terms
4. **Set severity thresholds** appropriate for your use case
5. **Handle multiple categories** — content can be harmful in multiple ways
6. **Use halt_on_blocklist_hit** for immediate rejection
7. **Log analysis results** for audit and improvement
8. **Consider 8-severity mode** for finer-grained control
9. **Pre-moderate AI outputs** before showing to users

Todos los archivos

0 archivos

Instalar azure-ai-contentsafety-py

Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.

Descargar ZIP

Clona el repositorio y copia los archivos de la habilidad a tu proyecto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-ai-contentsafety-py # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuración rápida: Copia la carpeta de la habilidad en .claude/skills/ Claude detectará y utilizará automáticamente la habilidad
Repositorio microsoft/skills

Habilidades relacionadas

gmgn-portfolio
Tiempo actualizado 1 de julio de 2026
zeroize-audit
Tiempo actualizado 1 de julio de 2026
device-integrity
Tiempo actualizado 29 de junio de 2026
flutter-use-http-package
Tiempo actualizado 30 de junio de 2026
OR