Skip to main content
skill

azure-ai-contentsafety-java — Claude Code skill

A skill that walks the agent through the Azure AI Content Safety SDK for Java: text and image analysis, blocklists, harm detection.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add microsoft/skills --skill azure-ai-contentsafety-java -a claude-code
Open on GitHub

What azure-ai-contentsafety-java does

The skill ships reference code for the com.azure:azure-ai-contentsafety package. It covers building ContentSafetyClient and BlocklistClient, running text analysis with a chosen set of categories, checking images from a file or a URL, and managing blocklists.

Harm falls into four categories: hate, sexual, violence and self-harm. Text severity runs on a 0–7 scale, yet the default response only carries 0, 2, 4 and 6; ask for AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS when you need every level. Images use the trimmed scale.

Both clients expect an endpoint plus credentials. The samples read CONTENT_SAFETY_ENDPOINT and CONTENT_SAFETY_KEY from the environment, and there is a second route through DefaultAzureCredentialBuilder with the AZURE_TOKEN_CREDENTIALS check. For production the README points at a concrete credential such as ManagedIdentityCredentialBuilder. No endpoint, no working client — sort out access to the Azure resource first.

What it helps with

  • score user text against harm categories and severity levels
  • check an uploaded image for disallowed content
  • create a custom blocklist and keep adding terms to it
  • filter messages by blocklist before the main moderation pass
  • build a Content Safety client with a key or a managed identity

Example prompts for the agent

  • Show me how to build a ContentSafetyClient with the key from an environment variable
  • Analyze this text for hate and violence with the full severity scale
  • Add a term to my-blocklist and check a string with setHaltOnBlocklistHit

How to install azure-ai-contentsafety-java

1Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-ai-contentsafety-java -a claude-code

2Manually: put the files in place

~/.claude/skills/azure-ai-contentsafety-java/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/azure-ai-contentsafety-java/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about azure-ai-contentsafety-java

How do I install azure-ai-contentsafety-java in Claude Code?

Run npx skills add microsoft/skills --skill azure-ai-contentsafety-java -a claude-code. The skill lands in ~/.claude/skills/azure-ai-contentsafety-java/SKILL.md.

What does azure-ai-contentsafety-java do?

It gives the agent working examples for Java moderation code: text and image analysis, blocklist handling, and the harm categories the service returns.

What do I need before using the SDK?

An Azure Content Safety endpoint and credentials — either a key passed to KeyCredential or a token from DefaultAzureCredentialBuilder.

Source text

SKILL.md · MIT
---
name: azure-ai-contentsafety-java
description: Build content moderation applications with Azure AI Content Safety SDK for Java. Use when implementing text/image analysis, blocklist management, or harm detection for hate, violence, sexual content, and self-harm.
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: com.azure:azure-ai-contentsafety
---

# Azure AI Content Safety SDK for Java

Build content moderation applications using the Azure AI Content Safety SDK for Java.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-contentsafety</artifactId>
    <version>1.1.0-beta.1</version>
</dependency>
```

## Client Creation

### With API Key

```java
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.BlocklistClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;
import com.azure.core.credential.KeyCredential;

String endpoint = System.getenv("CONTENT_SAFETY_ENDPOINT");
String key = System.getenv("CONTENT_SAFETY_KEY");

ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();

BlocklistClient blocklistClient = new BlocklistClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();
```

### With DefaultAzureCredential

```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

ContentSafetyClient client = new ContentSafetyClientBuilder()
    .credential(credential)
    .endpoint(endpoint)
    .buildClient();
```

## Key Concepts

### Harm Categories
| Category | Description |
|----------|-------------|
| Hate | Discriminatory language based on identity groups |
| Sexual | Sexual content, relationships, acts |
| Violence | Physical harm, weapons, injury |
| Self-harm | Self-injury, suicide-related content |

### Severity Levels
- Text: 0-7 scale (default outputs 0, 2, 4, 6)
- Image: 0, 2, 4, 6 (trimmed scale)

## Core Patterns

### Analyze Text

```java
import com.azure.ai.contentsafety.models.*;

AnalyzeTextResult result = contentSafetyClient.analyzeText(
    new AnalyzeTextOptions("This is text to analyze"));

for (TextCategoriesAnalysis category : result.getCategoriesAnalysis()) {
    System.out.printf("Category: %s, Severity: %d%n",
        category.getCategory(),
        category.getSeverity());
}
```

### Analyze Text with Options

```java
AnalyzeTextOptions options = new AnalyzeTextOptions("Text to analyze")
    .setCategories(Arrays.asList(
        TextCategory.HATE,
        TextCategory.VIOLENCE))
    .setOutputType(AnalyzeTextOutputType.EIGHT_SEVERITY_LEVELS);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);
```

### Analyze Text with Blocklist

```java
AnalyzeTextOptions options = new AnalyzeTextOptions("I h*te you and want to k*ll you")
    .setBlocklistNames(Arrays.asList("my-blocklist"))
    .setHaltOnBlocklistHit(true);

AnalyzeTextResult result = contentSafetyClient.analyzeText(options);

if (result.getBlocklistsMatch() != null) {
    for (TextBlocklistMatch match : result.getBlocklistsMatch()) {
        System.out.printf("Blocklist: %s, Item: %s, Text: %s%n",
            match.getBlocklistName(),
            match.getBlocklistItemId(),
            match.getBlocklistItemText());
    }
}
```

### Analyze Image

```java
import com.azure.ai.contentsafety.models.*;
import com.azure.core.util.BinaryData;
import java.nio.file.Files;
import java.nio.file.Paths;

