共用方式為


適用於 JavaScript 的 Azure AI Content Safety REST 用戶端連結庫 - 1.0.1 版

Azure AI 內容安全性 會在應用程式和服務中偵測有害的用戶產生和 AI 產生的內容。 內容安全性包含文字和影像 API,可讓您偵測有害的材料。

  • 文字分析 API:掃描文字中具有多重嚴重性層級的性內容、暴力、仇恨和自我傷害。
  • 影像分析 API:掃描具有多重嚴重性層級的性內容、暴力、仇恨和自我傷害影像。
  • 文本封鎖清單管理 API:預設的 AI 分類器足以滿足大部分的內容安全性需求;不過,您可能需要篩選使用案例專屬的字詞。 您可以建立要與文字 API 搭配使用的字詞封鎖清單。

請高度依賴我們的 REST 用戶端檔, 使用此連結庫

主要連結:

開始

目前支持的環境

  • LTS 版本的 Node.js

先決條件

安裝 @azure-rest/ai-content-safety 套件

使用 npm安裝適用於 JavaScript 的 Azure AI Content Safety REST 用戶端 REST 用戶端連結庫:

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

建立和驗證 ContentSafetyClient

取得端點

您可以使用 Azure 入口網站 或 azure CLI ,找到 Azure AI Content Safety 服務資源的端點:

# 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"

使用 AzureKeyCredential 建立 ContentSafetyClient

  • 步驟 1:取得 API 金鑰

您可以在 Azure 入口網站 中找到 API 金鑰,或執行下列 Azure CLI 命令:

az cognitiveservices account keys list --name "<resource-name>" --resource-group "<resource-group-name>"
  • 步驟 2:使用 AzureKeyCredential 建立 ContentSafetyClient

若要使用 API 金鑰作為 credential 參數,請將金鑰當做字串傳遞至 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);

使用 Microsoft Entra ID (先前稱為 Azure Active Directory (AAD)) 令牌認證建立 ContentSafetyClient

  • 步驟 1:為您的資源啟用Microsoft專案標識符 請參閱此認知服務驗證檔,使用 Microsoft Entra ID進行驗證。針對為資源啟用 AAD 的步驟。

    主要步驟包括:

    • 使用自訂子域建立資源。
    • 建立服務主體,並將認知服務使用者角色指派給它。
  • 步驟 2:將 AAD 應用程式的用戶端識別碼、租使用者識別碼和客戶端密碼的值設定為環境變數:AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET

若要向 AAD 進行驗證,您必須先 npm 安裝 @azure/identity。 設定之後,您可以選擇要使用的 @azure/identity認證類型。 例如,DefaultAzureCredential 可用來驗證用戶端。

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

重要概念

可用的功能

此服務提供不同類型的分析。 下表描述目前可用的 API。

特徵 描述
文字分析 API 掃描具有多重嚴重性層級的性內容、暴力、仇恨和自我傷害的文字。
影像分析 API 掃描具有多重嚴重性層級的性內容、暴力、仇恨和自我傷害影像。
文本封鎖清單管理 API 預設的 AI 分類器足以滿足大部分的內容安全性需求。 不過,您可能需要篩選使用案例專屬的字詞。 您可以建立要與文字 API 搭配使用的字詞封鎖清單。

傷害類別

內容安全性可辨識四種不同的令人反感內容類別。

類別 描述
仇恨是指根據該群組的特定區分屬性,攻擊或使用貶義或歧視性語言的任何內容。 這包括不限於種族、種族、國籍、性別認同和表達、性取向、宗教、移民身份、能力地位、個人外觀和身體大小。
性的 性描述與解剖器官和生殖器、浪漫關係、以色情或深情、懷孕、身體性行為描繪的行為有關的內容,包括那些被描繪成攻擊或強迫性暴力行為,反對自己意志的行為——賣淫、色情和虐待行為。
暴力 暴力描述與旨在傷害、傷害、傷害或殺害某人或某物的身體行動相關的內容。 它還包括武器、槍支和相關實體,如製造商、協會、立法和類似專案。
自我傷害 自我傷害描述與故意傷害、傷害或傷害他人身體或自殺的身體動作相關的內容。

分類可以多重標記。 例如,當文字範例通過文字仲裁模型時,它可以分類為「性內容」和「暴力」。

嚴重性層級

服務所套用的每個傷害類別也都隨附嚴重性等級評等。 嚴重性層級旨在指出顯示已標幟內容之後果的嚴重性。

文字:目前版本的文字模型支援 完整 0-7 嚴重性。 根據預設,回應會輸出 4 個值:0、2、4 和 6。 每兩個相鄰層級都會對應至單一層級。 用戶可以在要求中使用 「outputType」,並將其設定為 「8SeverityLevels」,以取得輸出中的 8 個值:0,1,2,3,4,5,6,7。 如需詳細資訊,請參閱 文字內容嚴重性層級定義

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

Image:映像模型的目前版本支援完整 0-7 嚴重性調整 修剪版本。 分類器只會傳回嚴重性 0、2、4 和 6;每兩個相鄰層級都會對應至單一層級。 如需詳細資訊,請參閱 影像內容嚴重性層級定義

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

文本封鎖清單管理

支援下列作業來管理您的文字封鎖清單:

  • 建立或修改封鎖清單
  • 列出所有封鎖清單
  • 依 blocklistName 取得封鎖清單
  • 將 blockItems 新增至封鎖清單
  • 從封鎖清單移除 blockItems
  • 依 blocklistName 列出封鎖清單中的所有 blockItems
  • 依 blockItemId 和 blocklistName 在封鎖清單中取得 blockItem
  • 刪除封鎖清單及其所有 blockItems

您可以設定分析文字時想要使用的封鎖清單,然後您可以從傳回的回應取得封鎖清單比對結果。

例子

下一節提供數個代碼段,涵蓋 TypeScriptJavaScript中一些最常見的 Content Safety 服務工作,包括:

分析文字

分析不含封鎖清單的文字

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

使用封鎖清單分析文字

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

分析影像

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

管理文本封鎖清單

建立或更新文本封鎖清單

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

列出文字封鎖清單

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

取得文本封鎖清單

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

刪除文字封鎖清單

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

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

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

取得 blockItem

TypeScript

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

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

故障排除

伐木

啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 @azure/logger中呼叫 setLogLevel

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

setLogLevel("info");

如需如何啟用記錄的詳細指示,請參閱 @azure/記錄器套件檔。

後續步驟

其他檔

如需 Azure 內容安全性的詳細資訊檔,請參閱 learn.microsoft.com 上的 Azure AI 內容安全性

貢獻

如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。