Pustaka klien Azure Text Analysis untuk JavaScript - versi 6.0.0-beta.1

Azure Cognitive Service for Language adalah layanan berbasis cloud yang menyediakan pemrosesan bahasa alami tingkat lanjut melalui teks mentah, dan mencakup fitur utama berikut:

Catatan: SDK ini menargetkan Azure Cognitive Service for Language API versi 2022-04-01-preview.

  • Deteksi Bahasa
  • Analisis Sentimen
  • Ekstraksi Frasa Kunci
  • Pengenalan Entitas
  • Pengenalan Informasi Pengidentifikasi Pribadi
  • Penautan Entitas
  • Analisis Layanan Kesehatan
  • Ringkasan Ekstraktif
  • Pengenalan Entitas Kustom
  • Klasifikasi Dokumen Kustom
  • Mendukung Beberapa Tindakan Per Dokumen

Gunakan pustaka klien untuk:

  • Deteksi teks input bahasa apa yang ditulis.
  • Tentukan pendapat pelanggan tentang merek atau topik Anda dengan menganalisis teks mentah untuk petunjuk tentang sentimen positif atau negatif.
  • Ekstrak frasa kunci secara otomatis untuk mengidentifikasi poin utama dengan cepat.
  • Identifikasi dan kategorikan entitas dalam teks Anda sebagai orang, tempat, organisasi, tanggal/waktu, jumlah, persentase, mata uang, spesifik layanan kesehatan, dan banyak lagi.
  • Lakukan beberapa tugas di atas sekaligus.

Tautan utama:

Memulai

Lingkungan yang didukung saat ini

Lihat kebijakan dukungan kami untuk detail selengkapnya.

Prasyarat

Jika Anda menggunakan Azure CLI, ganti <your-resource-group-name> dan <your-resource-name> dengan nama unik Anda sendiri:

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

Pasang paket @azure/ai-text-analytics

Instal pustaka klien Azure Text Analysis untuk JavaScript dengan npm:

npm install @azure/ai-text-analytics

Membuat dan mengautentikasi TextAnalysisClient

Untuk membuat objek klien untuk mengakses LANGUAGE API, Anda memerlukan endpoint sumber daya Bahasa dan credential. Klien Analisis Teks dapat menggunakan kredensial Azure Active Directory atau kredensial kunci API untuk mengautentikasi.

Anda dapat menemukan titik akhir untuk sumber daya Bahasa Anda baik di Portal Microsoft Azure atau dengan menggunakan cuplikan Azure CLI di bawah ini:

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

Menggunakan Kunci API

Gunakan Portal Microsoft Azure untuk menelusuri ke sumber daya Bahasa Anda dan mengambil kunci API, atau gunakan cuplikan Azure CLI di bawah ini:

Catatan: Terkadang kunci API disebut sebagai "kunci langganan" atau "kunci API langganan."

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

Setelah Anda memiliki kunci API dan titik akhir, Anda dapat menggunakan AzureKeyCredential kelas untuk mengautentikasi klien sebagai berikut:

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

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

Menggunakan Kredensial Azure Active Directory

Autentikasi kunci API klien digunakan di sebagian besar contoh, tetapi Anda juga dapat mengautentikasi dengan Azure Active Directory menggunakan pustaka Azure Identity. Untuk menggunakan penyedia DefaultAzureCredential yang ditunjukkan di bawah ini, atau penyedia kredensial lain yang disediakan dengan Azure SDK, instal @azure/identity paket:

npm install @azure/identity

Anda juga perlu mendaftarkan aplikasi AAD baru dan memberikan akses ke Bahasa dengan menetapkan "Cognitive Services User" peran ke perwakilan layanan Anda (catatan: peran lain seperti "Owner" tidak akan memberikan izin yang diperlukan, hanya "Cognitive Services User" cukup untuk menjalankan contoh dan kode sampel).

Atur nilai ID klien, ID penyewa, dan rahasia klien aplikasi AAD sebagai variabel lingkungan: 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());

Konsep utama

TextAnalysisClient

TextAnalysisClient adalah antarmuka utama untuk pengembang yang menggunakan pustaka klien Analisis Teks. Jelajahi metode pada objek klien ini untuk memahami berbagai fitur layanan Bahasa yang dapat Anda akses.

Input

Dokumen mewakili satu unit input yang akan dianalisis oleh model prediktif dalam layanan Bahasa. Operasi pada TextAnalysisClient mengambil kumpulan input untuk dianalisis sebagai batch. Metode operasi memiliki kelebihan beban yang memungkinkan input direpresentasikan sebagai string, atau sebagai objek dengan metadata terlampir.

Misalnya, setiap dokumen dapat diteruskan sebagai string dalam array, misalnya.

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

atau, jika Anda ingin meneruskan dokumen id per item atau languagecountryHint/, dokumen tersebut dapat diberikan sebagai daftar TextDocumentInput atau DetectLanguageInput tergantung pada operasi;

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!" },
];

Lihat batasan layanan untuk input, termasuk batas panjang dokumen, ukuran batch maksimum, dan pengodean teks yang didukung.

Tampilkan Nilai

Nilai yang dikembalikan yang terkait dengan satu dokumen adalah hasil yang berhasil atau objek kesalahan. Setiap TextAnalysisClient metode mengembalikan array hasil dan kesalahan heterogen yang sesuai dengan input menurut indeks. Input teks dan hasilnya akan memiliki indeks yang sama dalam kumpulan input dan hasil.

Hasilnya, seperti SentimentAnalysisResult, adalah hasil dari operasi Bahasa, yang berisi prediksi atau prediksi tentang input teks tunggal. Jenis hasil operasi juga dapat secara opsional menyertakan informasi tentang dokumen input dan cara pemrosesannya.

