JavaScript용 Azure Text Analysis 클라이언트 라이브러리 - 버전 6.0.0-beta.1

Azure Cognitive Service for Language 는 원시 텍스트에 대한 고급 자연어 처리를 제공하는 클라우드 기반 서비스이며 다음과 같은 주요 기능을 포함합니다.

참고: 이 SDK는 Azure Cognitive Service for Language API 버전 2022-04-01-preview를 대상으로 합니다.

  • 언어 검색
  • 감정 분석
  • 핵심 문구 추출
  • 명명된 엔터티 인식
  • 개인 식별 정보 인식
  • 엔터티 연결
  • 의료 분석
  • 추출 요약
  • 사용자 지정 엔터티 인식
  • 사용자 지정 문서 분류
  • 문서당 여러 작업 지원

클라이언트 라이브러리를 사용하여 다음을 수행할 수 있습니다.

  • 어떤 언어 입력 텍스트가 쓰여지는지 검색합니다.
  • 원시 텍스트를 분석하여 긍정적 또는 부정적인 감정에 대한 단서를 분석하여 고객이 브랜드 또는 토픽에 대해 어떻게 생각하는지 결정합니다.
  • 자동으로 핵심 구를 추출하여 요점을 빠르게 파악합니다.
  • 텍스트의 엔터티를 사람, 장소, 조직, 날짜/시간, 수량, 백분율, 통화, 의료 관련 등으로 식별하고 분류합니다.
  • 위의 여러 작업을 한 번에 수행합니다.

주요 링크:

시작

현재 지원되는 환경

자세한 내용은 지원 정책을 참조하세요.

필수 구성 요소

Azure CLI를 사용하는 경우 및 <your-resource-name> 를 고유한 이름으로 바꿉 <your-resource-group-name> 니다.

az cognitiveservices account create --kind TextAnalytics --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --location <your-location>

@azure/ai-text-analytics 패키지를 설치합니다.

를 사용하여 JavaScript용 Azure 텍스트 분석 클라이언트 라이브러리를 npm설치합니다.

npm install @azure/ai-text-analytics

TextAnalysisClient 만들기 및 인증

언어 API에 액세스하는 클라이언트 개체를 만들려면 언어 리소스 credential및 의 이 필요합니다endpoint. 텍스트 분석 클라이언트는 Azure Active Directory 자격 증명 또는 API 키 자격 증명을 사용하여 인증할 수 있습니다.

Azure Portal에서 또는 아래 AzureCLI 코드 조각을 사용하여 언어 리소스에 대한 엔드포인트를 찾을 수 있습니다.

az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "properties.endpoint"

API 키 사용

Azure Portal을 사용하여 언어 리소스를 찾아 API 키를 검색하거나 아래 Azure CLI 코드 조각을 사용합니다.

참고: 경우에 따라 API 키를 "구독 키" 또는 "구독 API 키"라고 합니다.

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

API 키와 엔드포인트가 있으면 다음과 같이 클래스를 AzureKeyCredential 사용하여 클라이언트를 인증할 수 있습니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

Azure Active Directory 자격 증명 사용

클라이언트 API 키 인증은 대부분의 예제에서 사용되지만 Azure ID 라이브러리를 사용하여 Azure Active Directory로 인증할 수도 있습니다. 아래 표시된 DefaultAzureCredential 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용하려면 패키지를 설치 @azure/identity 하세요.

npm install @azure/identity

또한 서비스 주체에 역할을 할당하여 새 AAD 애플리케이션"Cognitive Services User" 등록하고 언어에 대한 액세스 권한을 부여해야 합니다(참고: 와 같은 "Owner" 다른 역할은 필요한 권한을 부여하지 않으며 예제 및 샘플 코드를 실행하는 데만 "Cognitive Services User" 충분합니다).

AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수로 설정합니다. AZURE_CLIENT_ID, , AZURE_TENANT_IDAZURE_CLIENT_SECRET.

