Azure AI Content Veiligheid REST-clientbibliotheek voor JavaScript - versie 1.0.0
/TypeScript
Azure AI Content Veiligheid detecteert schadelijke door gebruikers gegenereerde en AI-gegenereerde inhoud in toepassingen en services. Inhoudsveiligheid omvat tekst- en afbeeldings-API's waarmee u materiaal kunt detecteren dat schadelijk is.
- Tekstanalyse-API: Hiermee wordt tekst gescand op seksuele inhoud, geweld, haat en zelfbeschadiging met niveaus met meerdere ernstniveaus.
- Afbeeldingsanalyse-API: scant afbeeldingen op seksuele inhoud, geweld, haat en zelfbeschadiging met niveaus met meerdere ernstniveaus.
- Beheer-API's voor tekstblokkeringslijsten: de standaard-AI-classificaties zijn voldoende voor de meeste behoeften op het veiligheidsniveau van inhoud; Mogelijk moet u echter controleren op termen die specifiek zijn voor uw use-case. U kunt blokkeringslijsten met termen maken voor gebruik met de Text-API.
Vertrouw sterk op onze REST-clientdocumenten om deze bibliotheek te gebruiken
Belangrijke koppelingen:
Aan de slag
Momenteel ondersteunde omgevingen
- LTS-versies van Node.js
Vereisten
- U hebt een Azure-abonnement nodig om dit pakket te gebruiken.
- Een Azure AI Content Veiligheid resource, als er geen bestaande resource is, kunt u een nieuwe maken.
Installeer het pakket @azure-rest/ai-content-safety
Installeer de rest-clientbibliotheek van Azure AI Content Veiligheid REST-client voor JavaScript met npm
:
npm install @azure-rest/ai-content-safety
Een maken en verifiëren ContentSafetyClient
Het eindpunt ophalen
U kunt het eindpunt voor uw Azure AI Content Veiligheid serviceresource vinden met behulp van Azure Portal of Azure CLI:
# 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"
Een ContentSafetyClient maken met AzureKeyCredential
- Stap 1: de API-sleutel ophalen
De API-sleutel vindt u in Azure Portal of door de volgende Azure CLI-opdracht uit te voeren:
az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
- Stap 2: Een ContentSafetyClient maken met AzureKeyCredential
Als u een API-sleutel als parameter credential
wilt gebruiken, geeft u de sleutel door als een tekenreeks in een exemplaar van 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);
Een ContentSafetyClient maken met Microsoft Entra-id (voorheen Azure Active Directory (AAD)) tokenreferentie
Stap 1: Microsoft Entra-id inschakelen voor uw resource Raadpleeg dit Cognitive Services-verificatiedocument Verifiëren met Microsoft Entra-id voor de stappen voor het inschakelen van AAD voor uw resource.
De belangrijkste stappen zijn:
- Maak een resource met een aangepast subdomein.
- Maak een service-principal en wijs de rol Cognitive Services-gebruiker eraan toe.
Stap 2: stel de waarden van de client-id, tenant-id en clientgeheim van de AAD-toepassing in als omgevingsvariabelen: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
Als u zich wilt verifiëren met AAD, moet u eerst npm
installeren @azure/identity
. Na de installatie kunt u kiezen welk type referentie@azure/identity
u wilt gebruiken.
Als voorbeeld kan DefaultAzureCredential worden gebruikt om de client te verifiëren.
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());
Belangrijkste concepten
Beschikbare functies
Er zijn verschillende soorten analyses beschikbaar via deze service. In de volgende tabel worden de momenteel beschikbare API's beschreven.
Functie | Beschrijving |
---|---|
Tekstanalyse-API | Hiermee scant u tekst op seksuele inhoud, geweld, haat en zelfbeschadiging met niveaus met meerdere ernstniveaus. |
Afbeeldingsanalyse-API | Scant afbeeldingen op seksuele inhoud, geweld, haat en zelfbeschadiging met niveaus van meerdere ernstniveaus. |
Beheer-API's voor tekstblokkeringslijsten | De standaard-AI-classificaties zijn voldoende voor de meeste vereisten voor inhoudsveiligheid. Mogelijk moet u echter controleren op termen die specifiek zijn voor uw use-case. U kunt blokkeringslijsten met termen maken voor gebruik met de Text-API. |
Schadecategorieën
Inhoudsveiligheid herkent vier verschillende categorieën aan ongewenste inhoud.
Categorie | Beschrijving |
---|---|
Haat | Haat verwijst naar alle inhoud die pejoratieve of discriminerende taal gebruikt met betrekking tot een persoon of identiteitsgroep op basis van bepaalde onderscheidende kenmerken van die groep. Dit omvat maar is niet beperkt tot ras, etniciteit, nationaliteit, genderidentiteit en expressie, seksuele geaardheid, religie, immigratiestatus, bekwaamheidsstatus, persoonlijk uiterlijk en lichaamslengte. |
Seksuele | Seksueel beschrijft inhoud met betrekking tot anatomische organen en geslachtsorganen, romantische relaties, handelingen die in erotische of aanhankelijke termen worden weergegeven, zwangerschap, fysieke seksuele handelingen, met inbegrip van de handelingen die worden afgeschilderd als een aanval of een gedwongen seksuele gewelddadige daad tegen de wil van de ander, prostitutie, pornografie en misbruik. |
Geweld | Geweld beschrijft inhoud met betrekking tot fysieke acties die bedoeld zijn om iemand of iets te kwetsen, verwonden, beschadigen of doden. Het omvat ook wapens, wapens en gerelateerde entiteiten, zoals fabrikanten, verenigingen, wetgeving en dergelijke. |
Zelfbeschadiging | Zelfbeschadiging beschrijft inhoud met betrekking tot fysieke acties die bedoeld zijn om iemands lichaam opzettelijk te kwetsen, verwonden of beschadigen of zichzelf te doden. |
Classificatie kan meerdere labels hebben. Wanneer een tekstvoorbeeld bijvoorbeeld het model voor tekstbeheer doorloopt, kan het worden geclassificeerd als zowel seksuele inhoud als geweld.
Ernstniveaus
Elke categorie van schade die door de service wordt toegepast, heeft ook een ernstniveauclassificatie. Het ernstniveau is bedoeld om de ernst aan te geven van de gevolgen van het weergeven van de gemarkeerde inhoud.
Tekst: de huidige versie van het tekstmodel ondersteunt de volledige ernstschaal van 0-7. Het antwoord voert standaard 4 waarden uit: 0, 2, 4 en 6. Elke twee aangrenzende niveaus worden toegewezen aan één niveau. Gebruikers kunnen 'outputType' gebruiken in de aanvraag en deze instellen op 'EightSeverityLevels' om 8 waarden in uitvoer op te halen: 0,1,2,3,4,5,6,7. U kunt definities van ernstniveaus voor tekstinhoud raadplegen voor meer informatie.
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
Afbeelding: De huidige versie van het afbeeldingsmodel ondersteunt de ingekorte versie van de volledige ernstschaal van 0-7. De classificatie retourneert alleen ernst 0, 2, 4 en 6; elke twee aangrenzende niveaus worden toegewezen aan één niveau. U kunt definities van ernstniveaus voor afbeeldingsinhoud raadplegen voor meer informatie.
- [0,1] -> 0
- [2,3] -> 2
- [4,5] -> 4
- [6,7] -> 6
Beheer van tekstblokkeringslijsten
De volgende bewerkingen worden ondersteund voor het beheren van uw tekstbloklijst:
- Een blokkeringslijst maken of wijzigen
- Alle blokkeringslijsten weergeven
- Een blokkeringslijst ophalen op blocklistName
- blockItems toevoegen aan een blokkeringslijst
- blockItems verwijderen uit een blokkeringslijst
- Alle blockItems in een blokkeringslijst weergeven op blocklistName
- Een blockItem ophalen in een blokkeringslijst door blockItemId en blocklistName
- Een blokkeringslijst en alle bijbehorende blockItems verwijderen
U kunt de blokkeringslijsten instellen die u wilt gebruiken bij het analyseren van tekst, waarna u het resultaat van de blokkeringslijstovereenkomst kunt ophalen uit het geretourneerde antwoord.
Voorbeelden
De volgende sectie bevat verschillende codefragmenten die betrekking hebben op enkele van de meest voorkomende Content Safety-servicetaken in zowel TypeScript als JavaScript, waaronder:
Tekst analyseren
Tekst analyseren zonder blokkeringslijsten
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);
});
Tekst analyseren met blokkeringslijsten
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);
});
Afbeelding analyseren
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);
});
Tekstblokkeringslijst beheren
Tekstblokkeringslijst maken of bijwerken
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);
});
Tekstblokkeringslijsten weergeven
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);
});
Tekstblokkeringslijst ophalen
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);
});
Tekstblokkeringslijst verwijderen
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);
});
BlockItems toevoegen
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);
});
BlockItems weergeven
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);
});
BlockItem ophalen
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);
});
BlockItems verwijderen
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);
});
Problemen oplossen
Logboekregistratie
Het inschakelen van logboekregistratie kan helpen bij het ontdekken van nuttige informatie over fouten. Als u een logboek met HTTP-aanvragen en -antwoorden wilt zien, stelt u de AZURE_LOG_LEVEL
omgevingsvariabele in op info
. Logboekregistratie kan ook worden ingeschakeld tijdens runtime door aan te roepen setLogLevel
in de @azure/logger
:
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
Voor meer gedetailleerde instructies over het inschakelen van logboeken kunt u de @azure-/loggerpakketdocumenten bekijken.
Volgende stappen
Aanvullende documentatie
Zie de Azure AI Content Veiligheid op docs.microsoft.com voor uitgebreidere documentatie over Azure Content Safety.
Bijdragen
Als u een bijdrage wilt leveren aan deze bibliotheek, leest u de handleiding voor bijdragen voor meer informatie over het bouwen en testen van de code.
Azure SDK for JavaScript