옵션
집 Skill 보안 azure-ai-contentsafety-py

azure-ai-contentsafety-py

microsoft/skills microsoft/skills

Python용 Azure AI 콘텐츠 안전성 SDK를 사용하여 텍스트 및 이미지에서 유해한 사용자 생성 콘텐츠와 AI 생성 콘텐츠를 탐지합니다.

...모든 것을 확장하십시오
1
업데이트 된 시간 2026년 9월 14일

Python용 Azure AI 콘텐츠 안전성 SDK

애플리케이션 내에서 유해한 사용자 생성 콘텐츠 및 AI 생성 콘텐츠를 탐지합니다.

설치

pip install azure-ai-contentsafety

환경 변수

CONTENT_SAFETY_ENDPOINT=https://.cognitiveservices.azure.com  # 모든 인증 방식에 필수
AZURE_TOKEN_CREDENTIALS=prod # 프로덕션 환경에서 DefaultAzureCredential을 사용하는 경우에만 필요
CONTENT_SAFETY_KEY= # 아래의 레거시 API 키 인증 경로에만 필요

인증 및 수명 주기

🔑 아래의 모든 코드 예제에는 다음 두 가지 규칙이 적용됩니다:

  1. DefaultAzureCredential을 우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI)과 Azure(관리형 ID, 워크로드 ID) 모두에서 작동합니다. 연결 문자열, 계정/API 키는 사용하지 마십시오. 이러한 방법은 Entra 감사 및 키 순환을 우회합니다.
    • 로컬 개발: DefaultAzureCredential은 그대로 사용할 수 있습니다.
    • 프로덕션: AZURE_TOKEN_CREDENTIALS=prod (또는 AZURE_TOKEN_CREDENTIALS=)를 설정하여 자격 증명 체인을 프로덕션에 안전한 자격 증명로 제한하십시오.
  2. 모든 클라이언트를 컨텍스트 매니저로 감싸서 HTTP 전송, 소켓 및 토큰 캐시가 결정론적으로 해제되도록 하십시오:
    • 동기식: (...) as client:
    • 비동기: (...)을 클라이언트로 사용하는 async DefaultAzureCredential()을 자격 증명으로 사용하는 async: ( azure.identity.aio에서 제공)

코드 예제에서는 이 설정을 생략할 수 있지만, 실제 운영 코드에서는 항상 두 가지 규칙을 모두 준수해야 합니다.

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

# 로컬 개발 환경: DefaultAzureCredential. 프로덕션 환경: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=설정 
credential = DefaultAzureCredential(require_envvar=True)
# 또는 프로덕션 환경에서 특정 자격 증명을 직접 사용:
# 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!"))

레거시: API 키 (기존 키 기반 배포)

새로운 코드에서는 위의 DefaultAzureCredential을 사용해야 합니다. AzureKeyCredential은 아직 Entra ID로 마이그레이션되지 않은 기존 키 기반 배포 환경(예: 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="Hello, world!"))

키를 사용하여 차단 목록을 관리해야 하는 경우에도 BlocklistClient는 동일한 AzureKeyCredential 을 사용할 수 있습니다.

텍스트 분석

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="분석할 텍스트 콘텐츠")
    response = client.analyze_text(request)

    # 각 카테고리 확인
    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}: 심각도 {result.severity}")

이미지 분석

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:
    # 파일에서 불러오기
    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}: 심각도 {result.severity}")

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)

텍스트 차단 목록 관리

차단 목록 생성

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="차단할 사용자 정의 용어"
    )

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

차단 항목 추가

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
)

차단 목록을 사용하여 분석

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"차단됨: {match.blocklist_item_text}")

심각도 수준

텍스트 분석은 기본적으로 4단계(0, 2, 4, 6)의 심각도 등급을 반환합니다. 8단계(0-7)를 사용하려면:

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

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

유해성 범주

범주 설명
증오 정체성(인종, 종교, 성별 등)을 근거로 한 공격
성적 성적 내용, 관계, 신체 구조
폭력 신체적 피해, 무기, 부상
자해 자해, 자살, 섭식 장애

심각도 척도

수준 텍스트 범위 이미지 범위 의미
0 안전 안전 유해한 콘텐츠 없음
2 낮음 낮음 경미한 언급
4 중간 중간 상당한 내용
6 높음 높음 심각한 콘텐츠

클라이언트 유형

클라이언트 목적
콘텐츠 안전성 클라이언트 텍스트 및 이미지 분석
차단 목록 클라이언트 사용자 지정 차단 목록 관리

모범 사례

  1. 동기(sync) 또는 비동기(async) 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로에서 azure.ai.contentsafety 동기 클라이언트와 azure.ai.contentsafety.aio 비동기 클라이언트를 혼용하지 마십시오. 모듈당 하나의 모드를 선택하십시오.
  2. 클라이언트 및 비동기 자격 증명에는 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를 ContentSafetyClient(...) as client: (sync) 또는 ContentSafetyClient(...) as client: (async) 감싸십시오. azure.identity.aio의 비동기 DefaultAzureCredential을 사용하는 경우에도 credential:을 사용하여 비동기 방식으로 처리하여 토큰과 전송 경로가 정리되도록 하십시오.
  3. 도메인별 용어에 대해서는차단 목록을 사용하십시오
  4. 사용 사례에 적합한심각도 임계값을 설정하십시오
  5. 여러 범주를 처리하십시오 — 콘텐츠는 다양한 방식으로 유해할 수 있습니다
  6. 즉시 거부를 위해halt_on_blocklist_hit을 사용하십시오
  7. 감사 및 개선을 위해분석 결과를 기록하십시오
  8. 더 세밀한 제어를 위해8단계 심각도 모드를 고려하십시오
  9. 사용자에게 표시하기 전에AI 출력물을 사전 검토하십시오
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

모든 파일

0개 파일

azure-ai-contentsafety-py 설치

스킬 파일을 다운로드하여 .claude/skills/ 디렉터리에 압축을 풀어주세요.

ZIP 다운로드

저장소를 클론하고 스킬 파일을 프로젝트에 복사하세요.

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

복사 복사
빠른 설정: 스킬 폴더를 .claude/skills/로 복사하세요. Claude가 해당 스킬을 자동으로 감지하여 사용할 것입니다.
저장소 microsoft/skills

관련 스킬

gmgn-portfolio
업데이트 된 시간 2026년 7월 1일
zeroize-audit
업데이트 된 시간 2026년 7월 1일
device-integrity
업데이트 된 시간 2026년 6월 29일
flutter-use-http-package
업데이트 된 시간 2026년 6월 30일
OR