クイックスタート: ドキュメント要約と会話要約の使用

重要

プレビュー リージョンであるスウェーデン中部では、GPT モデルに基づいた最新かつ常に進化し続けている LLM の微調整の手法を確認できます。 スウェーデン中部リージョンの Langauge リソースを使用してそれらをぜひお試しください。

会話の概要作成は、以下を使用した場合にのみ利用可能です。

  • REST API
  • Python
  • C#

このクイックスタートでは、.NET 用のクライアント ライブラリを使用してテキスト概要作成アプリケーションを作成します。 次の例では、ドキュメントまたはテキスト ベースのカスタマー サービスの会話を要約できる C# アプリケーションを作成します。

ヒント

Language Studio を使用すると、コードを書かなくてもドキュメントの要約を試すことができます。

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • Visual Studio IDE
  • Azure サブスクリプションを入手したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
    • 対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (Free F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
  • 分析フィーチャーを使用するには、標準 (S) 価格レベルのLanguageリソースが必要です。

設定

環境変数を作成する

API 要求を送信するには、アプリケーションを認証する必要があります。 運用環境では、資格情報を安全に保存してアクセスできる方法を使用してください。 この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。

ヒント

キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。

言語リソース キーの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。

  1. LANGUAGE_KEY 環境変数を設定するには、your-key をリソースのキーの 1 つに置き換えます。
  2. LANGUAGE_ENDPOINT 環境変数を設定するには、your-endpoint をリソースのエンドポイントに置き換えます。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

現在実行中のコンソールで環境変数のみにアクセスする必要がある場合は、環境変数を setx の代わりに set に設定できます。

実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を追加した後で再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

新しい .NET Core アプリを作成する

Visual Studio IDE を使用して新しい .NET Core コンソール アプリを作成します。 1 つの C# ソース ファイル (program.cs) を含んだ "Hello World" プロジェクトを作成します。

ソリューション エクスプローラーでソリューションを右クリックし、 [NuGet パッケージの管理] を選択して、クライアント ライブラリをインストールします。 パッケージ マネージャーが開いたら、 [参照] を選択して Azure.AI.TextAnalytics を検索します。 [プレリリースを含める] がオンになっていることを確認します。 バージョン 5.3.0 を選択し、 [インストール] を選択します。 パッケージ マネージャー コンソールを使用してもかまいません。

コードの例

次のコードを program.cs ファイルにコピーします。 次にコードを実行します。

重要

Azure Portal にアクセスします。 「前提条件」セクションで作成した Language リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [キーとエンドポイント] ページの [リソース管理] に移動することで確認できます。

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace Example
{
    class Program
    {
        // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
        static string languageKey = Environment.GetEnvironmentVariable("LANGUAGE_KEY");
        static string languageEndpoint = Environment.GetEnvironmentVariable("LANGUAGE_ENDPOINT");

        private static readonly AzureKeyCredential credentials = new AzureKeyCredential(languageKey);
        private static readonly Uri endpoint = new Uri(languageEndpoint);

        // Example method for summarizing text
        static async Task TextSummarizationExample(TextAnalyticsClient client)
        {
            string document = @"The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. 
                These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. 
                They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. 
                Extractive summarization supports several languages. It is based on pretrained multilingual transformer models, part of our quest for holistic representations. 
                It draws its strength from transfer learning across monolingual and harness the shared nature of languages to produce models of improved quality and efficiency." ;
        
            // Prepare analyze operation input. You can add multiple documents to this list and perform the same
            // operation to all of them.
            var batchInput = new List<string>
            {
                document
            };
        
            TextAnalyticsActions actions = new TextAnalyticsActions()
            {
                ExtractSummaryActions = new List<ExtractSummaryAction>() { new ExtractSummaryAction() }
            };
        
            // Start analysis process.
            AnalyzeActionsOperation operation = await client.StartAnalyzeActionsAsync(batchInput, actions);
            await operation.WaitForCompletionAsync();
            // View operation status.
            Console.WriteLine($"AnalyzeActions operation has completed");
            Console.WriteLine();
        
            Console.WriteLine($"Created On   : {operation.CreatedOn}");
            Console.WriteLine($"Expires On   : {operation.ExpiresOn}");
            Console.WriteLine($"Id           : {operation.Id}");
            Console.WriteLine($"Status       : {operation.Status}");
        
            Console.WriteLine();
            // View operation results.
            await foreach (AnalyzeActionsResult documentsInPage in operation.Value)
            {
                IReadOnlyCollection<ExtractSummaryActionResult> summaryResults = documentsInPage.ExtractSummaryResults;
        
                foreach (ExtractSummaryActionResult summaryActionResults in summaryResults)
                {
                    if (summaryActionResults.HasError)
                    {
                        Console.WriteLine($"  Error!");
                        Console.WriteLine($"  Action error code: {summaryActionResults.Error.ErrorCode}.");
                        Console.WriteLine($"  Message: {summaryActionResults.Error.Message}");
                        continue;
                    }
        
                    foreach (ExtractSummaryResult documentResults in summaryActionResults.DocumentsResults)
                    {
                        if (documentResults.HasError)
                        {
                            Console.WriteLine($"  Error!");
                            Console.WriteLine($"  Document error code: {documentResults.Error.ErrorCode}.");
                            Console.WriteLine($"  Message: {documentResults.Error.Message}");
                            continue;
                        }
        
                        Console.WriteLine($"  Extracted the following {documentResults.Sentences.Count} sentence(s):");
                        Console.WriteLine();
        
                        foreach (SummarySentence sentence in documentResults.Sentences)
                        {
                            Console.WriteLine($"  Sentence: {sentence.Text}");
                            Console.WriteLine();
                        }
                    }
                }
            }
        
        }

        static async Task Main(string[] args)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            await TextSummarizationExample(client);
        }
    }
}

