Dela via


Azure AI Innehållsäkerhet REST-klientbibliotek för JavaScript – version 1.0.0

/Maskin

Azure AI Innehållsäkerhet identifierar skadligt användargenererat och AI-genererat innehåll i program och tjänster. Content Safety innehåller text- och bild-API:er som gör att du kan identifiera skadligt material.

  • API för textanalys: Söker igenom text efter sexuellt innehåll, våld, hat och självskada med flera allvarlighetsnivåer.
  • API för bildanalys: Söker igenom bilder efter sexuellt innehåll, våld, hat och självskada med flera allvarlighetsnivåer.
  • API:er för hantering av textblockering: AI-standardklassificerarna är tillräckliga för de flesta innehållssäkerhetsbehov; Du kan dock behöva söka efter termer som är specifika för ditt användningsfall. Du kan skapa blocklistor med termer som ska användas med text-API:et.

Förlita dig mycket på våra REST-klientdokument för att använda det här biblioteket

Nyckellänkar:

Komma igång

Miljöer som stöds för närvarande

  • LTS-versioner av Node.js

Förutsättningar

Installera @azure-rest/ai-content-safety-paketet

Installera rest-klientbiblioteket Azure AI Innehållsäkerhet REST för JavaScript med npm:

npm install @azure-rest/ai-content-safety

Skapa och autentisera en ContentSafetyClient

Hämta slutpunkten

Du hittar slutpunkten för din Azure AI Innehållsäkerhet-tjänstresurs med hjälp av Azure-portalen eller 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"

Skapa en ContentSafetyClient med AzureKeyCredential

  • Steg 1: Hämta API-nyckeln

DU hittar API-nyckeln i Azure-portalen eller genom att köra följande Azure CLI-kommando :

az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
  • Steg 2: Skapa en ContentSafetyClient med AzureKeyCredential

Om du vill använda en API-nyckel som credential parameter skickar du nyckeln som en sträng till en instans av 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);

Skapa en ContentSafetyClient med tokenautentiseringsuppgifter för Microsoft Entra-ID (tidigare Azure Active Directory (AAD)

  • Steg 1: Aktivera Microsoft Entra-ID för din resurs Läs det här Cognitive Services-autentiseringsdokumentet Autentisera med Microsoft Entra-ID. Anvisningar för att aktivera AAD för din resurs.

    De viktigaste stegen är:

    • Skapa en resurs med en anpassad underdomän.
    • Skapa tjänstens huvudnamn och tilldela cognitive services-användarrollen till den.
  • Steg 2: Ange värdena för klient-ID, klient-ID och klienthemlighet för AAD-programmet som miljövariabler: AZURE_CLIENT_ID, AZURE_TENANT_ID AZURE_CLIENT_SECRET

Om du vill autentisera med AAD måste du först npm installera @azure/identity. Efter installationen kan du välja vilken typ av autentiseringsuppgift du @azure/identity vill använda. Till exempel kan DefaultAzureCredential användas för att autentisera klienten.

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());

Viktiga begrepp

Tillgängliga funktioner

Det finns olika typer av analys som är tillgängliga från den här tjänsten. I följande tabell beskrivs tillgängliga API:er.

Funktion Beskrivning
API för textanalys Söker igenom text efter sexuellt innehåll, våld, hat och självskada med flera allvarlighetsnivåer.
API för bildanalys Söker igenom bilder efter sexuellt innehåll, våld, hat och självskada med flera allvarlighetsnivåer.
API:er för hantering av textblockeringslista Ai-standardklassificerarna är tillräckliga för de flesta innehållssäkerhetsbehov. Du kan dock behöva söka efter termer som är specifika för ditt användningsfall. Du kan skapa blocklistor med termer som ska användas med text-API:et.

Skadekategorier

Content Safety identifierar fyra olika kategorier av stötande innehåll.

