Dela via


Azure AI Content Safety REST-klientbibliotek för JavaScript – version 1.0.1

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

  • API för textanalys: Söker igenom text efter sexuellt innehåll, våld, hat och självskadebeteende med flera allvarlighetsnivåer.
  • API för bildanalys: Söker igenom bilder efter sexuellt innehåll, våld, hat och självskadebeteende med flera allvarlighetsnivåer.
  • API:er för hantering av textblockering: STANDARD-AI-klassificerare räcker 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.

Vi förlitar dig mycket på våra REST-klientdokument för att kunna 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 för Rest-klientbiblioteket för Azure AI Content Safety 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 Content Safety-tjänstresurs med hjälp av Azure Portal 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

API-nyckeln finns 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 parametern credential skickar du nyckeln som en sträng till en instans av AzureKeyCredential.

import { AzureKeyCredential } from "@azure/core-auth";
import ContentSafetyClient from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const key = "<api_key>";
const credential = new AzureKeyCredential(key);
const client = ContentSafetyClient(endpoint, credential);

Skapa en ContentSafetyClient med autentiseringsuppgifter 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. för stegen för att aktivera AAD för din resurs.

    De viktigaste stegen är:

    • Skapa 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 autentiseringsuppgifter från @azure/identity att använda. Till exempel kan StandardAzureCredential användas för att autentisera klienten.

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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 de api:er som för närvarande är tillgängliga.

Drag Beskrivning
API för textanalys Söker igenom text efter sexuellt innehåll, våld, hat och självskadebeteende med flera allvarlighetsnivåer.
API för bildanalys Söker igenom bilder efter sexuellt innehåll, våld, hat och självskadebeteende med flera allvarlighetsnivåer.
API:er för hantering av textblockering Ai-standardklassificerarna räcker 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
Hata Hat avser 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.
Sexuell Sexual beskriver innehåll som rör anatomiska organ och könsorgan, romantiska relationer, handlingar som porträtteras i erotiska eller tillgivna termer, graviditet, fysiska sexuella handlingar , inklusive de handlingar som framställs som ett övergrepp eller en 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, skada eller döda någon eller något. Den omfattar även vapen, vapen och relaterade enheter, till exempel tillverkare, föreningar, lagstiftning och liknande.
Självskadebeteende Självskadebeteende beskriver innehåll som rör fysiska handlingar som syftar till 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.

Allvarlighetsgrad

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

Text: Den aktuella versionen av textmodellen stöder fullständig allvarlighetsgrad på 0–7. Som standard matar svaret ut 4 värden: 0, 2, 4 och 6. Varje två intilliggande nivåer mappas till en enda nivå. Användare kan använda "outputType" i begäran och ange den som "EightSeverityLevels" för att få 8 värden i utdata: 0,1,2,3,4,5,6,7. Du kan läsa definitioner av allvarlighetsgraderna för textinnehåll för mer information.

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

Image: Den aktuella versionen av avbildningsmodellen stöder den trimmade versionen av den fullständiga allvarlighetsgraden 0–7. Klassificeraren returnerar endast allvarlighetsgrad 0, 2, 4 och 6. varje två intilliggande nivåer mappas till en enda nivå. Du kan läsa definitioner av bildinnehålls allvarlighetsgrad för mer information.

  • [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 blocklista 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 blocklist av 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å resultat av blocklistmatchning från returnerade svar.

Exempel

Följande avsnitt innehåller flera kodfragment som täcker några av de vanligaste content safety-tjänsterna i både TypeScript- och JavaScript-, inklusive:

Analysera text

Analysera text utan blocklistor

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
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,
  );
}

Analysera text med blocklistor

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, {
  CreateOrUpdateTextBlocklistParameters,
  isUnexpected,
} from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
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,
      );
    }
  }
}

try {
  await createOrUpdateTextBlocklist();
  await addBlockItems();
  await analyzeTextWithBlocklists();
} catch (err) {
  console.error("The sample encountered an error:", err);
}

Analysera bild

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";
import { readFileSync } from "node:fs";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

const image_path = "./samples-dev/example-data/image.png";

const imageBuffer = 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,
  );
}

Hantera textblockeringslista

Skapa eller uppdatera textblockeringslista

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, {
  CreateOrUpdateTextBlocklistParameters,
  isUnexpected,
} from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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

Lista textblockeringslistor

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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

Hämta textblockeringslista

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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

Ta bort textblockeringslista

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

const blocklistName = "TestBlocklist";

const result = await client.path("/text/blocklists/{blocklistName}", blocklistName).delete();

if (isUnexpected(result)) {
  throw result;
}

console.log("Deleted blocklist: ", blocklistName);

Lägga till blockItems

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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

Lista blockItems

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

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

Hämta blockItem

Maskin

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

const blockItemId = "<blockItemId>";
const blocklistName = "TestBlocklist";

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

Ta bort blockItems

import { DefaultAzureCredential } from "@azure/identity";
import ContentSafetyClient, { isUnexpected } from "@azure-rest/ai-content-safety";

const endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/";
const credential = new DefaultAzureCredential();
const client = ContentSafetyClient(endpoint, credential);

const blockItemId = "<blockItemId>";
const blocklistName = "TestBlocklist";
const blockItemText = "sample";

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

Felsökning

Skogsavverkning

Aktivering av loggning kan hjälpa dig att hitta användbar information om fel. Om du vill se en logg med 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:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

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

Nästa steg

Ytterligare dokumentation

Mer omfattande dokumentation om Azure Content Safety finns i Azure AI Content Safety- på learn.microsoft.com.

Bidragande

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