Generated banner for Azure AI Contentsafety Java
Generated logo for Azure AI Contentsafety Java

Azure AI Contentsafety Java

MicrosoftOfficialCreated by Microsoft

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

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.
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a comprehensive guide for using the Azure AI Content Safety SDK for Java. It covers client initialization using API keys or Microsoft Entra ID, methods for analyzing text and images for harmful content, and managing custom blocklists. The documentation includes best practices for performance, error handling, and severity threshold configuration to help developers build robust moderation pipelines.

What it does

  • Analyzes text for hate, violence, sexual content, and self-harm.
  • Detects harmful content in images via local files or blob URLs.
  • Manages custom text blocklists to filter specific terms.
  • Configures severity levels for granular content filtering.
  • Supports authentication via API keys or DefaultAzureCredential.
  • Provides patterns for batch processing and error handling.

When to use it

  • When building applications that require automated content moderation.
  • When you need to filter user-generated text or images for safety.
  • When implementing custom keyword or phrase blocking.
  • When developing Java-based services on Azure that require AI-powered safety checks.

Advantages

  • Native Java support for Azure AI services.
  • Flexible authentication options including managed identities.
  • Configurable severity thresholds for different moderation needs.
  • Support for both text and image analysis in one SDK.

Usage examples

“How do I analyze a string of text for hate speech using the Azure Content Safety Java SDK?”
The agent provides a code snippet demonstrating the use of AnalyzeTextOptions and the analyzeText method to retrieve severity scores for specific harm categories.
“Show me how to add a custom word to a blocklist in Java.”
The agent provides a code example using the BlocklistClient to create or update a blocklist and add items using TextBlocklistItem objects.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/microsoft/azure-ai-contentsafety-java/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip azure-ai-contentsafety-java.zip -d .agents/skills

Documentation by Microsoft

Azure AI Content Safety SDK for Java

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

Installation

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

Client Creation

With API Key
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
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
CategoryDescription
HateDiscriminatory language based on identity groups
SexualSexual content, relationships, acts
ViolencePhysical harm, weapons, injury
Self-harmSelf-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
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
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
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
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
ContentSafetyImageData imageData = new ContentSafetyImageData()
    .setBlobUrl("https://example.com/image.jpg");

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

Blocklist Management

Create or Update Blocklist
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
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
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();

for (TextBlocklist blocklist : blocklists) {
    System.out.printf("Blocklist: %s, Description: %s%n",
        blocklist.getName(),
        blocklist.getDescription());
}
Get Blocklist
TextBlocklist blocklist = blocklistClient.getTextBlocklist("my-blocklist");
System.out.println("Name: " + blocklist.getName());
List Block Items
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
List<String> itemIds = Arrays.asList("item-id-1", "item-id-2");

blocklistClient.removeBlocklistItems(
    "my-blocklist",
    new RemoveTextBlocklistItemsOptions(itemIds));
Delete Blocklist
blocklistClient.deleteTextBlocklist("my-blocklist");

Error Handling

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

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"

Files

references/examples.md

Azure AI Content Safety SDK for Java - Examples

Comprehensive code examples for the Azure AI Content Safety SDK for Java.

Table of Contents

  • Maven Dependency

  • Client Creation

  • Analyzing Text Content

  • Analyzing Image Content

  • Handling Analysis Results

  • Blocklist Management

  • Async Client Patterns

  • Error Handling

Maven Dependency

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-contentsafety</artifactId>
    <version>1.0.16</version>
</dependency>

<!-- For DefaultAzureCredential authentication -->
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.14.2</version>
</dependency>

Client Creation

With API Key Credential
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;
import com.azure.core.util.Configuration;

String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");

// Content Safety client
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();

// Blocklist client
BlocklistClient blocklistClient = new BlocklistClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildClient();
With DefaultAzureCredential (Microsoft Entra ID)
import com.azure.identity.DefaultAzureCredentialBuilder;

// Set environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint(endpoint)
    .buildClient();

BlocklistClient blocklistClient = new BlocklistClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint(endpoint)
    .buildClient();

