共用方式為


Azure AI 內容安全適用于 JavaScript 的 REST 用戶端程式庫 - 1.0.0 版

/TypeScript

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

  • 文字分析 API:使用多重嚴重性層級掃描文字中是否有性內容、暴力、惡意和自我傷害。
  • 影像分析 API:使用多重嚴重性層級掃描影像中是否有性內容、暴力、惡意和自我傷害。
  • 文本封鎖清單管理 API:預設 AI 分類器足以滿足大部分的內容安全需求;不過,您可能需要針對使用案例特有的字詞進行畫面篩選。 您可以建立要與文字 API 搭配使用之條款的封鎖清單。

請依賴 我們的 REST 用戶端檔 來使用此程式庫

重要連結:

開始使用

目前支援的環境

  • Node.js 的 LTS 版本

必要條件

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

使用 安裝適用于 JavaScript npm 的 Azure AI 內容安全 REST 用戶端 REST 用戶端程式庫:

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

建立和驗證 ContentSafetyClient

取得端點

您可以使用Azure入口網站或Azure CLI,找到Azure AI 內容安全服務資源的端點:

# 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 金鑰

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

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

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

使用先前稱為 Azure Active Directory (AAD) ) 權杖認證 (Microsoft Entra識別碼建立 ContentSafetyClient

  • 步驟 1:為您的資源啟用Microsoft Entra識別碼,請參閱此認知服務驗證檔以Microsoft Entra識別碼進行驗證。如需為資源啟用 AAD 的步驟。

    主要步驟包括:

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

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

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

重要概念

可用的功能

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

功能 Description
文字分析 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

映射:映射模型的目前版本支援 完整 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 服務工作,包括:

分析文字

分析沒有封鎖清單的文字

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

使用封鎖清單分析文字

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

分析影像

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

管理文字封鎖清單

建立或更新文字封鎖清單

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

列出文字封鎖清單

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

取得文本封鎖清單

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

刪除文字封鎖清單

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

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

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

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

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

疑難排解

記錄

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

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

setLogLevel("info");

如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件

下一步

其他文件

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

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。