const { TextAnalysisClient } = require("@azure/ai-text-analytics");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new TextAnalysisClient("<endpoint>", new DefaultAzureCredential());

주요 개념

TextAnalysisClient

TextAnalysisClient 는 텍스트 분석 클라이언트 라이브러리를 사용하는 개발자를 위한 기본 인터페이스입니다. 이 클라이언트 개체의 메서드를 탐색하여 액세스할 수 있는 언어 서비스의 다양한 기능을 이해합니다.

입력

문서는 언어 서비스의 예측 모델에서 분석할 단일 입력 단위를 나타냅니다. 에 대한 TextAnalysisClient 작업은 일괄 처리로 분석할 입력 컬렉션을 사용합니다. 작업 메서드에는 입력을 문자열로 표시하거나 연결된 메타데이터가 있는 개체로 나타낼 수 있는 오버로드가 있습니다.

예를 들어 각 문서를 배열의 문자열로 전달할 수 있습니다(예: ).

const documents = [
  "I hated the movie. It was so slow!",
  "The movie made it into my top ten favorites.",
  "What a great movie!",
];

또는 항목별 문서 id 또는 languagecountryHint/를 전달하려는 경우 작업에 따라 또는 목록 TextDocumentInputDetectLanguageInput 으로 제공될 수 있습니다.

const textDocumentInputs = [
  { id: "1", language: "en", text: "I hated the movie. It was so slow!" },
  { id: "2", language: "en", text: "The movie made it into my top ten favorites." },
  { id: "3", language: "en", text: "What a great movie!" },
];

문서 길이 제한, 최대 일괄 처리 크기 및 지원되는 텍스트 인코딩을 포함하여 입력에 대한 서비스 제한을 참조하세요.

반환 값

단일 문서에 해당하는 반환 값은 성공적인 결과 또는 오류 개체입니다. 각 TextAnalysisClient 메서드는 인덱스별 입력에 해당하는 다른 유형의 결과 및 오류 배열을 반환합니다. 텍스트 입력과 그 결과는 입력 및 결과 컬렉션에서 동일한 인덱스를 갖습니다.

와 같은 SentimentAnalysisResult결과는 단일 텍스트 입력에 대한 예측 또는 예측을 포함하는 언어 작업의 결과입니다. 작업의 결과 형식에는 입력 문서 및 처리 방법에 대한 정보가 선택적으로 포함될 수도 있습니다.

오류 개체인 TextAnalysisErrorResult는 문서를 처리하는 동안 서비스에 오류가 발생했으며 오류에 대한 정보가 포함되어 있음을 나타냅니다.

문서 오류 처리

작업에서 반환된 컬렉션에서 오류는 오류가 발생한 경우 내부 TextAnalysisError 개체를 포함하는 속성의 error 존재로 인해 성공한 응답과 구별됩니다. 성공적인 결과 개체의 경우 이 속성은 항상undefined 입니다.

예를 들어 모든 오류를 필터링하려면 다음 filter을 사용할 수 있습니다.

const results = await client.analyze("SentimentAnalysis", documents);
const onlySuccessful = results.filter((result) => result.error === undefined);

참고: TypeScript 사용자는 가 구성에서 로 설정된 true 경우 compilerOptions.strictNullChecks 결과 및 오류 개체의 더 나은 형식 검사를 활용할 수 있습니다tsconfig.json. 다음은 그 예입니다.

const [result] = await client.analyze("SentimentAnalysis", ["Hello world!"]);

if (result.error !== undefined) {
  // In this if block, TypeScript will be sure that the type of `result` is
  // `TextAnalysisError` if compilerOptions.strictNullChecks is enabled in
  // the tsconfig.json

  console.log(result.error);
}

감정 분석

텍스트의 감정을 분석하여 문장별 감정 분석 및 신뢰도 점수를 포함하여 양수, 부정, 중립 또는 혼합인지 확인합니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "I did not like the restaurant. The food was too spicy.",
  "The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
  "The food was yummy. :)",
];