Analyzing Text Content

import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.models.AnalyzeTextOptions;
import com.azure.ai.contentsafety.models.AnalyzeTextResult;
import com.azure.ai.contentsafety.models.TextCategoriesAnalysis;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.Configuration;

public class AnalyzeText {
    public static void main(String[] args) {
        String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
        String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");

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

        // Analyze text
        AnalyzeTextResult response = contentSafetyClient.analyzeText(
            new AnalyzeTextOptions("This is text example")
        );

        // Process results - iterate through harm categories
        for (TextCategoriesAnalysis result : response.getCategoriesAnalysis()) {
            System.out.println(result.getCategory() + " severity: " + result.getSeverity());
        }
    }
}

Analyzing Image Content

import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.models.AnalyzeImageOptions;
import com.azure.ai.contentsafety.models.AnalyzeImageResult;
import com.azure.ai.contentsafety.models.ContentSafetyImageData;
import com.azure.ai.contentsafety.models.ImageCategoriesAnalysis;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Configuration;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class AnalyzeImage {
    public static void main(String[] args) throws IOException {
        String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
        String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");

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

        // Load image from file
        ContentSafetyImageData image = new ContentSafetyImageData();
        String cwd = System.getProperty("user.dir");
        String source = "/src/samples/resources/image.png";
        image.setContent(BinaryData.fromBytes(Files.readAllBytes(Paths.get(cwd, source))));

        // Analyze image
        AnalyzeImageResult response = contentSafetyClient.analyzeImage(
            new AnalyzeImageOptions(image)
        );

        // Process results - iterate through harm categories
        for (ImageCategoriesAnalysis result : response.getCategoriesAnalysis()) {
            System.out.println(result.getCategory() + " severity: " + result.getSeverity());
        }
    }
}

Handling Analysis Results

Severity Levels and Content Moderation
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.models.*;
import com.azure.core.credential.KeyCredential;
import com.azure.core.util.Configuration;

public class HandleAnalysisResults {
    
    // Severity thresholds for content moderation decisions
    private static final int SEVERITY_SAFE = 0;
    private static final int SEVERITY_LOW = 2;
    private static final int SEVERITY_MEDIUM = 4;
    private static final int SEVERITY_HIGH = 6;
    
    public static void main(String[] args) {
        String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
        String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");

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

        String textToAnalyze = "Sample text to analyze for harmful content";
        
        AnalyzeTextResult result = client.analyzeText(new AnalyzeTextOptions(textToAnalyze));
        
        // Process each harm category
        for (TextCategoriesAnalysis categoryResult : result.getCategoriesAnalysis()) {
            TextCategory category = categoryResult.getCategory();
            Integer severity = categoryResult.getSeverity();
            
            System.out.println("Category: " + category);
            System.out.println("Severity: " + severity);
            
            // Make moderation decisions based on severity
            // Categories: HATE, SEXUAL, VIOLENCE, SELF_HARM
            String action = determineModerationAction(severity);
            System.out.println("Recommended Action: " + action);
            System.out.println("---");
        }
        
        // Check if content should be blocked
        boolean shouldBlock = shouldBlockContent(result);
        System.out.println("Block Content: " + shouldBlock);
    }
    
    private static String determineModerationAction(Integer severity) {
        if (severity == null) {
            return "UNKNOWN";
        }
        
        if (severity <= SEVERITY_SAFE) {
            return "ALLOW - Content is safe";
        } else if (severity <= SEVERITY_LOW) {
            return "REVIEW - Low severity, may need human review";
        } else if (severity <= SEVERITY_MEDIUM) {
            return "FLAG - Medium severity, requires attention";
        } else {
            return "BLOCK - High severity, should be blocked";
        }
    }
    
    private static boolean shouldBlockContent(AnalyzeTextResult result) {
        for (TextCategoriesAnalysis categoryResult : result.getCategoriesAnalysis()) {
            Integer severity = categoryResult.getSeverity();
            if (severity != null && severity >= SEVERITY_MEDIUM) {
                return true;
            }
        }
        return false;
    }
}