出力

AnalyzeActions operation has completed

Created On   : 9/16/2021 8:04:27 PM +00:00
Expires On   : 9/17/2021 8:04:27 PM +00:00
Id           : 2e63fa58-fbaa-4be9-a700-080cff098f91
Status       : succeeded

Extracted the following 3 sentence(s):

Sentence: The extractive summarization feature in uses natural language processing techniques to locate key sentences in an unstructured text document.

Sentence: This feature is provided as an API for developers.

Sentence: They can use it to build intelligent solutions based on the relevant information extracted to support various use cases.

リファレンス ドキュメント | その他のサンプル | パッケージ (Maven) | ライブラリのソース コード

このクイックスタートでは、Java 用のクライアント ライブラリを使用してテキスト概要作成アプリケーションを作成します。 次の例では、ドキュメントを要約できる Java アプリケーションを作成します。

ヒント

Language Studio を使用すると、コードを書かなくてもドキュメントの要約を試すことができます。

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • Java Development Kit (JDK) バージョン 8 以降
  • Azure サブスクリプションを入手したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
    • 対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (Free F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
  • 分析フィーチャーを使用するには、標準 (S) 価格レベルのLanguageリソースが必要です。

設定

クライアント ライブラリを追加する

好みの IDE または開発環境で Maven プロジェクトを作成します。 次に、自分のプロジェクトの pom.xml ファイルに次の依存関係を追加します。 その他のビルド ツールの実装構文はオンラインで確認できます。

<dependencies>
     <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.3.0</version>
    </dependency>
</dependencies>

環境変数を作成する

API 要求を送信するには、アプリケーションを認証する必要があります。 運用環境では、資格情報を安全に保存してアクセスできる方法を使用してください。 この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。

ヒント

キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。

言語リソース キーの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。

  1. LANGUAGE_KEY 環境変数を設定するには、your-key をリソースのキーの 1 つに置き換えます。
  2. LANGUAGE_ENDPOINT 環境変数を設定するには、your-endpoint をリソースのエンドポイントに置き換えます。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

現在実行中のコンソールで環境変数のみにアクセスする必要がある場合は、環境変数を setx の代わりに set に設定できます。

実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を追加した後で再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

コードの例

Example.java という名前で Java ファイルを作成します。 ファイルを開き、下のコードをコピーします。 次にコードを実行します。

重要

Azure Portal にアクセスします。 「前提条件」セクションで作成した Language リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [キーとエンドポイント] ページの [リソース管理] に移動することで確認できます。

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;
import java.util.ArrayList;
import java.util.List;
import com.azure.core.util.polling.SyncPoller;
import com.azure.ai.textanalytics.util.*;

public class Example {

    // This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
    private static String languageKey = System.getenv("LANGUAGE_KEY");
    private static String languageEndpoint = System.getenv("LANGUAGE_ENDPOINT");

    public static void main(String[] args) {
        TextAnalyticsClient client = authenticateClient(languageKey, languageEndpoint);
        summarizationExample(client);
    }
    // Method to authenticate the client object with your key and endpoint
    static TextAnalyticsClient authenticateClient(String key, String endpoint) {
        return new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(key))
                .endpoint(endpoint)
                .buildClient();
    }
    // Example method for summarizing text
    static void summarizationExample(TextAnalyticsClient client) {
        List<String> documents = new ArrayList<>();
        documents.add(
                "The extractive summarization feature uses natural language processing techniques "
                + "to locate key sentences in an unstructured text document. "
                + "These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. "
                + "They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. "
                + "Extractive summarization supports several languages. "
                + "It is based on pretrained multilingual transformer models, part of our quest for holistic representations. "
                + "It draws its strength from transfer learning across monolingual and harness the shared nature of languages "
                + "to produce models of improved quality and efficiency.");
    
        SyncPoller<AnalyzeActionsOperationDetail, AnalyzeActionsResultPagedIterable> syncPoller =
                client.beginAnalyzeActions(documents,
                        new TextAnalyticsActions().setDisplayName("{tasks_display_name}")
                                .setExtractSummaryActions(
                                        new ExtractSummaryAction()),
                        "en",
                        new AnalyzeActionsOptions());
    
        syncPoller.waitForCompletion();
    
        syncPoller.getFinalResult().forEach(actionsResult -> {
            System.out.println("Extractive Summarization action results:");
            for (ExtractSummaryActionResult actionResult : actionsResult.getExtractSummaryResults()) {
                if (!actionResult.isError()) {
                    for (ExtractSummaryResult documentResult : actionResult.getDocumentsResults()) {
                        if (!documentResult.isError()) {
                            System.out.println("\tExtracted summary sentences:");
                            for (SummarySentence summarySentence : documentResult.getSentences()) {
                                System.out.printf(
                                        "\t\t Sentence text: %s, length: %d, offset: %d, rank score: %f.%n",
                                        summarySentence.getText(), summarySentence.getLength(),
                                        summarySentence.getOffset(), summarySentence.getRankScore());
                            }
                        } else {
                            System.out.printf("\tCannot extract summary sentences. Error: %s%n",
                                    documentResult.getError().getMessage());
                        }
                    }
                } else {
                    System.out.printf("\tCannot execute Extractive Summarization action. Error: %s%n",
                            actionResult.getError().getMessage());
                }
            }
        });
    }
}