async function main() {
  const results = await client.analyze("SentimentAnalysis", documents);

  for (const result of results) {
    if (result.error === undefined) {
      console.log("Overall sentiment:", result.sentiment);
      console.log("Scores:", result.confidenceScores);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

NLP(자연어 처리)의 측면 기반 감정 분석이라고도 하는 제품/서비스의 측면과 관련된 의견에 대한 보다 세분화된 정보를 얻으려면 여기에서 오피니언 마이닝이 있는 감정 분석에 대한 샘플을 참조 하세요.

엔터티 인식

텍스트의 엔터티를 사람, 장소, 조직, 날짜/시간, 수량, 통화 등으로 인식하고 분류합니다.

language 매개 변수는 선택 사항입니다. 지정하지 않으면 기본 영어 모델이 사용됩니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "Jeff bought three dozen eggs because there was a 50% discount.",
];

async function main() {
  const results = await client.analyze("EntityRecognition", documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

PII 엔터티 인식

사회 보장 번호, 은행 계좌 정보, 신용 카드 번호 등과 같은 텍스트에서 PII(개인 식별 정보)를 인식하기 위한 별도의 작업이 있습니다. 사용법은 위의 표준 엔터티 인식과 매우 유사합니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");
const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));
const documents = [
  "The employee's SSN is 555-55-5555.",
  "The employee's phone number is (555) 555-5555.",
];
async function main() {
  const results = await client.analyze("PiiEntityRecognition", documents, "en");
  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized PII entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}
main();

엔터티 연결

"연결된" 엔터티는 기술 자료 있는 엔터티입니다(예: Wikipedia). 이 EntityLinking 작업은 참조할 가능성이 있는 기술 자료 항목을 결정하여 엔터티를 명확하게 구분할 수 있습니다(예: 텍스트 조각에서 "Mars"라는 단어가 행성을 참조하거나 로마 전쟁의 신을 참조함). 연결된 엔터티에는 엔터티의 정의를 제공하는 기술 자료 연결된 URL이 포함되어 있습니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product.",
];

async function main() {
  const results = await client.analyze("EntityLinking", documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized linked entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.name, "(URL:", entity.url, ", Source:", entity.dataSource, ")");
        for (const match of entity.matches) {
          console.log(
            "  Occurrence:",
            '"' + match.text + '"',
            "(Score:",
            match.confidenceScore,
            ")"
          );
        }
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

핵심 문구 추출

핵심 구 추출은 문서의 주요 대화 지점을 식별합니다. 예를 들어 "음식이 맛 있었으며 훌륭한 직원이 있었습니다"라는 입력 텍스트가 있는 경우 서비스는 "음식" 및 "훌륭한 직원"을 반환합니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "I need to take my cat to the veterinarian.",
  "I will travel to South America in the summer.",
];

async function main() {
  const results = await client.analyze("KeyPhraseExtraction", documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Extracted key phrases for input", result.id, "--");
      console.log(result.keyPhrases);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

언어 검색

텍스트 조각의 언어를 결정합니다.

매개 변수는 countryHint 선택 사항이지만 원본 국가가 알려진 경우 서비스가 올바른 출력을 제공하는 데 도움이 될 수 있습니다. 제공된 경우 ISO-3166 Alpha-2 두 글자 국가 코드(예: 미국 "us" 또는 일본 "jp") 또는 값"none"으로 설정해야 합니다. 매개 변수가 제공되지 않으면 기본 "us" (미국) 모델이 사용됩니다. 문서의 원본 국가를 모르는 경우 매개 변수 "none" 를 사용해야 하며 언어 서비스는 알 수 없는 원본 국가에 대해 조정된 모델을 적용합니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "This is written in English.",
  "Il documento scritto in italiano.",
  "Dies ist in deutscher Sprache verfasst.",
];

async function main() {
  const results = await client.analyze("LanguageDetection", documents, "none");

  for (const result of results) {
    if (result.error === undefined) {
      const { primaryLanguage } = result;
      console.log(
        "Input #",
        result.id,
        "identified as",
        primaryLanguage.name,
        "( ISO6391:",
        primaryLanguage.iso6391Name,
        ", Score:",
        primaryLanguage.confidenceScore,
        ")"
      );
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

의료 분석

의료 분석은 의료 엔터티를 식별합니다. 예를 들어 입력 텍스트 "처방된 100mg 이부프로펜, 매일 두 번 촬영"이 제공되면 서비스는 복용량으로 분류된 "100mg", "ibuprofen"을 MedicationName으로, "매일 두 번"을 Frequency로 반환합니다.

const {
  AnalyzeBatchAction,
  AzureKeyCredential,
  TextAnalysisClient,
} = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Prescribed 100mg ibuprofen, taken twice daily.",
  "Patient does not suffer from high blood pressure.",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "Healthcare",
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  const results = await poller.pollUntilDone();
  for await (const actionResult of results) {
    if (actionResult.kind !== "Healthcare") {
      throw new Error(`Expected a healthcare results but got: ${actionResult.kind}`);
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log("\tRecognized Entities:");
      for (const entity of result.entities) {
        console.log(`\t- Entity "${entity.text}" of type ${entity.category}`);
        if (entity.dataSources.length > 0) {
          console.log("\t and it can be referenced in the following data sources:");
          for (const ds of entity.dataSources) {
            console.log(`\t\t- ${ds.name} with Entity ID: ${ds.entityId}`);
          }
        }
      }
    }
  }
}

main();

추출 요약

추출 요약은 자신이 속한 문서를 요약하는 문장을 식별합니다.

const {
  AnalyzeBatchAction,
  AzureKeyCredential,
  TextAnalysisClient,
} = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Prescribed 100mg ibuprofen, taken twice daily.",
  "Patient does not suffer from high blood pressure.",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "ExtractiveSummarization",
      maxSentenceCount: 2,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  const results = await poller.pollUntilDone();

  for await (const actionResult of results) {
    if (actionResult.kind !== "ExtractiveSummarization") {
      throw new Error(`Expected extractive summarization results but got: ${actionResult.kind}`);
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log("Summary:");
      console.log(result.sentences.map((sentence) => sentence.text).join("\n"));
    }
  }
}

main();

사용자 지정 엔터티 인식

Azure Language Studio를 사용하여 빌드된 사용자 지정 엔터티 검색 모델을 사용하여 텍스트의 엔터티를 인식하고 엔터티로 분류합니다.

const {
  AnalyzeBatchAction,
  AzureKeyCredential,
  TextAnalysisClient,
} = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "We love this trail and make the trip every year. The views are breathtaking and well worth the hike! Yesterday was foggy though, so we missed the spectacular views. We tried again today and it was amazing. Everyone in my family liked the trail although it was too challenging for the less athletic among us.",
  "Last week we stayed at Hotel Foo to celebrate our anniversary. The staff knew about our anniversary so they helped me organize a little surprise for my partner. The room was clean and with the decoration I requested. It was perfect!",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "CustomEntityRecognition",
      deploymentName,
      projectName,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  for await (const actionResult of results) {
    if (actionResult.kind !== "CustomEntityRecognition") {
      throw new Error(`Expected a CustomEntityRecognition results but got: ${actionResult.kind}`);
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log("\tRecognized Entities:");
      for (const entity of result.entities) {
        console.log(`\t- Entity "${entity.text}" of type ${entity.category}`);
      }
    }
  }
}

main();

사용자 지정 단일 레이블 분류

Azure Language Studio를 사용하여 빌드된 사용자 지정 단일 레이블 모델을 사용하여 문서를 분류합니다.

const { TextAnalysisClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "The plot begins with a large group of characters where everyone thinks that the two main ones should be together but foolish things keep them apart. Misunderstandings, miscommunication, and confusion cause a series of humorous situations.",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "CustomSingleLabelClassification",
      deploymentName,
      projectName,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  const results = await poller.pollUntilDone();

  for await (const actionResult of results) {
    if (actionResult.kind !== "CustomSingleLabelClassification") {
      throw new Error(
        `Expected a CustomSingleLabelClassification results but got: ${actionResult.kind}`
      );
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log(`\tClassification: ${result.classification.category}`);
    }
  }
}

main();

사용자 지정 다중 레이블 분류

Azure Language Studio를 사용하여 빌드된 사용자 지정 다중 레이블 모델을 사용하여 문서를 분류합니다.

const {
  AnalyzeBatchAction,
  AzureKeyCredential,
  TextAnalysisClient,
} = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "The plot begins with a large group of characters where everyone thinks that the two main ones should be together but foolish things keep them apart. Misunderstandings, miscommunication, and confusion cause a series of humorous situations.",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "CustomMultiLabelClassification",
      deploymentName,
      projectName,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  const results = await poller.pollUntilDone();

  for await (const actionResult of results) {
    if (actionResult.kind !== "CustomMultiLabelClassification") {
      throw new Error(
        `Expected a CustomMultiLabelClassification results but got: ${actionResult.kind}`
      );
    }
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    for (const result of actionResult.results) {
      console.log(`- Document ${result.id}`);
      if (result.error) {
        const { code, message } = result.error;
        throw new Error(`Unexpected error (${code}): ${message}`);
      }
      console.log(`\tClassification:`);
      for (const classification of result.classifications) {
        console.log(`\t\t-category: ${classification.category}`);
      }
    }
  }
}

main();

작업 일괄 처리

하나의 서비스 요청에서 각 입력 문서에 여러 작업을 적용합니다.

const {
  AnalyzeBatchAction,
  AzureKeyCredential,
  TextAnalysisClient,
} = require("@azure/ai-text-analytics");

const client = new TextAnalysisClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "The employee's SSN is 555-55-5555.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product.",
];