Blocklist Management

Create or Update Blocklist
import com.azure.ai.contentsafety.BlocklistClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;
import com.azure.core.credential.KeyCredential;
import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.core.util.Configuration;

import java.util.HashMap;
import java.util.Map;

String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");

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

// Create or update blocklist
String blocklistName = "TestBlocklist";
Map<String, String> description = new HashMap<>();
description.put("description", "Test Blocklist");
BinaryData resource = BinaryData.fromObject(description);
RequestOptions requestOptions = new RequestOptions();

Response<BinaryData> response = blocklistClient
    .createOrUpdateTextBlocklistWithResponse(blocklistName, resource, requestOptions);

if (response.getStatusCode() == 201) {
    System.out.println("Blocklist " + blocklistName + " created.");
} else if (response.getStatusCode() == 200) {
    System.out.println("Blocklist " + blocklistName + " updated.");
}
Add Blocklist Items
import com.azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions;
import com.azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult;
import com.azure.ai.contentsafety.models.TextBlocklistItem;

import java.util.Arrays;
import java.util.List;

String blockItemText1 = "k*ll";
String blockItemText2 = "h*te";
List<TextBlocklistItem> blockItems = Arrays.asList(
    new TextBlocklistItem(blockItemText1).setDescription("Kill word"),
    new TextBlocklistItem(blockItemText2).setDescription("Hate word")
);

AddOrUpdateTextBlocklistItemsResult addedBlockItems = blocklistClient.addOrUpdateBlocklistItems(
    blocklistName,
    new AddOrUpdateTextBlocklistItemsOptions(blockItems)
);

if (addedBlockItems != null && addedBlockItems.getBlocklistItems() != null) {
    System.out.println("BlockItems added:");
    for (TextBlocklistItem addedBlockItem : addedBlockItems.getBlocklistItems()) {
        System.out.println("BlockItemId: " + addedBlockItem.getBlocklistItemId() 
            + ", Text: " + addedBlockItem.getText() 
            + ", Description: " + addedBlockItem.getDescription());
    }
}
Analyze Text with Blocklist
import com.azure.ai.contentsafety.ContentSafetyClient;
import com.azure.ai.contentsafety.models.AnalyzeTextOptions;
import com.azure.ai.contentsafety.models.AnalyzeTextResult;
import com.azure.ai.contentsafety.models.TextBlocklistMatch;

import java.util.Arrays;

// Note: After editing blocklist, wait ~5 minutes for changes to take effect
AnalyzeTextOptions request = new AnalyzeTextOptions("I h*te you and I want to k*ll you");
request.setBlocklistNames(Arrays.asList(blocklistName));
request.setHaltOnBlocklistHit(true);  // Stop analysis on first blocklist match

AnalyzeTextResult analyzeTextResult = contentSafetyClient.analyzeText(request);

// Check for blocklist matches
if (analyzeTextResult.getBlocklistsMatch() != null) {
    System.out.println("Blocklist matches found:");
    for (TextBlocklistMatch match : analyzeTextResult.getBlocklistsMatch()) {
        System.out.println("BlocklistName: " + match.getBlocklistName());
        System.out.println("BlocklistItemId: " + match.getBlocklistItemId());
        System.out.println("BlocklistItemText: " + match.getBlocklistItemText());
    }
}
Remove Blocklist Items
import com.azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions;

import java.util.Arrays;
import java.util.List;

List<String> blocklistItemIdsToRemove = Arrays.asList(
    "blocklistItemId1",
    "blocklistItemId2"
);

blocklistClient.removeBlocklistItems(
    blocklistName,
    new RemoveTextBlocklistItemsOptions(blocklistItemIdsToRemove)
);

System.out.println("Blocklist items removed.");
List Blocklists and Items
import com.azure.ai.contentsafety.models.TextBlocklist;
import com.azure.ai.contentsafety.models.TextBlocklistItem;
import com.azure.core.http.rest.PagedIterable;