出力

Extractive Summarization action results:
	Extracted summary sentences:
		 Sentence text: The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document., length: 138, offset: 0, rank score: 1.000000.
		 Sentence text: This feature is provided as an API for developers., length: 50, offset: 206, rank score: 0.510000.
		 Sentence text: Extractive summarization supports several languages., length: 52, offset: 378, rank score: 0.410000.

リファレンス                 ドキュメント | その他の             サンプル | パッケージ (npm) | ライブラリのソース コード

このクイックスタートでは、Node.js 用のクライアント ライブラリを使用してテキスト概要作成アプリケーションを作成します。 次の例では、ドキュメントを要約できる JavaScript アプリケーションを作成します。

ヒント

Language Studio を使用すると、コードを書かなくてもドキュメントの要約を試すことができます。

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • Node.js v16 LTS
  • Azure サブスクリプションを入手したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
    • 対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (Free F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
  • 分析フィーチャーを使用するには、標準 (S) 価格レベルのLanguageリソースが必要です。

設定

環境変数を作成する

API 要求を送信するには、アプリケーションを認証する必要があります。 運用環境では、資格情報を安全に保存してアクセスできる方法を使用してください。 この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。

ヒント

キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。

言語リソース キーの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。

  1. LANGUAGE_KEY 環境変数を設定するには、your-key をリソースのキーの 1 つに置き換えます。
  2. LANGUAGE_ENDPOINT 環境変数を設定するには、your-endpoint をリソースのエンドポイントに置き換えます。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

現在実行中のコンソールで環境変数のみにアクセスする必要がある場合は、環境変数を setx の代わりに set に設定できます。

実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を追加した後で再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

新しい Node.js アプリケーションを作成する

コンソール ウィンドウ (cmd、PowerShell、Bash など) で、ご利用のアプリ用に新しいディレクトリを作成し、そこに移動します。

mkdir myapp 

cd myapp

npm init コマンドを実行し、package.json ファイルを使用して node アプリケーションを作成します。

npm init

クライアント ライブラリをインストールする

npmパッケージをインストールします:

npm install --save @azure/ai-language-text@1.1.0

コードの例

ファイルを開き、下のコードをコピーします。 次にコードを実行します。

重要

Azure Portal にアクセスします。 「前提条件」セクションで作成した Language リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [キーとエンドポイント] ページの [リソース管理] に移動することで確認できます。

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

/**
 * This sample program extracts a summary of two sentences at max from an article.
 * For more information, see the feature documentation: {@link https://learn.microsoft.com/azure/ai-services/language-service/summarization/overview}
 *
 * @summary extracts a summary from an article
 */

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

// Load the .env file if it exists
require("dotenv").config();

// This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
const endpoint = process.env.LANGUAGE_ENDPOINT;
const apiKey = process.env.LANGUAGE_KEY;

const documents = [
  `
           Windows 365 was in the works before COVID-19 sent companies around the world on a scramble to secure solutions to support employees suddenly forced to work from home, but “what really put the firecracker behind it was the pandemic, it accelerated everything,” McKelvey said. She explained that customers were asking, “’How do we create an experience for people that makes them still feel connected to the company without the physical presence of being there?”
           In this new world of Windows 365, remote workers flip the lid on their laptop, bootup the family workstation or clip a keyboard onto a tablet, launch a native app or modern web browser and login to their Windows 365 account. From there, their Cloud PC appears with their background, apps, settings and content just as they left it when they last were last there – in the office, at home or a coffee shop.
           “And then, when you’re done, you’re done. You won’t have any issues around security because you’re not saving anything on your device,” McKelvey said, noting that all the data is stored in the cloud.
           The ability to login to a Cloud PC from anywhere on any device is part of Microsoft’s larger strategy around tailoring products such as Microsoft Teams and Microsoft 365 for the post-pandemic hybrid workforce of the future, she added. It enables employees accustomed to working from home to continue working from home; it enables companies to hire interns from halfway around the world; it allows startups to scale without requiring IT expertise.
           “I think this will be interesting for those organizations who, for whatever reason, have shied away from virtualization. This is giving them an opportunity to try it in a way that their regular, everyday endpoint admin could manage,” McKelvey said.
           The simplicity of Windows 365 won over Dean Wells, the corporate chief information officer for the Government of Nunavut. His team previously attempted to deploy a traditional virtual desktop infrastructure and found it inefficient and unsustainable given the limitations of low-bandwidth satellite internet and the constant need for IT staff to manage the network and infrastructure.
           We didn’t run it for very long,” he said. “It didn’t turn out the way we had hoped. So, we actually had terminated the project and rolled back out to just regular PCs.”
           He re-evaluated this decision after the Government of Nunavut was hit by a ransomware attack in November 2019 that took down everything from the phone system to the government’s servers. Microsoft helped rebuild the system, moving the government to Teams, SharePoint, OneDrive and Microsoft 365. Manchester’s team recruited the Government of Nunavut to pilot Windows 365. Wells was intrigued, especially by the ability to manage the elastic workforce securely and seamlessly.
           “The impact that I believe we are finding, and the impact that we’re going to find going forward, is being able to access specialists from outside the territory and organizations outside the territory to come in and help us with our projects, being able to get people on staff with us to help us deliver the day-to-day expertise that we need to run the government,” he said.
           “Being able to improve healthcare, being able to improve education, economic development is going to improve the quality of life in the communities.”`,
];

async function main() {
  console.log("== Extractive Summarization Sample ==");

  const client = new TextAnalysisClient(endpoint, new AzureKeyCredential(apiKey));
  const actions = [
    {
      kind: "ExtractiveSummarization",
      maxSentenceCount: 2,
    },
  ];
  const poller = await client.beginAnalyzeBatch(actions, documents, "en");

  poller.onProgress(() => {
    console.log(
      `Last time the operation was updated was on: ${poller.getOperationState().modifiedOn}`
    );
  });
  console.log(`The operation was created on ${poller.getOperationState().createdOn}`);
  console.log(`The operation results will expire on ${poller.getOperationState().expiresOn}`);

  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().catch((err) => {
  console.error("The sample encountered an error:", err);
});

module.exports = { main };

このクイックスタートでは、Python 用のクライアント ライブラリを使用してテキスト概要作成アプリケーションを作成します。 次の例では、ドキュメントまたはテキスト ベースのカスタマー サービスの会話を要約できる Python アプリケーションを作成します。

ヒント

Language Studio を使用すると、コードを書かなくてもドキュメントの要約を試すことができます。

前提条件

  • Azure サブスクリプション - 無料アカウントを作成します
  • Python 3.x
  • Azure サブスクリプションを入手したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
    • 対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (Free F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。
  • 分析フィーチャーを使用するには、標準 (S) 価格レベルのLanguageリソースが必要です。

設定

環境変数を作成する

API 要求を送信するには、アプリケーションを認証する必要があります。 運用環境では、資格情報を安全に保存してアクセスできる方法を使用してください。 この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。

ヒント

キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。

言語リソース キーの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。

  1. LANGUAGE_KEY 環境変数を設定するには、your-key をリソースのキーの 1 つに置き換えます。
  2. LANGUAGE_ENDPOINT 環境変数を設定するには、your-endpoint をリソースのエンドポイントに置き換えます。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

現在実行中のコンソールで環境変数のみにアクセスする必要がある場合は、環境変数を setx の代わりに set に設定できます。

実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を追加した後で再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

クライアント ライブラリをインストールする

Python をインストールしたら、次を使用してクライアント ライブラリをインストールすることができます。

pip install azure-ai-textanalytics==5.3.0

コードの例

新しい Python ファイルを作成し、下のコードをコピーします。 次にコードを実行します。

重要

Azure Portal にアクセスします。 「前提条件」セクションで作成した Language リソースが正常にデプロイされた場合、 [次の手順] の下にある [リソースに移動] ボタンをクリックします。 キーとエンドポイントは、リソースの [キーとエンドポイント] ページの [リソース管理] に移動することで確認できます。

重要

終わったらコードからキーを削除し、公開しないよう注意してください。 運用環境では、Azure Key Vault などの資格情報を格納してアクセスする安全な方法を使用します。 詳細については、Azure AI サービスのセキュリティに関する記事を参照してください。

# This example requires environment variables named "LANGUAGE_KEY" and "LANGUAGE_ENDPOINT"
key = os.environ.get('LANGUAGE_KEY')
endpoint = os.environ.get('LANGUAGE_ENDPOINT')

from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Authenticate the client using your key and endpoint 
def authenticate_client():
    ta_credential = AzureKeyCredential(key)
    text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, 
            credential=ta_credential)
    return text_analytics_client

client = authenticate_client()

# Example method for summarizing text
def sample_extractive_summarization(client):
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.textanalytics import (
        TextAnalyticsClient,
        ExtractiveSummaryAction
    ) 

    document = [
        "The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. "
        "These sentences collectively convey the main idea of the document. This feature is provided as an API for developers. " 
        "They can use it to build intelligent solutions based on the relevant information extracted to support various use cases. "
        "Extractive summarization supports several languages. It is based on pretrained multilingual transformer models, part of our quest for holistic representations. "
        "It draws its strength from transfer learning across monolingual and harness the shared nature of languages to produce models of improved quality and efficiency. "
    ]

    poller = client.begin_analyze_actions(
        document,
        actions=[
            ExtractiveSummaryAction(max_sentence_count=4)
        ],
    )

    document_results = poller.result()
    for result in document_results:
        extract_summary_result = result[0]  # first document, first result
        if extract_summary_result.is_error:
            print("...Is an error with code '{}' and message '{}'".format(
                extract_summary_result.code, extract_summary_result.message
            ))
        else:
            print("Summary extracted: \n{}".format(
                " ".join([sentence.text for sentence in extract_summary_result.sentences]))
            )

sample_extractive_summarization(client)

出力

Summary extracted: 
The extractive summarization feature uses natural language processing techniques to locate key sentences in an unstructured text document. This feature is provided as an API for developers. They can use it to build intelligent solutions based on the relevant information extracted to support various use cases.

このクイックスタートでは、REST API を使用してテキスト概要作成要求を送信します。 次の例では、cURL を使用して、ドキュメントまたはテキスト ベースのカスタマー サービスの会話を要約します。

ヒント

Language Studio を使用すると、コードを書かなくてもドキュメントの要約を試すことができます。

前提条件

  • 最新バージョンの cURL
  • Azure サブスクリプションを入手したら、Azure portal で言語リソースを作成して、キーとエンドポイントを取得します。 デプロイされたら、 [リソースに移動] を選択します。
    • 対象のアプリケーションを API に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。
    • Free 価格レベル (Free F0) を使用してサービスを試用し、後から運用環境用の有料レベルにアップグレードすることができます。

設定

環境変数を作成する

API 要求を送信するには、アプリケーションを認証する必要があります。 運用環境では、資格情報を安全に保存してアクセスできる方法を使用してください。 この例では、アプリケーションを実行しているローカル コンピューター上の環境変数に資格情報を書き込みます。

ヒント

キーは、コードに直接含めないようにし、公開しないでください。 Azure Key Vault などのその他の認証オプションについては、Azure AI サービスのセキュリティに関する記事を参照してください。

言語リソース キーの環境変数を設定するには、コンソール ウィンドウを開き、オペレーティング システムと開発環境の指示に従います。

  1. LANGUAGE_KEY 環境変数を設定するには、your-key をリソースのキーの 1 つに置き換えます。
  2. LANGUAGE_ENDPOINT 環境変数を設定するには、your-endpoint をリソースのエンドポイントに置き換えます。
setx LANGUAGE_KEY your-key
setx LANGUAGE_ENDPOINT your-endpoint

Note

現在実行中のコンソールで環境変数のみにアクセスする必要がある場合は、環境変数を setx の代わりに set に設定できます。

実行中のプログラムのうち、環境変数の読み取りを必要とするプログラム (コンソール ウィンドウを含む) については、環境変数を追加した後で再起動が必要となる場合があります。 たとえば、Visual Studio をエディターとして使用している場合、サンプルを実行する前に Visual Studio を再起動します。

要求の例

注意

  • 以降に掲載した BASH の例では、行連結文字として \ を使用しています。 ご利用のコンソールまたはターミナルで異なる行連結文字が使用されている場合は、その文字を使用してください。
  • 言語固有のサンプルについては GitHub を参照してください。 API を呼び出すには、次の情報が必要です。

実行する概要作成の種類を選択し、次のいずれかのタブを選択して API 呼び出しの例を表示します。

機能 説明
ドキュメントの概要作成 抽出するテキストの概要作成を使用して、ドキュメント内の重要または関連する情報の概要を生成します。
会話の概要作成 抽象化するテキストの概要作成を使用して、顧客サービス エージェントと顧客の間のトランスクリプトの問題と解決策の概要を生成します。
パラメーター Description
-X POST <endpoint> API にアクセスするためのエンドポイントを指定します。
-H Content-Type: application/json JSON データを送信するためのコンテンツ タイプ。
-H "Ocp-Apim-Subscription-Key:<key> API にアクセスするためのキーを指定します。
-d <documents> 送信するドキュメントを含む JSON。

次の cURL コマンドは、BASH シェルから実行されます。 これらのコマンドは、独自の JSON 値を使用して編集します。

ドキュメントの概要作成

ドキュメント抽出要約の例

ドキュメントの抽出要約を使い始めるときの例を次に示します。

  1. テキスト エディターに以下のコマンドをコピーします。 BASH の例では、行連結文字として \ を使用します。 ご利用のコンソールまたはターミナルで異なる行連結文字が使われている場合は、その文字を代わりに使ってください。
curl -i -X POST $LANGUAGE_ENDPOINT/language/analyze-text/jobs?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY" \
-d \
' 
{
  "displayName": "Document ext Summarization Task Example",
  "analysisInput": {
    "documents": [
      {
        "id": "1",
        "language": "en",
        "text": "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI services, I have been working with a team of amazing scientists and engineers to turn this quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see, and understand humans better. We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, spanning modalities and languages. The goal is to have pre-trained models that can jointly learn representations to support a broad range of downstream AI tasks, much in the way humans do today. Over the past five years, we have achieved human performance on benchmarks in conversational speech recognition, machine translation, conversational question answering, machine reading comprehension, and image captioning. These five breakthroughs provided us with strong signals toward our more ambitious aspiration to produce a leap in AI capabilities, achieving multi-sensory and multilingual learning that is closer in line with how humans learn and understand. I believe the joint XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks."
      }
    ]
  },
  "tasks": [
    {
      "kind": "ExtractiveSummarization",
      "taskName": "Document Extractive Summarization Task 1",
      "parameters": {
        "sentenceCount": 6
      }
    }
  ]
}
'
  1. コマンド プロンプト ウィンドウ (BASH など) を開きます。

  2. テキスト エディターからコマンド プロンプト ウィンドウにコマンドを貼り付けて、コマンドを実行します。

  3. operation-location を応答ヘッダーから取得します。 この値は次の URL のようになります。

https://<your-language-resource-endpoint>/language/analyze-text/jobs/12345678-1234-1234-1234-12345678?api-version=2023-04-01
  1. 要求の結果を取得するには、次の cURL コマンドを使用します。 <my-job-id> を、前の operation-location 応答ヘッダーから受け取った数値 ID 値に必ず置き換えてください。
curl -X GET $LANGUAGE_ENDPOINT/language/analyze-text/jobs/<my-job-id>?api-version=2023-04-01 \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: $LANGUAGE_KEY"

ドキュメント抽出要約の JSON 応答の例

{
    "jobId": "56e43bcf-70d8-44d2-a7a7-131f3dff069f",
    "lastUpdateDateTime": "2022-09-28T19:33:43Z",
    "createdDateTime": "2022-09-28T19:33:42Z",
    "expirationDateTime": "2022-09-29T19:33:42Z",
    "status": "succeeded",
    "errors": [],
    "displayName": "Document ext Summarization Task Example",
    "tasks": {
        "completed": 1,
        "failed": 0,
        "inProgress": 0,
        "total": 1,
        "items": [
            {
                "kind": "ExtractiveSummarizationLROResults",
                "taskName": "Document Extractive Summarization Task 1",
                "lastUpdateDateTime": "2022-09-28T19:33:43.6712507Z",
                "status": "succeeded",
                "results": {
                    "documents": [
                        {
                            "id": "1",
                            "sentences": [
                                {
                                    "text": "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic, human-centric approach to learning and understanding.",
                                    "rankScore": 0.69,
                                    "offset": 0,
                                    "length": 160
                                },
                                {
                                    "text": "In my role, I enjoy a unique perspective in viewing the relationship among three attributes of human cognition: monolingual text (X), audio or visual sensory signals, (Y) and multilingual (Z).",
                                    "rankScore": 0.66,
                                    "offset": 324,
                                    "length": 192
                                },
                                {
                                    "text": "At the intersection of all three, there’s magic—what we call XYZ-code as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear, see, and understand humans better.",
                                    "rankScore": 0.63,
                                    "offset": 517,
                                    "length": 203
                                },
                                {
                                    "text": "We believe XYZ-code will enable us to fulfill our long-term vision: cross-domain transfer learning, spanning modalities and languages.",
                                    "rankScore": 1.0,
                                    "offset": 721,
                                    "length": 134
                                },
                                {
                                    "text": "The goal is to have pre-trained models that can jointly learn representations to support a broad range of downstream AI tasks, much in the way humans do today.",
                                    "rankScore": 0.74,
                                    "offset": 856,
                                    "length": 159
                                },
                                {
                                    "text": "I believe the joint XYZ-code is a foundational component of this aspiration, if grounded with external knowledge sources in the downstream AI tasks.",
                                    "rankScore": 0.49,
                                    "offset": 1481,
                                    "length": 148
                                }
                            ],
                            "warnings": []
                        }
                    ],
                    "errors": [],
                    "modelVersion": "latest"
                }
            }
        ]
    }
}

リソースをクリーンアップする

Azure AI サービス サブスクリプションをクリーンアップして削除したい場合は、リソースまたはリソース グループを削除することができます。 リソース グループを削除すると、それに関連付けられている他のリソースも削除されます。

次のステップ