// From file
byte[] imageBytes = Files.readAllBytes(Paths.get("image.png"));
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setContent(BinaryData.fromBytes(imageBytes));

AnalyzeImageResult result = contentSafetyClient.analyzeImage(
    new AnalyzeImageOptions(imageData));

for (ImageCategoriesAnalysis category : result.getCategoriesAnalysis()) {
    System.out.printf("Category: %s, Severity: %d%n",
        category.getCategory(),
        category.getSeverity());
}
```

### Analyze Image from URL

```java
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setBlobUrl("https://example.com/image.jpg");

AnalyzeImageResult result = contentSafetyClient.analyzeImage(
    new AnalyzeImageOptions(imageData));
```

## Blocklist Management

### Create or Update Blocklist

```java
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import java.util.Map;

Map<String, String> description = Map.of("description", "Custom blocklist");
BinaryData resource = BinaryData.fromObject(description);

Response<BinaryData> response = blocklistClient.createOrUpdateTextBlocklistWithResponse(
    "my-blocklist", resource, new RequestOptions());

if (response.getStatusCode() == 201) {
    System.out.println("Blocklist created");
} else if (response.getStatusCode() == 200) {
    System.out.println("Blocklist updated");
}
```

### Add Block Items

```java
import com.azure.ai.contentsafety.models.*;
import java.util.Arrays;

List<TextBlocklistItem> items = Arrays.asList(
    new TextBlocklistItem("badword1").setDescription("Offensive term"),
    new TextBlocklistItem("badword2").setDescription("Another term")
);

AddOrUpdateTextBlocklistItemsResult result = blocklistClient.addOrUpdateBlocklistItems(
    "my-blocklist",
    new AddOrUpdateTextBlocklistItemsOptions(items));

for (TextBlocklistItem item : result.getBlocklistItems()) {
    System.out.printf("Added: %s (ID: %s)%n",
        item.getText(),
        item.getBlocklistItemId());
}
```

### List Blocklists

```java
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();

for (TextBlocklist blocklist : blocklists) {
    System.out.printf("Blocklist: %s, Description: %s%n",
        blocklist.getName(),
        blocklist.getDescription());
}
```

### Get Blocklist

```java
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("Name: " + blocklist.getName());
```

### List Block Items

```java
PagedIterable<TextBlocklistItem> items = 
    blocklistClient.listTextBlocklistItems("my-blocklist");

for (TextBlocklistItem item : items) {
    System.out.printf("ID: %s, Text: %s%n",
        item.getBlocklistItemId(),
        item.getText());
}
```

### Remove Block Items

```java
List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");

blocklistClient.removeBlocklistItems(
    "my-blocklist",
    new RemoveTextBlocklistItemsOptions(itemIds));
```

### Delete Blocklist

```java
blocklistClient.deleteTextBlocklist("my-blocklist");
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;

try {
    contentSafetyClient.analyzeText(new AnalyzeTextOptions("test"));
} catch (HttpResponseException e) {
    System.out.println("Status: " + e.getResponse().getStatusCode());
    System.out.println("Error: " + e.getMessage());
    // Common codes: InvalidRequestBody, ResourceNotFound, TooManyRequests
}
```

## Environment Variables

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

## Best Practices

1. **Blocklist Delay**: Changes take ~5 minutes to take effect
2. **Category Selection**: Only request needed categories to reduce latency
3. **Severity Thresholds**: Typically block severity >= 4 for strict moderation
4. **Batch Processing**: Process multiple items in parallel for throughput
5. **Caching**: Cache blocklist results where appropriate

## Trigger Phrases

- "content safety Java"
- "content moderation Azure"
- "analyze text safety"
- "image moderation Java"
- "blocklist management"
- "hate speech detection"
- "harmful content filter"

© Microsoft · MIT · microsoft/skills

Similar skills

All skills for Cloud: AWS, Azure, GCP →

From the same set99

The whole set →
azure-cosmos-java A skill that tells your agent how to use the Azure Cosmos DB Java SDK: clients, queries, partition keys and error handling. ★ 3,149repo stars azure-communication-common-java A skill covering shared Azure Communication Services utilities for Java: tokens, user identifiers, Entra ID auth. ★ 3,149repo stars azure-communication-callautomation-java Java SDK skill for Azure Communication Services Call Automation: outbound calls, IVR, recording, DTMF and speech recognition. ★ 3,149repo stars azure-ai-vision-imageanalysis-java A skill for the Azure AI Vision SDK for Java. It feeds the agent ready code for captions, OCR, object detection, tagging and smart cropping. ★ 3,149repo stars azure-resource-manager-redis-dotnet A skill for provisioning and managing Azure Cache for Redis through Azure Resource Manager in .NET: caches, firewall rules, access keys, geo-replication. ★ 3,149repo stars azure-mgmt-weightsandbiases-dotnet A skill that walks the agent through deploying and managing Weights & Biases instances in Azure, including Entra ID single sign-on. ★ 3,149repo stars azure-mgmt-apimanagement-dotnet A skill for management plane operations on Azure API Management in .NET: creating services, APIs, products, subscriptions and policies via Azure Resource Manager. Use it when APIM infrastructure should be provisioned from code. ★ 3,149repo stars azure-local-multi-rack A skill for planning and running multi-rack Azure Local deployments: aggregation rack, compute racks, Network Fabric Controller, SAN storage. ★ 3,149repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor