Sicurezza dei contenuti di Azure AI libreria client REST per JavaScript - versione 1.0.0
/TypeScript
Sicurezza dei contenuti di Azure AI rileva contenuti generati dall'utente dannosi e generati dall'intelligenza artificiale nelle applicazioni e nei servizi. La sicurezza del contenuto include API di testo e immagine che consentono di rilevare materiale dannoso.
- API Analisi del testo: analizza il testo per contenuto sessuale, violenza, odio e autolesionismo con livelli di gravità multipla.
- API Analisi immagini: analizza immagini per contenuti sessuali, violenza, odio e autolesionismo con livelli di gravità multipla.
- API di gestione blocklist di testo: i classificatori di intelligenza artificiale predefiniti sono sufficienti per la maggior parte delle esigenze di sicurezza dei contenuti; Potrebbe tuttavia essere necessario visualizzare la schermata per i termini specifici del caso d'uso. È possibile creare elenchi di blocchi di termini da usare con l'API Testo.
Per usare questa libreria, affidarsi fortemente alla documentazione del client REST
Collegamenti principali:
Introduzione
Ambienti attualmente supportati
- Versioni LTS di Node.js
Prerequisiti
- È necessaria una sottoscrizione di Azure per usare questo pacchetto.
- Una risorsa Sicurezza dei contenuti di Azure AI, se non esiste alcuna risorsa esistente, è possibile crearne una nuova.
Installare il pacchetto @azure-rest/ai-content-safety
Installare la libreria client REST del Sicurezza dei contenuti di Azure AI per JavaScript con npm
:
npm install @azure-rest/ai-content-safety
Creare e autenticare un oggetto ContentSafetyClient
Ottenere l'endpoint
È possibile trovare l'endpoint per la risorsa del servizio Sicurezza dei contenuti di Azure AI usando il portale di Azure o l'interfaccia della riga di comando di Azure:
# Get the endpoint for the Azure AI Content Safety service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"
Creare un contentSafetyClient con AzureKeyCredential
- Passaggio 1: Ottenere la chiave API
La chiave API è disponibile nel portale di Azure o eseguendo il comando dell'interfaccia della riga di comando di Azure seguente:
az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
- Passaggio 2: Creare un contentSafetyClient con AzureKeyCredential
Per usare una chiave API come credential
parametro, passare la chiave come stringa in un'istanza di AzureKeyCredential
.
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
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);
Creare una credenziale del token ContentSafetyClient con Microsoft Entra ID (in precedenza Azure Active Directory (AAD))
Passaggio 1: Abilitare Microsoft Entra ID per la risorsa Fare riferimento a questo documento di autenticazione di Servizi cognitivi Autenticare con Microsoft Entra ID. Per abilitare AAD per la risorsa.
I passaggi principali sono:
- Creare una risorsa con un sottodominio personalizzato.
- Creare un'entità servizio e assegnare il ruolo utente di Servizi cognitivi.
Passaggio 2: Impostare i valori dell'ID client, dell'ID tenant e del segreto client dell'applicazione AAD come variabili di ambiente: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
Per eseguire l'autenticazione con AAD, è prima necessario npm
installare @azure/identity
. Dopo la configurazione, è possibile scegliere quale tipo di credenziale da @azure/identity
usare.
Ad esempio, DefaultAzureCredential può essere usato per autenticare il client.
import ContentSafetyClient from "@azure-rest/ai-content-safety";
import { DefaultAzureCredential } from "@azure/identity";
const endpoint = process.env["CONTENT_SAFETY_ENDPOINT"] || "<endpoint>";
const client = ContentSafetyClient(endpoint, new DefaultAzureCredential());
Concetti chiave
Funzionalità disponibili
Esistono diversi tipi di analisi disponibili da questo servizio. Nella tabella seguente vengono descritte le API attualmente disponibili.
Funzionalità | Descrizione |
---|---|
API analisi del testo | Analizza il testo per contenuti sessuali, violenza, odio e autolesionismo con livelli di gravità multipla. |
API di analisi delle immagini | Analizza le immagini per contenuti sessuali, violenza, odio e autolesionismo con livelli di gravità multipla. |
API di gestione degli elenchi di testo | I classificatori di intelligenza artificiale predefiniti sono sufficienti per la maggior parte delle esigenze di sicurezza dei contenuti. Tuttavia, potrebbe essere necessario visualizzare la schermata per i termini specifici del caso d'uso. È possibile creare elenchi di blocchi di termini da usare con l'API Testo. |
Categorie di danni
La sicurezza del contenuto riconosce quattro categorie distinte di contenuto discutibile.
Category | Descrizione |
---|---|
Odio | L'odio si riferisce a qualsiasi contenuto che attacca o usa linguaggio pejorative o discriminatorio in riferimento a una persona o a un gruppo di identità in base a determinati attributi diversi di tale gruppo. Ciò include, ma non è limitato alla razza, all'etnia, alla nazionalità, all'identità di genere e all'espressione, all'orientamento sessuale, alla religione, allo stato di immigrazione, allo stato di abilità, all'aspetto personale e alle dimensioni del corpo. |
Sessuale | La descrizione sessuale descrive il contenuto correlato a organi anatomici e genitali, relazioni romantiche, atti rappresentati in termini erotici o affettuosi, gravidanza, atti sessuali fisici, tra cui tali atti interpretati come un assalto o un atto violento sessuale forzato contro la volontà di uno, la prostituzione, la pornografia e l'abuso. |
Violenza | La violenza descrive il contenuto correlato alle azioni fisiche destinate a danneggiare, danneggiare, danneggiare o uccidere qualcuno o qualcosa. Include anche armi, pistole e entità correlate, ad esempio produttori, associazioni, normative e simili. |
Autolesionismo | L'autolesionismo descrive il contenuto correlato alle azioni fisiche destinate a danneggiare intenzionalmente, ferire o danneggiare il corpo o uccidersi. |
La classificazione può essere con etichetta multipla. Ad esempio, quando un esempio di testo passa attraverso il modello di moderazione del testo, può essere classificato come contenuto sessuale e violenza.
Livelli di gravità
Ogni categoria di danni applicata al servizio include anche una classificazione a livello di gravità. Il livello di gravità è destinato a indicare la gravità delle conseguenze della visualizzazione del contenuto contrassegnato.
Testo: la versione corrente del modello di testo supporta la scala di gravità completa di 0-7. Per impostazione predefinita, la risposta restituisce 4 valori: 0, 2, 4 e 6. Ogni due livelli adiacenti vengono mappati a un singolo livello. Gli utenti possono usare "outputType" nella richiesta e impostarlo come "EightSeverityLevels" per ottenere 8 valori nell'output: 0,1,2,3,4,5,6,7. Per informazioni dettagliate, è possibile fare riferimento alle definizioni dei livelli di gravità del contenuto del testo .
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
Immagine: la versione corrente del modello di immagine supporta la versione troncato della scala di gravità completa di 0-7. Il classificatore restituisce solo gravità 0, 2, 4 e 6; ogni due livelli adiacenti vengono mappati a un singolo livello. Per informazioni dettagliate, è possibile fare riferimento alle definizioni dei livelli di gravità del contenuto dell'immagine .
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
Gestione degli elenchi di blocchi di testo
Le operazioni seguenti sono supportate per gestire l'elenco dei blocchi di testo:
- Creare o modificare un elenco di blocchi
- Elencare tutti gli elenchi di blocchi
- Ottenere un elenco di blocchi per blocklistName
- Aggiungere blockItems a un elenco di blocchi
- Rimuovere blockItems da un elenco blocchi
- Elencare tutti gli elementi blockItem in un elenco di blocchi per blocklistName
- Ottenere un blockItem in un elenco di blocchi per blockItemId e blocklistName
- Eliminare un elenco di blocchi e tutti i relativi blockItem
È possibile impostare gli elenchi di blocchi da usare per l'analisi del testo, quindi è possibile ottenere il risultato della corrispondenza dell'elenco di blocchi dalla risposta restituita.
Esempio
La sezione seguente fornisce diversi frammenti di codice che illustrano alcune delle attività più comuni del servizio Content Safety in TypeScript e JavaScript, tra cui:
Analizzare il testo
Analizzare il testo senza elenchi bloccati
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
async function main() {
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
const text = "This is a sample text";
const analyzeTextOption = { text: text };
const analyzeTextParameters = { body: analyzeTextOption };
const result = await client.path("/text:analyze").post(analyzeTextParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const textCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(textCategoriesAnalysisOutput.category, " severity: ", textCategoriesAnalysisOutput.severity)
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
async function main() {
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
const text = "This is a sample text";
const analyzeTextOption = { text: text };
const analyzeTextParameters = { body: analyzeTextOption };
const result = await client.path("/text:analyze").post(analyzeTextParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const textCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(
textCategoriesAnalysisOutput.category,
" severity: ",
textCategoriesAnalysisOutput.severity
);
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Analizzare il testo con elenchi di blocchi
TypeScript
import ContentSafetyClient, { CreateOrUpdateTextBlocklistParameters, isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
const createOrUpdateTextBlocklistParameters: 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 function addBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1
},
{
description: "Test block item 2",
text: blockItemText2
}
]
}
};
const result = await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName).post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log("BlockItemId: ", blockItem.blocklistItemId, ", Text: ", blockItem.text, ", Description: ", blockItem.description);
}
}
}
async function analyzeTextWithBlocklists() {
const blocklistName = "TestBlocklist";
const inputText = "This is a sample to test text with blocklist.";
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, ", BlockItemId: ", blocklistMatchResult.blocklistItemId, ", BlockItemText: ", blocklistMatchResult.blocklistItemText);
}
}
}
(async () => {
await createOrUpdateTextBlocklist();
await addBlockItems();
await analyzeTextWithBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
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 function addBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1,
},
{
description: "Test block item 2",
text: blockItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description
);
}
}
}
async function analyzeTextWithBlocklists() {
const blocklistName = "TestBlocklist";
const inputText = "This is a sample to test text with blocklist.";
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,
", BlockItemId: ",
blocklistMatchResult.blocklistItemId,
", BlockItemText: ",
blocklistMatchResult.blocklistItemText
);
}
}
}
(async () => {
await createOrUpdateTextBlocklist();
await addBlockItems();
await analyzeTextWithBlocklists();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
Analizzare l'immagine
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
import fs from "fs";
import path from "path";
async function main() {
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
const image_path = path.resolve(__dirname, "./samples-dev/example-data/image.png");
const imageBuffer = fs.readFileSync(image_path);
const base64Image = imageBuffer.toString("base64");
const analyzeImageOption = { image: { content: base64Image } };
const analyzeImageParameters = { body: analyzeImageOption };
const result = await client.path("/image:analyze").post(analyzeImageParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const imageCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(imageCategoriesAnalysisOutput.category, " severity: ", imageCategoriesAnalysisOutput.severity)
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const fs = require("fs");
const path = require("path");
async function main() {
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
const image_path = path.resolve(__dirname, "./samples-dev/example-data/image.png");
const imageBuffer = fs.readFileSync(image_path);
const base64Image = imageBuffer.toString("base64");
const analyzeImageOption = { image: { content: base64Image } };
const analyzeImageParameters = { body: analyzeImageOption };
const result = await client.path("/image:analyze").post(analyzeImageParameters);
if (isUnexpected(result)) {
throw result;
}
for (let i = 0; i < result.body.categoriesAnalysis.length; i++) {
const imageCategoriesAnalysisOutput = result.body.categoriesAnalysis[i];
console.log(
imageCategoriesAnalysisOutput.category,
" severity: ",
imageCategoriesAnalysisOutput.severity
);
}
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Gestire l'elenco di blocchi di testo
Creare o aggiornare l'elenco di blocchi di testo
TypeScript
import ContentSafetyClient, { CreateOrUpdateTextBlocklistParameters, isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
const createOrUpdateTextBlocklistParameters: 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);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
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);
});
Elencare elenchi di elementi bloccati di testo
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_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);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_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);
});
Ottenere l'elenco di blocchi di testo
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getTextBlocklist() {
const blocklistName = "TestBlocklist";
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);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getTextBlocklist() {
const blocklistName = "TestBlocklist";
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);
});
Elimina elenco di blocchi di testo
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function deleteBlocklist() {
const blocklistName = "TestBlocklist";
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);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function deleteBlocklist() {
const blocklistName = "TestBlocklist";
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);
});
Aggiungere blockItems
TypeScript
import ContentSafetyClient, { CreateOrUpdateTextBlocklistParameters, isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
const createOrUpdateTextBlocklistParameters: 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 function addBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1
},
{
description: "Test block item 2",
text: blockItemText2
}
]
}
};
const result = await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName).post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log("BlockItemId: ", blockItem.blocklistItemId, ", Text: ", blockItem.text, ", Description: ", blockItem.description);
}
}
}
(async () => {
await createOrUpdateTextBlocklist();
await addBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function createOrUpdateTextBlocklist() {
const blocklistName = "TestBlocklist";
const blocklistDescription = "Test blocklist management.";
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 function addBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText1 = "sample";
const blockItemText2 = "text";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText1,
},
{
description: "Test block item 2",
text: blockItemText2,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result)) {
throw result;
}
console.log("Block items added: ");
if (result.body.blocklistItems) {
for (const blockItem of result.body.blocklistItems) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description
);
}
}
}
(async () => {
await createOrUpdateTextBlocklist();
await addBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
List blockItems
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listBlockItems() {
const blocklistName = "TestBlocklist";
const result = await client.path("/text/blocklists/{blocklistName}/blocklistItems", blocklistName).get();
if (isUnexpected(result)) {
throw result;
}
console.log("List block items: ");
if (result.body.value) {
for (const blockItem of result.body.value) {
console.log("BlockItemId: ", blockItem.blocklistItemId, ", Text: ", blockItem.text, ", Description: ", blockItem.description);
}
}
}
(async () => {
await listBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function listBlockItems() {
const blocklistName = "TestBlocklist";
const result = await client
.path("/text/blocklists/{blocklistName}/blocklistItems", blocklistName)
.get();
if (isUnexpected(result)) {
throw result;
}
console.log("List block items: ");
if (result.body.value) {
for (const blockItem of result.body.value) {
console.log(
"BlockItemId: ",
blockItem.blocklistItemId,
", Text: ",
blockItem.text,
", Description: ",
blockItem.description
);
}
}
}
(async () => {
await listBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
Get blockItem
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getBlockItem() {
const blocklistName = "TestBlocklist";
const blockItemText = "sample";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText
}
]
}
};
const result = await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName).post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result) || result.body.blocklistItems === undefined) {
throw new Error("Block item not added.");
}
const blockItemId = result.body.blocklistItems[0].blocklistItemId;
const blockItem = await client.path("/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}", blocklistName, blockItemId).get();
if (isUnexpected(blockItem)) {
throw blockItem;
}
console.log("Get blockitem: ");
console.log("BlockItemId: ", blockItem.body.blocklistItemId, ", Text: ", blockItem.body.text, ", Description: ", blockItem.body.description);
}
(async () => {
await getBlockItem();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function getBlockItem() {
const blocklistName = "TestBlocklist";
const blockItemText = "sample";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result) || result.body.blocklistItems === undefined) {
throw new Error("Block item not added.");
}
const blockItemId = result.body.blocklistItems[0].blocklistItemId;
const blockItem = await client
.path(
"/text/blocklists/{blocklistName}/blocklistItems/{blocklistItemId}",
blocklistName,
blockItemId
)
.get();
if (isUnexpected(blockItem)) {
throw blockItem;
}
console.log("Get blockitem: ");
console.log(
"BlockItemId: ",
blockItem.body.blocklistItemId,
", Text: ",
blockItem.body.text,
", Description: ",
blockItem.body.description
);
}
(async () => {
await getBlockItem();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
Rimuovere blockItems
TypeScript
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { AzureKeyCredential } from "@azure/core-auth";
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function removeBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText = "sample";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText
}
]
}
};
const result = await client.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName).post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result) || result.body.blocklistItems === undefined) {
throw new Error("Block item not added.");
}
const blockItemId = result.body.blocklistItems[0].blocklistItemId;
const removeBlocklistItemsParameters = {
body: {
blocklistItemIds: [blockItemId]
}
};
const removeBlockItem = await client.path("/text/blocklists/{blocklistName}:removeBlocklistItems", blocklistName).post(removeBlocklistItemsParameters);
if (isUnexpected(removeBlockItem)) {
throw removeBlockItem;
}
console.log("Removed blockItem: ", blockItemText);
}
(async () => {
await removeBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
JavaScript
const ContentSafetyClient = require("@azure-rest/ai-content-safety").default,
{ isUnexpected } = require("@azure-rest/ai-content-safety");
const { AzureKeyCredential } = require("@azure/core-auth");
const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);
async function removeBlockItems() {
const blocklistName = "TestBlocklist";
const blockItemText = "sample";
const addOrUpdateBlocklistItemsParameters = {
body: {
blocklistItems: [
{
description: "Test block item 1",
text: blockItemText,
},
],
},
};
const result = await client
.path("/text/blocklists/{blocklistName}:addOrUpdateBlocklistItems", blocklistName)
.post(addOrUpdateBlocklistItemsParameters);
if (isUnexpected(result) || result.body.blocklistItems === undefined) {
throw new Error("Block item not added.");
}
const blockItemId = result.body.blocklistItems[0].blocklistItemId;
const removeBlocklistItemsParameters = {
body: {
blocklistItemIds: [blockItemId],
},
};
const removeBlockItem = await client
.path("/text/blocklists/{blocklistName}:removeBlocklistItems", blocklistName)
.post(removeBlocklistItemsParameters);
if (isUnexpected(removeBlockItem)) {
throw removeBlockItem;
}
console.log("Removed blockItem: ", blockItemText);
}
(async () => {
await removeBlockItems();
})().catch((err) => {
console.error("The sample encountered an error:", err);
});
Risoluzione dei problemi
Registrazione
L'abilitazione della registrazione consente di individuare informazioni utili sugli errori. Per visualizzare un log di richieste e risposte HTTP, impostare la variabile di ambiente AZURE_LOG_LEVEL
su info
. In alternativa, la registrazione può essere abilitata in fase di esecuzione chiamando setLogLevel
in @azure/logger
:
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
Per istruzioni più dettagliate su come abilitare i log, è possibile esaminare la documentazione del pacchetto di @azure/logger.
Passaggi successivi
Documentazione aggiuntiva
Per una documentazione più completa su Sicurezza dei contenuti di Azure, vedere il Sicurezza dei contenuti di Azure AI in docs.microsoft.com.
Contributo
Per contribuire a questa libreria, leggere la guida ai contributi per altre informazioni su come compilare e testare il codice.
Azure SDK for JavaScript