Kategori Beskrivning
Hatar Hat syftar på innehåll som angriper eller använder nedsättande eller diskriminerande språk med hänvisning till en person eller identitetsgrupp baserat på vissa differentieringsattribut för den gruppen. Detta inkluderar men är inte begränsat till ras, etnicitet, nationalitet, könsidentitet och uttryck, sexuell läggning, religion, invandringsstatus, förmågasstatus, personligt utseende och kroppsstorlek.
Sexuella Sexuell beskriver innehåll som rör anatomiska organ och könsorgan, romantiska relationer, handlingar som framställs i erotiska eller tillgivna termer, graviditet, fysiska sexuella handlingar , inklusive de handlingar som framställs som ett övergrepp eller en påtvingad sexuell våldsam handling mot ens vilja - prostitution, pornografi och övergrepp.
Våld Våld beskriver innehåll som rör fysiska handlingar som är avsedda att skada, skada eller döda någon eller något. Det omfattar också vapen, vapen och relaterade enheter, såsom tillverkare, föreningar, lagstiftning och liknande.
Självskada Självskada beskriver innehåll som rör fysiska handlingar som är avsedda att avsiktligt skada, skada eller skada ens kropp eller döda sig själv.

Klassificering kan vara flera etiketter. När ett textexempel till exempel går igenom textmodereringsmodellen kan det klassificeras som både sexuellt innehåll och våld.

Allvarlighetsnivåer

Varje skadekategori som tjänsten gäller har också en allvarlighetsgrad. Allvarlighetsgraden är avsedd att ange allvarlighetsgraden för konsekvenserna av att visa det flaggade innehållet.

Text: Den aktuella versionen av textmodellen stöder den fullständiga allvarlighetsgraden 0–7. Som standard matar svaret ut 4 värden: 0, 2, 4 och 6. Varje två angränsande nivåer mappas till en enda nivå. Användare kan använda "outputType" i begäran och ange den som "EightSeverityLevels" för att hämta 8 värden i utdata: 0,1,2,3,4,5,6,7. Mer information finns i definitionerna för allvarlighetsgraderna för textinnehåll .

  • [0,1] -> 0
  • [2,3] -> 2
  • [4,5] -> 4
  • [6,7] -> 6

Bild: Den aktuella versionen av avbildningsmodellen stöder den trimmade versionen av den fullständiga allvarlighetsgraden 0–7. Klassificeraren returnerar endast allvarlighetsgraderna 0, 2, 4 och 6. varje två angränsande nivåer mappas till en enda nivå. Mer information finns i definitionerna för allvarlighetsgraderna för bildinnehåll .

  • [0,1] -> 0
  • [2,3] -> 2
  • [4,5] -> 4
  • [6,7] -> 6

Hantering av textblockeringslistor

Följande åtgärder stöds för att hantera din textblockeringslista:

  • Skapa eller ändra en blockeringslista
  • Visa en lista över alla blocklistor
  • Hämta en blockeringslista efter blocklistName
  • Lägga till blockItems i en blocklista
  • Ta bort blockItems från en blocklista
  • Visa en lista över alla blockItems i en blocklista efter blocklistName
  • Hämta en blockItem i en blocklista efter blockItemId och blocklistName
  • Ta bort en blockeringslista och alla dess blockItems

Du kan ange de blocklistor som du vill använda när du analyserar text, och sedan kan du få matchningsresultat för blocklista från returnerade svar.

Exempel

Följande avsnitt innehåller flera kodfragment som omfattar några av de vanligaste innehållssäkerhetstjänstuppgifterna i både TypeScript och JavaScript, inklusive:

Analysera text

Analysera text utan blocklistor

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);
});

Analysera text med blocklistor

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);
});

Analysera bild

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);
});

Hantera textblockeringslista

Skapa eller uppdatera textblockeringslista

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);
});

Lista textblockeringslistor

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);
});

Hämta textblockeringslista

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);
});

Ta bort textblockeringslista

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);
});

Lägga till 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);
});

Lista 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);
});

Hämta 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);
});

Ta bort 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);
});

Felsökning

Loggning

Aktivering av loggning kan hjälpa dig att hitta användbar information om fel. Om du vill se en logg över HTTP-begäranden och svar anger du AZURE_LOG_LEVEL miljövariabeln till info. Du kan också aktivera loggning vid körning genom att anropa setLogLevel i @azure/logger:

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

Mer detaljerade anvisningar om hur du aktiverar loggar finns i @azure-/loggningspaketdokumenten.

Nästa steg

Ytterligare dokumentation

Mer omfattande dokumentation om Azure Content Safety finns i Azure AI Innehållsäkerhet på docs.microsoft.com.

Bidra

Om du vill bidra till det här biblioteket kan du läsa bidragsguiden för att lära dig mer om hur du skapar och testar koden.