Option
HeimHeim Skill Sicherheit azure-ai-contentsafety-py

azure-ai-contentsafety-py

microsoft/skills microsoft/skills

Erkennen Sie schädliche, von Nutzern erstellte und KI-generierte Inhalte in Texten und Bildern mithilfe des Azure AI Content Safety SDK für Python.

...Alle erweitern
1
Zeit aktualisiert 14. September 2026

Azure AI Content Safety SDK für Python

Erkennen Sie schädliche, von Benutzern oder KI generierte Inhalte in Anwendungen.

Installation

pip install azure-ai-contentsafety

Umgebungsvariablen

CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com  # Für alle Authentifizierungsmethoden erforderlich
AZURE_TOKEN_CREDENTIALS=prod # Nur erforderlich, wenn „DefaultAzureCredential“ in der Produktion verwendet wird
CONTENT_SAFETY_KEY= # Nur erforderlich für den unten aufgeführten veralteten API-Schlüssel-Authentifizierungspfad

Authentifizierung und Lebenszyklus

🔑 Für alle folgenden Code-Beispiele gelten zwei Regeln:

  1. Verwenden Sie vorzugsweise „DefaultAzureCredential“. Es funktioniert lokal (Azure CLI / VS Code / Developer CLI) und in Azure (verwaltete Identität, Workload-Identität) ohne Codeänderungen. Vermeiden Sie Verbindungszeichenfolgen, Konto- und API-Schlüssel – diese umgehen die Entra-Überprüfung und -Rotation.
    • Lokale Entwicklung: „DefaultAzureCredential“ funktioniert unverändert.
    • Produktion: Setzen Sie AZURE_TOKEN_CREDENTIALS=prod (oder AZURE_TOKEN_CREDENTIALS=), um die Anmeldeketten auf produktionssichere Anmeldedaten zu beschränken.
  2. Hüllen Sie jeden Client in einen Kontextmanager ein, damit HTTP-Transporte, Sockets und Token-Caches deterministisch freigegeben werden:
    • Synchron: mit ` (...)` als Client:
    • Asynchron: async mit (...) als Client: und async mit DefaultAzureCredential() als Anmeldeinformationen: (aus azure.identity.aio)

Code-Schnipsel können diese Konfiguration zwar verkürzen, aber Produktionscode sollte stets beide Regeln befolgen.

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

# Lokale Entwicklung: DefaultAzureCredential. Produktion: Setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Oder verwenden Sie in der Produktion direkt spezifische Anmeldedaten:
# Siehe 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!"))

Veraltete Methode: API-Schlüssel (bestehende schlüsselbasierte Bereitstellungen)

Neuer Code sollte die oben genannte `DefaultAzureCredential` verwenden. Verwenden Sie `AzureKeyCredential` nur, wenn Sie über eine bestehende schlüsselbasierte Bereitstellung verfügen, die noch nicht auf Entra ID migriert wurde – beispielsweise in regulierten Umgebungen, in denen die Einführung von Entra noch nicht abgeschlossen ist.

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

Der `BlocklistClient` akzeptiert dieselbe ` AzureKeyCredential`, falls Sie auch Sperrlisten mit einem Schlüssel verwalten müssen.

Text analysieren

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="Ihr zu analysierender Textinhalt")
    response = client.analyze_text(request)

    # Jede Kategorie prüfen
    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}: Schweregrad {result.severity}")

Bild analysieren

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:
    # Aus Datei
    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}: Schweregrad {result.severity}")

Bild von einer URL

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

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

response = client.analyze_image(request)

Verwaltung der Text-Blockliste

Blockliste erstellen

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="Zu blockierende benutzerdefinierte Begriffe"
    )

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

Blockelemente hinzufügen

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
)

Mit Blockliste analysieren

from azure.ai.contentsafety.models import AnalyzeTextOptions

request = AnalyzeTextOptions(
    text="Text, der den Begriff 'blocked-term-1' enthält",
    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"Gesperrt: {match.blocklist_item_text}")

Schweregrade

Die Textanalyse gibt standardmäßig 4 Schweregrade (0, 2, 4, 6) zurück. Für 8 Stufen (0–7):

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

request = AnalyzeTextOptions(
    text="Ihr Text",
    output_type=AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS
)

Schadenskategorien

Kategorie Beschreibung
Hass Angriffe aufgrund der Identität (Ethnie, Religion, Geschlecht usw.)
Sexuell Sexuelle Inhalte, Beziehungen, Anatomie
Gewalt Körperliche Gewalt, Waffen, Verletzungen
Selbstverletzung Selbstverletzung, Selbstmord, Essstörungen

Schweregrad-Skala

Stufe Textbereich Bildbereich Bedeutung
0 Sicher Unbedenklich Keine schädlichen Inhalte
2 Gering Gering Leichte Anspielungen
4 Mittel Mittel Mäßiger Inhalt
6 Hoch Hoch Starker Inhalt

Kundentypen

Kunde Zweck
ContentSafetyClient Text und Bilder analysieren
BlocklistClient Benutzerdefinierte Sperrlisten verwalten

Bewährte Vorgehensweisen

  1. Entscheiden Sie sich für „sync“ ODER „async“ und bleiben Sie dabei. Mischen Sie keine „azure.ai.contentsafety “-Sync-Clients mit „azure.ai.contentsafety.aio “-Async-Clients im selben Aufrufpfad. Wählen Sie pro Modul einen Modus.
  2. Verwenden Sie für Clients und asynchrone Anmeldeinformationen stets Kontextmanager. Umschließen Sie jeden Client mit `ContentSafetyClient(...)` als Client: (synchron) oder asynchron mit `ContentSafetyClient(...)` als Client: (asynchron). Verwenden Sie für „async DefaultAzureCredential“ aus „azure.identity.aio“ ebenfalls „async“ mit „credential:“, damit Tokens und Transporte bereinigt werden.
  3. Verwenden Sie Blocklisten für domänenspezifische Begriffe
  4. Legen Sie für Ihren Anwendungsfall geeigneteSchweregradschwellenwerte fest
  5. Behandeln Sie mehrere Kategorien – Inhalte können auf verschiedene Arten schädlich sein
  6. Verwenden Sie „halt_on_blocklist_hit“ für eine sofortige Ablehnung
  7. Protokollieren Sie die Analyseergebnisse für Audits und Verbesserungen
  8. Ziehen Sie den 8-Stufen-Schweregradmodus für eine feinere Steuerungin Betracht
  9. Moderieren Sie KI-Ergebnisse vorab, bevor Sie sie den Nutzern anzeigen
Auf GitHub ansehen
---
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

Alle Dateien

0 Dateien

azure-ai-contentsafety-py installieren

Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.

ZIP herunterladen

Klonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.

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

Kopieren Kopieren
Schnelle Einrichtung: Kopiere den Skill-Ordner nach .claude/skills/ Claude erkennt den Skill automatisch und nutzt ihn.
Repository microsoft/skills

Ähnliche Skills

gmgn-portfolio
Zeit aktualisiert 1. Juli 2026
zeroize-audit
Zeit aktualisiert 1. Juli 2026
device-integrity
Zeit aktualisiert 29. Juni 2026
flutter-use-http-package
Zeit aktualisiert 30. Juni 2026
OR