Objek kesalahan , TextAnalysisErrorResult, menunjukkan bahwa layanan mengalami kesalahan saat memproses dokumen dan berisi informasi tentang kesalahan.

Penanganan Kesalahan Dokumen

Dalam koleksi yang dikembalikan oleh operasi, kesalahan dibedakan dari respons yang berhasil dengan keberadaan error properti , yang berisi objek dalam TextAnalysisError jika terjadi kesalahan. Untuk objek hasil yang berhasil, properti ini selaluundefined.

Misalnya, untuk memfilter semua kesalahan, Anda dapat menggunakan yang berikut:filter

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

Catatan: Pengguna TypeScript dapat memperoleh manfaat dari pemeriksaan jenis objek hasil dan kesalahan yang lebih baik jika compilerOptions.strictNullChecks diatur ke true dalam tsconfig.json konfigurasi. Contohnya:

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

Contoh

Analisis Sentimen

Analisis sentimen teks untuk menentukan apakah itu positif, negatif, netral, atau campuran, termasuk analisis sentimen per kalimat dan skor keyakinan.

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

Untuk mendapatkan informasi yang lebih terperinci tentang pendapat yang terkait dengan aspek produk/layanan, juga dikenal sebagai Analisis Sentimen Berbasis Aspek dalam Pemrosesan Bahasa Alami (NLP), lihat sampel analisis sentimen dengan penggalian opini di sini.

Pengenalan Entitas

Mengenali dan mengategorikan entitas dalam teks sebagai orang, tempat, organisasi, tanggal/waktu, jumlah, mata uang, dll.

Parameter language bersifat opsional. Jika tidak ditentukan, model bahasa Inggris default akan digunakan.

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

Pengenalan Entitas PII

Ada tindakan terpisah untuk mengenali Informasi Pengidentifikasi Pribadi (PII) dalam teks seperti Nomor Jaminan Sosial, informasi rekening bank, nomor kartu kredit, dll. Penggunaannya sangat mirip dengan pengenalan entitas standar di atas:

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

Penautan Entitas

Entitas "Tertaut" adalah entitas yang ada dalam Pangkalan Pengetahuan (seperti Wikipedia). Tindakan ini EntityLinking dapat membedakan entitas dengan menentukan entri mana dalam Pangkalan Pengetahuan yang mungkin mereka rujuk (misalnya, dalam sepotong teks, apakah kata "Mars" merujuk ke planet ini, atau dewa perang Romawi). Entitas tertaut berisi URL terkait ke Pangkalan Pengetahuan yang menyediakan definisi entitas.

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

Ekstraksi Frasa Kunci

Ekstraksi Frasa Kunci mengidentifikasi poin pembicaraan utama dalam dokumen. Misalnya, diberi teks input "Makanannya lezat dan ada staf yang luar biasa", layanan mengembalikan "makanan" dan "staf yang luar biasa".

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

Deteksi Bahasa

Tentukan bahasa sepotong teks.

Parameter countryHint bersifat opsional, tetapi dapat membantu layanan dalam memberikan output yang benar jika negara asal diketahui. Jika disediakan, kode negara dua huruf ISO-3166 Alpha-2 harus diatur ke ISO-3166 Alpha-2 (seperti "kami" untuk Amerika Serikat atau "jp" untuk Jepang) atau ke nilai "none". Jika parameter tidak disediakan, maka model default "us" (Amerika Serikat) akan digunakan. Jika Anda tidak tahu negara asal dokumen, maka parameter "none" harus digunakan, dan layanan Bahasa akan menerapkan model yang disetel untuk negara asal yang tidak diketahui.

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

Analisis Layanan Kesehatan

Analisis layanan kesehatan mengidentifikasi entitas layanan kesehatan. Misalnya, diberi teks input "Diresepkan 100mg ibuprofen, diambil dua kali sehari", layanan mengembalikan "100mg" yang dikategorikan sebagai Dosis, "ibuprofen" sebagai MedicationName, dan "dua kali sehari" sebagai Frekuensi.

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

Ringkasan Ekstraktif

Ringkasan ekstraktif mengidentifikasi kalimat yang meringkas artikel miliknya.

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

Pengenalan Entitas Kustom

Mengenali dan mengategorikan entitas dalam teks sebagai entitas menggunakan model deteksi entitas kustom yang dibuat menggunakan 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();

Klasifikasi Label Tunggal Kustom

Mengklasifikasikan dokumen menggunakan model label tunggal kustom yang dibuat menggunakan 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();

Klasifikasi Multi-label Kustom

Mengklasifikasikan dokumen menggunakan model multi-label kustom yang dibuat menggunakan 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();

Batching Tindakan

Menerapkan beberapa tindakan pada setiap dokumen input dalam satu permintaan layanan.

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

Pemecahan Masalah

Pencatatan

Mengaktifkan pengelogan dapat membantu menemukan informasi yang berguna tentang kegagalan. Untuk melihat log permintaan dan respons HTTP, atur variabel lingkungan AZURE_LOG_LEVEL ke info. Atau, pengelogan dapat diaktifkan saat runtime dengan memanggil setLogLevel di @azure/logger:

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

setLogLevel("info");

Untuk instruksi lebih rinci tentang cara mengaktifkan log, Anda dapat melihat dokumen paket @azure/pencatat.

Langkah berikutnya

Silakan lihat direktori sampel untuk contoh terperinci tentang cara menggunakan pustaka ini.

Berkontribusi

Jika Anda ingin berkontribusi pada pustaka ini, baca panduan berkontribusi untuk mempelajari selengkapnya tentang cara membuat dan menguji kode.

Tayangan