// List all blocklists
PagedIterable<TextBlocklist> blocklists = blocklistClient.listTextBlocklists();
for (TextBlocklist blocklist : blocklists) {
    System.out.println("Blocklist: " + blocklist.getName());
    System.out.println("Description: " + blocklist.getDescription());
}

// List items in a blocklist
PagedIterable<TextBlocklistItem> items = blocklistClient.listTextBlocklistItems(blocklistName);
for (TextBlocklistItem item : items) {
    System.out.println("Item ID: " + item.getBlocklistItemId());
    System.out.println("Text: " + item.getText());
    System.out.println("Description: " + item.getDescription());
}
Delete Blocklist
blocklistClient.deleteTextBlocklist(blocklistName);
System.out.println("Blocklist " + blocklistName + " deleted.");

Async Client Patterns

Async Content Safety Client
import com.azure.ai.contentsafety.ContentSafetyAsyncClient;
import com.azure.ai.contentsafety.ContentSafetyClientBuilder;
import com.azure.ai.contentsafety.models.AnalyzeTextOptions;
import com.azure.core.credential.KeyCredential;

ContentSafetyAsyncClient asyncClient = new ContentSafetyClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildAsyncClient();

// Async text analysis
asyncClient.analyzeText(new AnalyzeTextOptions("Text to analyze"))
    .subscribe(
        result -> {
            result.getCategoriesAnalysis().forEach(category -> {
                System.out.println(category.getCategory() + ": " + category.getSeverity());
            });
        },
        error -> System.err.println("Error: " + error.getMessage()),
        () -> System.out.println("Analysis completed")
    );
Async Blocklist Client
import com.azure.ai.contentsafety.BlocklistAsyncClient;
import com.azure.ai.contentsafety.BlocklistClientBuilder;

BlocklistAsyncClient asyncBlocklistClient = new BlocklistClientBuilder()
    .credential(new KeyCredential(key))
    .endpoint(endpoint)
    .buildAsyncClient();

// Async list blocklists
asyncBlocklistClient.listTextBlocklists()
    .subscribe(
        blocklist -> System.out.println("Found blocklist: " + blocklist.getName()),
        error -> System.err.println("Error: " + error.getMessage())
    );

Error Handling

import com.azure.core.exception.HttpResponseException;
import com.azure.ai.contentsafety.models.AnalyzeTextOptions;

public class ContentSafetyErrorHandling {
    public static void analyzeWithErrorHandling(ContentSafetyClient client, String text) {
        try {
            var result = client.analyzeText(new AnalyzeTextOptions(text));
            // Process result
            result.getCategoriesAnalysis().forEach(category -> {
                System.out.println(category.getCategory() + ": " + category.getSeverity());
            });
        } catch (HttpResponseException e) {
            int statusCode = e.getResponse().getStatusCode();
            System.err.println("HTTP Status: " + statusCode);
            System.err.println("Error: " + e.getMessage());
            
            switch (statusCode) {
                case 400:
                    System.err.println("Bad request - check input parameters");
                    break;
                case 401:
                    System.err.println("Unauthorized - check API key");
                    break;
                case 403:
                    System.err.println("Forbidden - check permissions");
                    break;
                case 404:
                    System.err.println("Resource not found");
                    break;
                case 429:
                    System.err.println("Rate limited - slow down requests");
                    break;
                default:
                    if (statusCode >= 500) {
                        System.err.println("Server error - retry later");
                    }
            }
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
    }
}
Async Error Handling
asyncClient.analyzeText(new AnalyzeTextOptions(text))
    .subscribe(
        result -> {
            // Process result
        },
        error -> {
            if (error instanceof HttpResponseException) {
                HttpResponseException httpError = (HttpResponseException) error;
                System.err.println("HTTP error: " + httpError.getResponse().getStatusCode());
            } else {
                System.err.println("Error: " + error.getMessage());
            }
        }
    );

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/skills · .github/plugins/azure-sdk-java/skills/azure-ai-contentsafety-java · commit 0696600
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Microsoft or Microsoft.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-ai-contentsafety-java.zip