async function main() {
  const actions: AnalyzeBatchAction[] = [
    {
      kind: "EntityRecognition",
      modelVersion: "latest",
    },
    {
      kind: "PiiEntityRecognition",
      modelVersion: "latest",
    },
    {
      kind: "KeyPhraseExtraction",
      modelVersion: "latest",
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");
  const actionResults = await poller.pollUntilDone();
  for await (const actionResult of actionResults) {
    if (actionResult.error) {
      const { code, message } = actionResult.error;
      throw new Error(`Unexpected error (${code}): ${message}`);
    }
    switch (actionResult.kind) {
      case "KeyPhraseExtraction": {
        for (const doc of actionResult.results) {
          console.log(`- Document ${doc.id}`);
          if (!doc.error) {
            console.log("\tKey phrases:");
            for (const phrase of doc.keyPhrases) {
              console.log(`\t- ${phrase}`);
            }
          } else {
            console.error("\tError:", doc.error);
          }
        }
        break;
      }
      case "EntityRecognition": {
        for (const doc of actionResult.results) {
          console.log(`- Document ${doc.id}`);
          if (!doc.error) {
            console.log("\tEntities:");
            for (const entity of doc.entities) {
              console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
            }
          } else {
            console.error("\tError:", doc.error);
          }
        }
        break;
      }
      case "PiiEntityRecognition": {
        for (const doc of actionResult.results) {
          console.log(`- Document ${doc.id}`);
          if (!doc.error) {
            console.log("\tPii Entities:");
            for (const entity of doc.entities) {
              console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
            }
          } else {
            console.error("\tError:", doc.error);
          }
        }
        break;
      }
      default: {
        throw new Error(`Unexpected action results: ${actionResult.kind}`);
      }
    }
  }
}

main();

문제 해결

로깅

로깅을 사용하도록 설정하면 실패에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info로 설정합니다. 또는 @azure/logger에서 setLogLevel을 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

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

setLogLevel("info");

로그를 사용하는 방법에 대한 자세한 내용은 @azure/logger package docs를 참조하세요.

다음 단계

이 라이브러리를 사용하는 방법에 대한 자세한 예제는 샘플 디렉터리를 참조하세요.

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions