Attenzione
I dati di esempio in questa guida possono includere contenuto offensivo. La discrezione dell'utente è consigliata.
I classificatori di intelligenza artificiale predefiniti sono sufficienti per la maggior parte delle esigenze di moderazione dei contenuti. Può tuttavia essere necessario filtrare termini specifici per il proprio caso d’uso. Gli elenchi di blocchi consentono di aggiungere termini personalizzati ai classificatori di intelligenza artificiale. È possibile usare gli elenchi di blocchi per visualizzare termini o frasi specifici che si desidera contrassegnare nel contenuto.
Prerequisiti
- Una sottoscrizione di Azure: creare un account gratuitamente
- Dopo aver creato la sottoscrizione di Azure, Creare una risorsa di Sicurezza dei contenuti nel portale di Azure per ottenere la chiave e l'endpoint. Immettere un nome univoco per la risorsa, selezionare la sottoscrizione, quindi selezionare un gruppo di risorse, un'area supportata (vedere Disponibilità di aree) e un piano tariffario supportato. Selezionare Crea.
- La distribuzione della risorsa richiede alcuni minuti. Al termine, selezionare Vai alla risorsa. Nel riquadro a sinistra, in Gestione risorse selezionare Chiave di sottoscrizione ed endpoint. L'endpoint e una delle chiavi vengono usati per chiamare le API.
- Una delle seguenti installazioni:
-
cURL per le chiamate API REST.
-
Python 3.x installato
- L'installazione di Python deve includere pip. È possibile verificare se pip è installato eseguendo
pip --version
nella riga di comando. Ottenere pip installando la versione più recente di Python.
- Se si usa Python, è necessario installare la libreria client di Sicurezza dei contenuti di Azure AI per Python. Eseguire il comando
pip install azure-ai-contentsafety
nella directory del progetto
-
Runtime .NET installato.
-
.NET Core SDK installato.
- Se si usa .NET, è necessario installare la libreria client di Sicurezza dei contenuti di Azure AI per .NET. Eseguire il comando
dotnet add package Azure.AI.ContentSafety --prerelease
nella directory del progetto
Creare variabili di ambiente
In questo esempio, sarà possibile scrivere le credenziali nelle variabili di ambiente nel computer locale che esegue l'applicazione.
Per impostare la variabile di ambiente per la chiave e l'endpoint, aprire una finestra della console e seguire le istruzioni del sistema operativo e dell'ambiente di sviluppo.
- Per impostare la
CONTENT_SAFETY_KEY
variabile di ambiente, sostituire YOUR_CONTENT_SAFETY_KEY
con una delle chiavi della risorsa.
- Per impostare la
CONTENT_SAFETY_ENDPOINT
variabile di ambiente, sostituire YOUR_CONTENT_SAFETY_ENDPOINT
con l'endpoint della risorsa.
Importante
Usare le chiavi API con cautela. Non includere la chiave API direttamente nel codice e non esporla mai pubblicamente. Se si usa una chiave API, archiviarla in modo sicuro in Azure Key Vault. Per altre informazioni sull'uso sicuro delle chiavi API nelle app, vedere Chiavi API con Azure Key Vault.
Per altre informazioni sulla sicurezza dei servizi IA, vedere Autenticare richieste in Servizi di Azure AI.
setx CONTENT_SAFETY_KEY 'YOUR_CONTENT_SAFETY_KEY'
setx CONTENT_SAFETY_ENDPOINT 'YOUR_CONTENT_SAFETY_ENDPOINT'
Dopo aver aggiunto le variabili di ambiente, potrebbe essere necessario riavviare gli eventuali programmi in esecuzione che leggeranno le variabili di ambiente, inclusa la finestra della console.
export CONTENT_SAFETY_KEY='YOUR_CONTENT_SAFETY_KEY'
export CONTENT_SAFETY_ENDPOINT='YOUR_CONTENT_SAFETY_ENDPOINT'
Dopo avere aggiunto le variabili di ambiente, eseguire source ~/.bashrc
dalla finestra della console per rendere effettive le modifiche.
Analizzare il testo con una blocklist
È possibile creare blocklist da usare con l'API Testo. Per iniziare, seguire questa procedura.
Creare o modificare una blocklist
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell’URL) con un nome personalizzato per l'elenco. Sostituire anche l'ultimo termine dell'URL REST con lo stesso nome. Caratteri consentiti: 0-9, A-Z, a-z, - . _ ~
.
- Facoltativamente, sostituire il valore del campo
"description"
con una descrizione personalizzata.
curl --location --request PATCH '<endpoint>/contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '{
"description": "This is a violence list"
}'
Il codice di risposta deve essere 201
(creazione di un nuovo elenco) o 200
(aggiornamento di un elenco esistente).
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var blocklistDescription = "<description>";
var data = new
{
description = blocklistDescription,
};
var createResponse = blocklistClient.CreateOrUpdateTextBlocklist(blocklistName, RequestContent.Create(data));
if (createResponse.Status == 201)
{
Console.WriteLine("\nBlocklist {0} created.", blocklistName);
}
else if (createResponse.Status == 200)
{
Console.WriteLine("\nBlocklist {0} updated.", blocklistName);
}
- Sostituire
<your_list_name>
con un nome personalizzato per l'elenco. Caratteri consentiti: 0-9, A-Z, a-z, - . _ ~
.
- Facoltativamente, sostituire
<description>
con una descrizione personalizzata.
- Eseguire il codice.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
Map<String, String> description = new HashMap<>();
description.put("description", "<description>");
BinaryData resource = BinaryData.fromObject(description);
RequestOptions requestOptions = new RequestOptions();
Response<BinaryData> response =
blocklistClient.createOrUpdateTextBlocklistWithResponse(blocklistName, resource, requestOptions);
if (response.getStatusCode() == 201) {
System.out.println("\nBlocklist " + blocklistName + " created.");
} else if (response.getStatusCode() == 200) {
System.out.println("\nBlocklist " + blocklistName + " updated.");
}
- Sostituire
<your_list_name>
con un nome personalizzato per l'elenco. Caratteri consentiti: 0-9, A-Z, a-z, - . _ ~
.
- Facoltativamente, sostituire
<description>
con una descrizione personalizzata.
- Eseguire il codice.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import TextBlocklist
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_description = "<description>"
try:
blocklist = client.create_or_update_text_blocklist(
blocklist_name=blocklist_name,
options=TextBlocklist(blocklist_name=blocklist_name, description=blocklist_description),
)
if blocklist:
print("\nBlocklist created or updated: ")
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nCreate or update text blocklist failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con un nome personalizzato per l'elenco. Caratteri consentiti: 0-9, A-Z, a-z, - . _ ~
.
- Sostituire
<description>
con una descrizione personalizzata.
- Eseguire lo script.
Creare un nuovo script JavaScript in un editor o un IDE a scelta. Incollare il codice seguente.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "<your_list_name>";
const blocklistDescription = "<description>";
const createOrUpdateTextBlocklistParameters = {
contentType: "application/merge-patch+json",
body: {
description: blocklistDescription,
},
};
const result = await client
.path("/text/blocklists/{blocklistName}", blocklistName)
.patch(createOrUpdateTextBlocklistParameters);
if (isUnexpected(result)) {
throw result;
}
console.log(
"Blocklist created or updated. Name: ",
result.body.blocklistName,
", Description: ",
result.body.description
);
}
(async () => {
await createOrUpdateTextBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con un nome personalizzato per l'elenco. Caratteri consentiti: 0-9, A-Z, a-z, - . _ ~
.
- Facoltativamente, sostituire
<description>
con una descrizione personalizzata.
- Eseguire lo script.
Aggiungere blocklistItem all'elenco
Nota
È presente un limite massimo di 10.000 termini in totale per tutti gli elenchi. È possibile aggiungere al massimo 100 blocklistItem in una richiesta.
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL) con il nome usato nel passaggio di creazione dell'elenco.
- Facoltativamente, sostituire il valore del campo
"description"
con una descrizione personalizzata.
- Sostituire il valore del campo
"text"
con l'elemento che si desidera aggiungere alla blocklist. La lunghezza massima di un blocklistItem è di 128 caratteri.
curl --location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:addOrUpdateBlocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '{"blocklistItems": [{
"description": "string",
"text": "bleed"
}]}'
Suggerimento
È possibile aggiungere più blocklistItem in una chiamata API. Impostare il corpo della richiesta su un array JSON di gruppi di dati:
{
"blocklistItems": [
{
"description": "string",
"text": "bleed"
},
{
"description": "string",
"text": "blood"
}
]
}
Il codice di risposta deve essere 200
.
{
"blocklistItems:"[
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed"
}
]
}
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
string blocklistItemText1 = "<block_item_text_1>";
string blocklistItemText2 = "<block_item_text_2>";
var blocklistItems = new TextBlocklistItem[] { new TextBlocklistItem(blocklistItemText1), new TextBlocklistItem(blocklistItemText2) };
var addedBlocklistItems = blocklistClient.AddOrUpdateBlocklistItems(blocklistName, new AddOrUpdateTextBlocklistItemsOptions(blocklistItems));
if (addedBlocklistItems != null && addedBlocklistItems.Value != null)
{
Console.WriteLine("\nBlocklistItems added:");
foreach (var addedBlocklistItem in addedBlocklistItems.Value.BlocklistItems)
{
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", addedBlocklistItem.BlocklistItemId, addedBlocklistItem.Text, addedBlocklistItem.Description);
}
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire i valori dei campi
blocklistItemText1
e blocklistItemText2
con gli elementi da aggiungere all'elenco di blocchi. La lunghezza massima di un elemento block-level è di 128 caratteri.
- Facoltativamente, aggiungere altre stringhe di elementi block-level al parametro
blockItems
.
- Eseguire il codice.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
String blockItemText1 = "<block_item_text_1>";
String blockItemText2 = "<block_item_text_2>";
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("\nBlockItems added:");
for (TextBlocklistItem addedBlockItem : addedBlockItems.getBlocklistItems()) {
System.out.println("BlockItemId: " + addedBlockItem.getBlocklistItemId() + ", Text: " + addedBlockItem.getText() + ", Description: " + addedBlockItem.getDescription());
}
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire i valori dei campi
blockItemText1
e blockItemText2
con gli elementi da aggiungere all'elenco di blocchi. La lunghezza massima di un elemento block-level è di 128 caratteri.
- Facoltativamente, aggiungere altre stringhe di elementi block-level al parametro
blockItems
.
- Eseguire il codice.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import (
AddOrUpdateTextBlocklistItemsOptions, TextBlocklistItem
)
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text_1>"
blocklist_item_text_2 = "<block_item_text_2>"
blocklist_items = [TextBlocklistItem(text=blocklist_item_text_1), TextBlocklistItem(text=blocklist_item_text_2)]
try:
result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name, options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=blocklist_items))
for blocklist_item in result.blocklist_items:
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nAdd blocklistItems failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire i valori dei campi
blocklist_item_text_1
e blocklist_item_text_2
con gli elementi da aggiungere all'elenco di blocchi. La lunghezza massima di un elemento block-level è di 128 caratteri.
- Facoltativamente, aggiungere altre stringhe di elementi block-level al parametro
block_items
.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function addBlocklistItems() {
const blocklistName = "<your_list_name>";
const blocklistItemText1 = "<block_item_text_1>";
const blocklistItemText2 = "<block_item_text_2>";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test blocklist item 1",
text: blocklistItemText1,
},
{
description: "Test blocklist item 2",
text: blocklistItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Blocklist items added: ");
if (result.body.blocklistItems) {
for (const blocklistItem of result.body.blocklistItems) {
console.log(
"BlocklistItemId: ",
blocklistItem.blocklistItemId,
", Text: ",
blocklistItem.text,
", Description: ",
blocklistItem.description
);
}
}
}
(async () => {
await addBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire i valori dei campi
block_item_text_1
e block_item_text_2
con gli elementi da aggiungere all'elenco di blocchi. La lunghezza massima di un elemento block-level è di 128 caratteri.
- Facoltativamente, aggiungere altre stringhe di elementi block-level al parametro
blocklistItems
.
- Eseguire lo script.
Nota
Ci sarà un certo ritardo dopo l'aggiunta o la modifica di un elemento block-level prima che abbia effetto sull'analisi del testo, in genere non più di cinque minuti.
Analizzare il testo con una blocklist
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco. Il campo "blocklistNames"
può contenere un array di diversi ID elenco.
- Facoltativamente, modificare il valore di
"breakByBlocklists"
.
true
indica che una volta trovata una corrispondenza con una blocklist, l'analisi restituirà immediatamente senza output del modello.
false
causerà la prosecuzione dell'analisi del modello nelle categorie predefinite.
- Facoltativamente, modificare il valore del campo
"text"
in qualsiasi testo da analizzare.
curl --location --request POST '<endpoint>/contentsafety/text:analyze?api-version=2024-09-01&' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": "I want to beat you till you bleed",
"categories": [
"Hate",
"Sexual",
"SelfHarm",
"Violence"
],
"blocklistNames":["<your_list_name>"],
"haltOnBlocklistHit": false,
"outputType": "FourSeverityLevels"
}'
La risposta JSON conterrà un valore "blocklistMatchResults"
che indica le corrispondenze con la blocklist. Segnala la posizione nella stringa di testo in cui è stata trovata la corrispondenza.
{
"blocklistsMatch": [
{
"blocklistName": "string",
"blocklistItemId": "string",
"blocklistItemText": "bleed"
}
],
"categoriesAnalysis": [
{
"category": "Hate",
"severity": 0
}
]
}
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
ContentSafetyClient client = new ContentSafetyClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
// After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing with blocklist after editing.
var request = new AnalyzeTextOptions("<your_input_text>");
request.BlocklistNames.Add(blocklistName);
request.HaltOnBlocklistHit = true;
Response<AnalyzeTextResult> response;
try
{
response = client.AnalyzeText(request);
}
catch (RequestFailedException ex)
{
Console.WriteLine("Analyze text failed.\nStatus code: {0}, Error code: {1}, Error message: {2}", ex.Status, ex.ErrorCode, ex.Message);
throw;
}
if (response.Value.BlocklistsMatch != null)
{
Console.WriteLine("\nBlocklist match result:");
foreach (var matchResult in response.Value.BlocklistsMatch)
{
Console.WriteLine("BlocklistName: {0}, BlocklistItemId: {1}, BlocklistText: {2}, ", matchResult.BlocklistName, matchResult.BlocklistItemId, matchResult.BlocklistItemText);
}
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire la il testo di input
request
con il testo che si desidera analizzare.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
AnalyzeTextOptions request = new AnalyzeTextOptions("<sample_text>");
request.setBlocklistNames(Arrays.asList(blocklistName));
request.setHaltOnBlocklistHit(true);
AnalyzeTextResult analyzeTextResult;
try {
analyzeTextResult = contentSafetyClient.analyzeText(request);
} catch (HttpResponseException ex) {
System.out.println("Analyze text failed.\nStatus code: " + ex.getResponse().getStatusCode() + ", Error message: " + ex.getMessage());
throw ex;
}
if (analyzeTextResult.getBlocklistsMatch() != null) {
System.out.println("\nBlocklist match result:");
for (TextBlocklistMatch matchResult : analyzeTextResult.getBlocklistsMatch()) {
System.out.println("BlocklistName: " + matchResult.getBlocklistName() + ", BlockItemId: " + matchResult.getBlocklistItemId() + ", BlockItemText: " + matchResult.getBlocklistItemText());
}
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire la il testo di input
request
con il testo che si desidera analizzare.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import AnalyzeTextOptions
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Content Safety client
client = ContentSafetyClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
input_text = "<your_input_text>"
try:
# After you edit your blocklist, it usually takes effect in 5 minutes, please wait some time before analyzing
# with blocklist after editing.
analysis_result = client.analyze_text(
AnalyzeTextOptions(text=input_text, blocklist_names=[blocklist_name], halt_on_blocklist_hit=False)
)
if analysis_result and analysis_result.blocklists_match:
print("\nBlocklist match results: ")
for match_result in analysis_result.blocklists_match:
print(
f"BlocklistName: {match_result.blocklist_name}, BlocklistItemId: {match_result.blocklist_item_id}, "
f"BlocklistItemText: {match_result.blocklist_item_text}"
)
except HttpResponseError as e:
print("\nAnalyze text failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire la variabile
input_text
con il testo che si desidera analizzare.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function analyzeTextWithBlocklists() {
const blocklistName = "<your_list_name>";
const inputText = "<your_input_text>";
const analyzeTextParameters = {
body: {
text: inputText,
blocklistNames: [blocklistName],
haltOnBlocklistHit: false,
},
};
const result = await client.path("/text:analyze").post(analyzeTextParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Blocklist match results: ");
if (result.body.blocklistsMatch) {
for (const blocklistMatchResult of result.body.blocklistsMatch) {
console.log(
"BlocklistName: ",
blocklistMatchResult.blocklistName,
", BlocklistItemId: ",
blocklistMatchResult.blocklistItemId,
", BlocklistItemText: ",
blocklistMatchResult.blocklistItemText
);
}
}
}
(async () => {
await analyzeTextWithBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire la variabile
inputText
con il testo che si desidera analizzare.
- Eseguire lo script.
Altre operazioni di blocklist
Questa sezione contiene altre operazioni che consentono di gestire e usare la funzionalità blocklist.
Elencare tutti gli elementi blocklist in un elenco
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
curl --location --request GET '<endpoint>/contentsafety/text/blocklists/<your_list_name>/blocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
Il codice di stato dovrebbe essere 200
e il corpo della risposta dovrebbe essere simile al seguente:
{
"values": [
{
"blocklistItemId": "string",
"description": "string",
"text": "bleed",
}
]
}
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var allBlocklistitems = blocklistClient.GetTextBlocklistItems(blocklistName);
Console.WriteLine("\nList BlocklistItems:");
foreach (var blocklistItem in allBlocklistitems)
{
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", blocklistItem.BlocklistItemId, blocklistItem.Text, blocklistItem.Description);
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
PagedIterable<TextBlocklistItem> allBlockitems = blocklistClient.listTextBlocklistItems(blocklistName);
System.out.println("\nList BlockItems:");
for (TextBlocklistItem blocklistItem : allBlockitems) {
System.out.println("BlockItemId: " + blocklistItem.getBlocklistItemId() + ", Text: " + blocklistItem.getText() + ", Description: " + blocklistItem.getDescription());
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
blocklist_items = client.list_text_blocklist_items(blocklist_name=blocklist_name)
if blocklist_items:
print("\nList blocklist items: ")
for blocklist_item in blocklist_items:
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, "
f"Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nList blocklist items failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listBlocklistItems() {
const blocklistName = "<your_list_name>";
const result = await client
.path("/text/blocklists/{blocklistName}/blocklistItems", blocklistName)
.get();
if (isUnexpected(result)) {
throw result;
}
console.log("List blocklist items: ");
if (result.body.value) {
for (const blocklistItem of result.body.value) {
console.log(
"BlocklistItemId: ",
blocklistItem.blocklistItemId,
", Text: ",
blocklistItem.text,
", Description: ",
blocklistItem.description
);
}
}
}
(async () => {
await listBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Elencare tutti gli elenchi di blocchi
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
curl --location --request GET '<endpoint>/contentsafety/text/blocklists?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
Il codice di stato dovrebbe essere 200
. La risposta JSON è simile alla seguente:
"value": [
{
"blocklistName": "string",
"description": "string"
}
]
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklists = blocklistClient.GetTextBlocklists();
Console.WriteLine("\nList blocklists:");
foreach (var blocklist in blocklists)
{
Console.WriteLine("BlocklistName: {0}, Description: {1}", blocklist.Name, blocklist.Description);
}
Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
PagedIterable<TextBlocklist> allTextBlocklists = blocklistClient.listTextBlocklists();
System.out.println("\nList Blocklist:");
for (TextBlocklist blocklist : allTextBlocklists) {
System.out.println("Blocklist: " + blocklist.getName() + ", Description: " + blocklist.getDescription());
}
Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
try:
blocklists = client.list_text_blocklists()
if blocklists:
print("\nList blocklists: ")
for blocklist in blocklists:
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nList text blocklists failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listTextBlocklists() {
const result = await client.path("/text/blocklists").get();
if (isUnexpected(result)) {
throw result;
}
console.log("List blocklists: ");
if (result.body.value) {
for (const blocklist of result.body.value) {
console.log(
"BlocklistName: ",
blocklist.blocklistName,
", Description: ",
blocklist.description
);
}
}
}
(async () => {
await listTextBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
Eseguire lo script.
Ottenere un elenco di blocchi per blocklistName
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
cURL --location '<endpoint>contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
Il codice di stato dovrebbe essere 200
. La risposta JSON è simile alla seguente:
{
"blocklistName": "string",
"description": "string"
}
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var getBlocklist = blocklistClient.GetTextBlocklist(blocklistName);
if (getBlocklist != null && getBlocklist.Value != null)
{
Console.WriteLine("\nGet blocklist:");
Console.WriteLine("BlocklistName: {0}, Description: {1}", getBlocklist.Value.Name, getBlocklist.Value.Description);
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
TextBlocklist getBlocklist = blocklistClient.getTextBlocklist(blocklistName);
if (getBlocklist != null) {
System.out.println("\nGet blocklist:");
System.out.println("BlocklistName: " + getBlocklist.getName() + ", Description: " + getBlocklist.getDescription());
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
blocklist = client.get_text_blocklist(blocklist_name=blocklist_name)
if blocklist:
print("\nGet blocklist: ")
print(f"Name: {blocklist.blocklist_name}, Description: {blocklist.description}")
except HttpResponseError as e:
print("\nGet text blocklist failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getTextBlocklist() {
const blocklistName = "<your_list_name>";
const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).get();
if (isUnexpected(result)) {
throw result;
}
console.log("Get blocklist: ");
console.log("Name: ", result.body.blocklistName, ", Description: ", result.body.description);
}
(async () => {
await getTextBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Ottenere un blocklistItem per blocklistName e blocklistItemId
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_item_id>
con il valore ID per il blocklistitem. Si tratta del valore del campo "blocklistItemId"
dalle chiamate API Aggiungi blocklistItem o Ottieni tutti i blocklistItem.
cURL --location '<endpoint>contentsafety/text/blocklists/<your_list_name>/blocklistItems/<your_item_id>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--data ''
Il codice di stato dovrebbe essere 200
. La risposta JSON è simile alla seguente:
{
"blocklistItemId": "string",
"description": "string",
"text": "string"
}
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = Environment.GetEnvironmentVariable("CONTENT_SAFETY_ENDPOINT");
string key = Environment.GetEnvironmentVariable("CONTENT_SAFETY_KEY");
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var getBlocklistItemId = "<your_block_item_id>";
var getBlocklistItem = blocklistClient.GetTextBlocklistItem(blocklistName, getBlocklistItemId);
Console.WriteLine("\nGet BlocklistItem:");
Console.WriteLine("BlocklistItemId: {0}, Text: {1}, Description: {2}", getBlocklistItem.Value.BlocklistItemId, getBlocklistItem.Value.Text, getBlocklistItem.Value.Description);
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_block_item_id>
con l'ID di un elemento aggiunto in precedenza.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
String getBlockItemId = "<your_block_item_id>";
TextBlocklistItem getBlockItem = blocklistClient.getTextBlocklistItem(blocklistName, getBlockItemId);
System.out.println("\nGet BlockItem:");
System.out.println("BlockItemId: " + getBlockItem.getBlocklistItemId() + ", Text: " + getBlockItem.getText() + ", Description: " + getBlockItem.getDescription());
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_block_item_id>
con l'ID di un elemento aggiunto in precedenza.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import TextBlocklistItem, AddOrUpdateTextBlocklistItemsOptions
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text>"
try:
# Add a blocklistItem
add_result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name,
options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=blocklist_item_text_1)]),
)
if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
raise RuntimeError("BlocklistItem not created.")
blocklist_item_id = add_result.blocklist_items[0].blocklist_item_id
# Get this blocklistItem by blocklistItemId
blocklist_item = client.get_text_blocklist_item(blocklist_name=blocklist_name, blocklist_item_id=blocklist_item_id)
print("\nGet blocklistItem: ")
print(
f"BlocklistItemId: {blocklist_item.blocklist_item_id}, Text: {blocklist_item.text}, Description: {blocklist_item.description}"
)
except HttpResponseError as e:
print("\nGet blocklist item failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<block_item_text>
con il testo dell'elemento di blocco.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getBlocklistItem() {
const blocklistName = "<your_list_name>";
const blocklistItemId = "<your_block_item_id>";
// Get this blocklistItem by blocklistItemId
const blocklistItem = await client
.path(
"/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}",
blocklistName,
blocklistItemId
)
.get();
if (isUnexpected(blocklistItem)) {
throw blocklistItem;
}
console.log("Get blocklistitem: ");
console.log(
"BlocklistItemId: ",
blocklistItem.body.blocklistItemId,
", Text: ",
blocklistItem.body.text,
", Description: ",
blocklistItem.body.description
);
}
(async () => {
await getBlocklistItem();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_block_item_id>
con l'ID dell'elemento da ottenere.
- Eseguire lo script.
Rimuovere blocklistItem da un elenco di blocchi.
Nota
Ci sarà un certo ritardo dopo l’eliminazione di un elemento block-level prima che abbia effetto sull'analisi del testo, in genere non più di cinque minuti.
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<item_id>
con il valore ID per il blocklistitem. Si tratta del valore del campo "blocklistItemId"
dalle chiamate API Aggiungi blocklistItem o Ottieni tutti i blocklistItem.
curl --location --request POST '<endpoint>/contentsafety/text/blocklists/<your_list_name>:removeBlocklistItems?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json'
--data-raw '{"blocklistItemIds":[
"<item_id>"
]}'
Suggerimento
È possibile eliminare più blocklistItem in una chiamata API. Impostare il corpo della richiesta su un array di valori blocklistItemId
.
Il codice di risposta deve essere 204
.
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"];
string key = os.environ["CONTENT_SAFETY_KEY"];
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var removeBlocklistItemId = "<your_block_item_id>";
var removeBlocklistItemIds = new List<string> { removeBlocklistItemId };
var removeResult = blocklistClient.RemoveBlocklistItems(blocklistName, new RemoveTextBlocklistItemsOptions(removeBlocklistItemIds));
if (removeResult != null && removeResult.Status == 204)
{
Console.WriteLine("\nBlocklistItem removed: {0}.", removeBlocklistItemId);
}
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_block_item_id>
con l'ID di un elemento aggiunto in precedenza.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
String removeBlockItemId = "<your_block_item_id>";
List<String> removeBlockItemIds = new ArrayList<>();
removeBlockItemIds.add(removeBlockItemId);
blocklistClient.removeBlocklistItems(blocklistName, new RemoveTextBlocklistItemsOptions(removeBlockItemIds));
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
- Sostituire
<your_block_item_id>
con l'ID di un elemento aggiunto in precedenza.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.ai.contentsafety.models import (
TextBlocklistItem,
AddOrUpdateTextBlocklistItemsOptions,
RemoveTextBlocklistItemsOptions,
)
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
blocklist_item_text_1 = "<block_item_text>"
try:
# Add a blocklistItem
add_result = client.add_or_update_blocklist_items(
blocklist_name=blocklist_name,
options=AddOrUpdateTextBlocklistItemsOptions(blocklist_items=[TextBlocklistItem(text=blocklist_item_text_1)]),
)
if not add_result or not add_result.blocklist_items or len(add_result.blocklist_items) <= 0:
raise RuntimeError("BlocklistItem not created.")
blocklist_item_id = add_result.blocklist_items[0].blocklist_item_id
# Remove this blocklistItem by blocklistItemId
client.remove_blocklist_items(
blocklist_name=blocklist_name, options=RemoveTextBlocklistItemsOptions(blocklist_item_ids=[blocklist_item_id])
)
print(f"\nRemoved blocklistItem: {add_result.blocklist_items[0].blocklist_item_id}")
except HttpResponseError as e:
print("\nRemove blocklist item failed: ")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
Sostituire <block_item_text>
con il testo dell'elemento di blocco.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
// Sample: Remove blocklistItems from a blocklist
async function removeBlocklistItems() {
const blocklistName = "<your_list_name>";
const blocklistItemId = "<your_block_item_id>";
// Remove this blocklistItem by blocklistItemId
const removeBlocklistItemsParameters = {
body: {
blocklistItemIds: [blocklistItemId],
},
};
const removeBlocklistItem = await client
.path("/text/blocklists/{blocklistName}:removeBlocklistItems", blocklistName)
.post(removeBlocklistItemsParameters);
if (isUnexpected(removeBlocklistItem)) {
throw removeBlocklistItem;
}
console.log("Removed blocklistItem: ", blocklistItemText);
}
(async () => {
await removeBlocklistItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
con il nome usato nel passaggio di creazione dell'elenco.
Sostituire <your_block_item_id
con l'ID dell'elemento da rimuovere.
- Eseguire lo script.
Eliminare un elenco e tutto il contenuto
Nota
Ci sarà un certo ritardo dopo l’eliminazione di un elenco prima che abbia effetto sull'analisi del testo, in genere non più di cinque minuti.
Copiare il comando cURL qui di seguito in un editor di testo e apportare le modifiche seguenti:
- Sostituire
<endpoint>
con l'URL dell'endpoint.
- Sostituire
<enter_your_key_here>
con la chiave.
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
curl --location --request DELETE '<endpoint>/contentsafety/text/blocklists/<your_list_name>?api-version=2024-09-01' \
--header 'Ocp-Apim-Subscription-Key: <enter_your_key_here>' \
--header 'Content-Type: application/json' \
Il codice di risposta deve essere 204
.
Creare una nuova app console C# e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
string endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"];
string key = os.environ["CONTENT_SAFETY_KEY"];
BlocklistClient blocklistClient = new BlocklistClient(new Uri(endpoint), new AzureKeyCredential(key));
var blocklistName = "<your_list_name>";
var deleteResult = blocklistClient.DeleteTextBlocklist(blocklistName);
if (deleteResult != null && deleteResult.Status == 204)
{
Console.WriteLine("\nDeleted blocklist.");
}
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare una nuova applicazione Java e aprirla in un editor o un IDE a scelta. Incollare il codice seguente.
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();
String blocklistName = "<your_list_name>";
blocklistClient.deleteTextBlocklist(blocklistName);
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Creare un nuovo script Python in un editor o un IDE a scelta. Incollare il codice seguente.
import os
from azure.ai.contentsafety import BlocklistClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
key = os.environ["CONTENT_SAFETY_KEY"]
endpoint = os.environ["CONTENT_SAFETY_ENDPOINT"]
# Create a Blocklist client
client = BlocklistClient(endpoint, AzureKeyCredential(key))
blocklist_name = "<your_list_name>"
try:
client.delete_text_blocklist(blocklist_name=blocklist_name)
print(f"\nDeleted blocklist: {blocklist_name}")
except HttpResponseError as e:
print("\nDelete blocklist failed:")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
raise
print(e)
raise
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
// Load the .env file if it exists
require("dotenv").config();
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const key = process.env["CONTENT_SAFETY_API_KEY"] || "<key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function deleteBlocklist() {
const blocklistName = "<your_list_name>";
const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).delete();
if (isUnexpected(result)) {
throw result;
}
console.log("Deleted blocklist: ", blocklistName);
}
(async () => {
await deleteBlocklist();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
- Sostituire
<your_list_name>
(nell'URL della richiesta) con il nome usato nel passaggio di creazione dell'elenco.
- Eseguire lo script.
Passaggi successivi
Per altre informazioni sulle API usate in questa guida, vedere la documentazione di riferimento sulle API.