クイックスタート: Language Understanding (LUIS) クライアント ライブラリと REST API

重要

LUIS は 2025 年 10 月 1 日に廃止され、2023 年 4 月 1 日から新しい LUIS リソースを作成できなくなります。 継続的な製品サポートと多言語機能のベネフィットを得るために、LUIS アプリケーション会話言語理解に移行することをお勧めします。

C#、Python、または JavaScript を使用したこのクイックスタートでは、LUIS SDK クライアント ライブラリを使用して Azure LUIS 人工知能 (AI) アプリを作成し、クエリを実行します。 また、cURL を使用して、REST API で要求を送信することもできます。

Language Understanding (LUIS) を使うと、自然言語処理 (NLP) をユーザーの自然言語での会話に適用して、全体の意味を予測し、関連性のある詳細な情報を引き出すことができます。

  • 作成クライアント ライブラリと REST API を使用すると、LUIS アプリを作成、編集、トレーニング、および公開できます。
  • 予測ランタイム クライアント ライブラリと REST API を使用すると、公開されているアプリに対してクエリを実行できます。

.NET 用 Language Understanding (LUIS) クライアント ライブラリを使用して次のことを行います。

  • アプリを作成する
  • 発話の例を使用して、意図 (機械学習エンティティの 1 つ) を追加する
  • アプリをトレーニングして公開する
  • クエリ予測ランタイム

リファレンス ドキュメント | 作成および予測ライブラリ ソース コード | 作成および予測 NuGet | C# のサンプル

前提条件

  • 現在のバージョンの .NET Core および .NET Core CLI
  • Azure サブスクリプション - 無料アカウントを作成します
  • Azure サブスクリプションを入手したら、Azure portal で Language Understanding 作成リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • アプリケーションを Language Understanding 作成に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。 Free 価格レベル (F0) を利用して、サービスを試用できます。

設定

新しい C# アプリケーションを作成する

好みのエディターまたは IDE で、新しい .NET Core アプリケーションを作成します。

  1. コンソール ウィンドウ (cmd、PowerShell、Bash など) で、dotnet new コマンドを使用し、language-understanding-quickstart という名前で新しいコンソール アプリを作成します。 このコマンドにより、1 つのソース ファイル (Program.cs) を使用する単純な "Hello World" C# プロジェクトが作成されます。

    dotnet new console -n language-understanding-quickstart
    
  2. 新しく作成されたアプリ フォルダーにディレクトリを変更します。

    cd language-understanding-quickstart
    
  3. 次を使用してアプリケーションをビルドできます。

    dotnet build
    

    ビルドの出力に警告やエラーが含まれないようにする必要があります。

    ...
    Build succeeded.
     0 Warning(s)
     0 Error(s)
    ...
    

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

次のコマンドを使用して、アプリケーション ディレクトリ内に .NET 用 Language Understanding (LUIS) クライアント ライブラリをインストールします。

dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring --version 3.2.0-preview.3
dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime --version 3.1.0-preview.1

作成オブジェクト モデル

Language Understanding (LUIS) 作成クライアントは、認証を経て作成キーの保管場所である Azure にアクセスする LUISAuthoringClient オブジェクトです。

作成のコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

予測オブジェクト モデル

Language Understanding (LUIS) 予測ランタイム クライアントは、認証を経てリソース キーの保管場所である Azure にアクセスする LUISRuntimeClient オブジェクトです。

予測ランタイムのコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

コード例

以下のコード スニペットは、Python 用 Language Understanding (LUIS) クライアント ライブラリを使用して次のことを実行する方法を示したものです。

依存関係を追加する

プロジェクト ディレクトリから、好みのエディターまたは IDE で Program.cs ファイルを開きます。 既存の using コードを次の using ディレクティブに置き換えます。

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
using Newtonsoft.Json;

定型コードを追加する

  1. 非同期呼び出しを許可するように、Main メソッドのシグネチャを変更します。

    public static async Task Main()
    
  2. 特に指定がなければ、Program クラスの Main メソッドに残りのコードを追加します。

アプリの変数を作成する

変数の 2 つのセットを作成します。最初のセットに変更を加え、2 番目のセットはコード サンプルに表示されるままにしておきます。

重要

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

  1. 作成キーとリソース名を保持する変数を作成します。

    var key = "PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE";
    
    var authoringEndpoint = "PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE";
    var predictionEndpoint = "PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE";
    
  2. エンドポイント、アプリ名、バージョン、および意図名を保持する変数を作成します。

    var appName = "Contoso Pizza Company";
    var versionId = "0.1";
    var intentName = "OrderPizzaIntent";
    

クライアントを認証する

自分のキーを指定して ApiKeyServiceClientCredentials オブジェクトを作成し、それを自分のエンドポイントと共に使用して LUISAuthoringClient オブジェクトを作成します。

var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(key);
var client = new LUISAuthoringClient(credentials) { Endpoint = authoringEndpoint };

LUIS アプリの作成

LUIS アプリには、意図、エンティティ、発話例を備えた自然言語処理 (NLP) モデルが含まれています。

ApplicationCreateObject を作成します。 名前と言語のカルチャは必須のプロパティです。 Apps.AddAsync メソッドを呼び出します。 応答はアプリ ID です。

var newApp = new ApplicationCreateObject
{
    Culture = "en-us",
    Name = appName,
    InitialVersionId = versionId
};

var appId = await client.Apps.AddAsync(newApp);

アプリの意図の作成

LUIS アプリのモデルの中で最も重要なオブジェクトが、意図です。 意図は、ユーザーが発話において "意図したこと" をグループ分けしたものに対応しています。 ユーザーが質問をしたり、言葉を発したりするのは、ボット (またはその他のクライアント アプリケーション) から "自らが意図した" 回答を得るためです。 意図の例は、フライトの予約、目的地の天気の確認、カスタマー サービスの連絡先情報の取得などが挙げられます。

一意の意図の名前を備えた ModelCreateObject を作成し、Model.AddIntentAsync メソッドにアプリ ID、バージョン ID、ModelCreateObject を渡します。 応答は意図 ID です。

intentName の値は、「intentName」セクションの変数の一部として OrderPizzaIntent にハードコーディングされます。

await client.Model.AddIntentAsync(appId, versionId, new ModelCreateObject()
{
    Name = intentName
});

アプリのエンティティの作成

必須ではないものの、ほとんどのアプリで見られるのがエンティティです。 エンティティは、ユーザーの発話からユーザーが意図した成果を達成するために必要な情報を抽出します。 事前構築済みエンティティとカスタム エンティティにはいくつかの種類があり、それぞれが専用のデータ変換オブジェクト (DTO) モデルを備えています。 事前構築済みエンティティのうち、アプリに追加することが多いものとしては、numberdatetimeV2geographyV2ordinal があります。

重要なのは、エンティティには 1 つの意図だけがマークされるわけではないという点です。 これらは多くの意図に適用することができますし、多くの意図に適用されるのが普通です。 特定の意図が 1 つだけマークされるのは、ユーザーの発話の例のみです。

エンティティ作成のためのメソッドは、Model クラスに含まれています。 エンティティは種類ごとに固有のデータ変換オブジェクト (DTO) モデルを備えており、その model 名前空間には通常 model という語が含まれています。

エンティティ作成コードによって、サブエンティティを備えた機械学習エンティティが作成され、さまざまな特徴が Quantity サブエンティティに適用されます。

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

// Add Prebuilt entity
await client.Model.AddPrebuiltAsync(appId, versionId, new[] { "number" });

// Define ml entity with children and grandchildren
var mlEntityDefinition = new EntityModelCreateObject
{
    Name = "Pizza order",
    Children = new[]
    {
        new ChildEntityModelCreateObject
        {
            Name = "Pizza",
            Children = new[]
            {
                new ChildEntityModelCreateObject { Name = "Quantity" },
                new ChildEntityModelCreateObject { Name = "Type" },
                new ChildEntityModelCreateObject { Name = "Size" }
            }
        },
        new ChildEntityModelCreateObject
        {
            Name = "Toppings",
            Children = new[]
            {
                new ChildEntityModelCreateObject { Name = "Type" },
                new ChildEntityModelCreateObject { Name = "Quantity" }
            }
        }
    }
};

// Add ML entity 
var mlEntityId = await client.Model.AddEntityAsync(appId, versionId, mlEntityDefinition); ;

// Add phraselist feature
var phraselistId = await client.Features.AddPhraseListAsync(appId, versionId, new PhraselistCreateObject
{
    EnabledForAllModels = false,
    IsExchangeable = true,
    Name = "QuantityPhraselist",
    Phrases = "few,more,extra"
});

// Get entity and subentities
var model = await client.Model.GetEntityAsync(appId, versionId, mlEntityId);
var toppingQuantityId = GetModelGrandchild(model, "Toppings", "Quantity");
var pizzaQuantityId = GetModelGrandchild(model, "Pizza", "Quantity");

// add model as feature to subentity model
await client.Features.AddEntityFeatureAsync(appId, versionId, pizzaQuantityId, new ModelFeatureInformation { ModelName = "number", IsRequired = true });
await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { ModelName = "number"});

// add phrase list as feature to subentity model
await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { FeatureName = "QuantityPhraselist" });

Quantity サブエンティティに特徴を割り当てるために、クラスに対して次のメソッドを使用して、Quantity サブエンティティの ID を検索します。

static Guid GetModelGrandchild(NDepthEntityExtractor model, string childName, string grandchildName)
{
    return model.Children.
        Single(c => c.Name == childName).
        Children.
        Single(c => c.Name == grandchildName).Id;
}

意図に対する発話の例の追加

アプリでは、発話の意図を特定し、エンティティを抽出するために、発話の例が必要になります。 例では、特定の 1 つの意図をターゲットとし、すべてのカスタム エンティティをマークする必要があります。 事前構築済みエンティティをマークする必要はありません。

ExampleLabelObject オブジェクトの一覧 (発話の例 1 件につき 1 つのオブジェクト) を作成し、発話の例を追加します。 それぞれの例では、エンティティの名前とエンティティの値から成る名前と値のペアのディクショナリを使用し、エンティティをすべてマークする必要があります。 エンティティの値は、発話の例のテキストに表示されているものと正確に一致している必要があります。

Partial screenshot showing the labeled example utterance in the portal.

アプリ ID、バージョン ID、および例を指定して Examples.AddAsync を呼び出します。

// Define labeled example
var labeledExampleUtteranceWithMLEntity = new ExampleLabelObject
{
    Text = "I want two small seafood pizzas with extra cheese.",
    IntentName = intentName,
    EntityLabels = new[]
    {
        new EntityLabelObject
        {
            StartCharIndex = 7,
            EndCharIndex = 48,
            EntityName = "Pizza order",
            Children = new[]
            {
                new EntityLabelObject
                {
                    StartCharIndex = 7,
                    EndCharIndex = 30,
                    EntityName = "Pizza",
                    Children = new[]
                    {
                        new EntityLabelObject { StartCharIndex = 7, EndCharIndex = 9, EntityName = "Quantity" },
                        new EntityLabelObject { StartCharIndex = 11, EndCharIndex = 15, EntityName = "Size" },
                        new EntityLabelObject { StartCharIndex = 17, EndCharIndex = 23, EntityName = "Type" }
                    }
                },
                new EntityLabelObject
                {
                    StartCharIndex = 37,
                    EndCharIndex = 48,
                    EntityName = "Toppings",
                    Children = new[]
                    {
                        new EntityLabelObject { StartCharIndex = 37, EndCharIndex = 41, EntityName = "Quantity" },
                        new EntityLabelObject { StartCharIndex = 43, EndCharIndex = 48, EntityName = "Type" }
                    }
                }
            }
        },
    }
};

// Add an example for the entity.
// Enable nested children to allow using multiple models with the same name.
// The quantity subentity and the phraselist could have the same exact name if this is set to True
await client.Examples.AddAsync(appId, versionId, labeledExampleUtteranceWithMLEntity, enableNestedChildren: true); 

アプリをトレーニングする

モデルの作成を終えたら、このバージョンのモデルに合わせて LUIS アプリをトレーニングする必要があります。 トレーニングを済ませたモデルは、コンテナーで使用したり、ステージング スロットまたは製品スロットに公開したりできます。

Train.TrainVersionAsync メソッドでは、アプリ ID とバージョン ID が必要です。

このクイックスタートで示したような非常に小さなモデルであれば、トレーニングが短時間で完了します。 運用レベルのアプリケーションの場合には、アプリのトレーニングに、トレーニングが成功したかどうかと、そのタイミングを確認するための GetStatusAsync メソッドに対するポーリング呼び出しが含まれます。 応答は、オブジェクトごとの状態を格納した ModelTrainingInfo オブジェクトの一覧です。 トレーニングが完了したと判定されるには、オブジェクトがすべて成功している必要があります。

await client.Train.TrainVersionAsync(appId, versionId);
while (true)
{
    var status = await client.Train.GetStatusAsync(appId, versionId);
    if (status.All(m => m.Details.Status == "Success"))
    {
        // Assumes that we never fail, and that eventually we'll always succeed.
        break;
    }
}

アプリを運用スロットに公開する

PublishAsync メソッドを使用して、LUIS アプリを公開します。 これにより、トレーニング済みの最新バージョンがエンドポイントの指定されたスロットに公開されます。 クライアント アプリケーションではこのエンドポイントを使用して、意図の予測とエンティティの抽出の対象となるユーザー発話を送信します。

await client.Apps.PublishAsync(appId, new ApplicationPublishObject { VersionId = versionId, IsStaging=false});

予測ランタイム クライアントを認証する

自分のキーを指定して ApiKeyServiceClientCredentials オブジェクトを使用し、それを自分のエンドポイントと共に使用して LUISRuntimeClient オブジェクトを作成します。

注意事項

このクイックスタートでは、ランタイム資格情報の一部として作成キーを使います。 作成キーを使用すると、いくつかのクエリを使用してランタイムにクエリを実行できます。 ステージングおよび運用レベルのコードでは、作成キーを予測ランタイム キーで置き換えます。

var runtimeClient = new LUISRuntimeClient(credentials) { Endpoint = predictionEndpoint };

ランタイムから予測を取得する

次のコードを追加して、予測ランタイムへの要求を作成します。

ユーザーの発話は、PredictionRequest オブジェクトの一部です。

GetSlotPredictionAsync メソッドには、アプリ ID、スロット名、要求を満たす予測要求オブジェクトなど、いくつかのパラメーターが必要です。 詳細、すべての意図の表示、ログなど、その他のオプションは省略可能です。

// Production == slot name
var request = new PredictionRequest { Query = "I want two small pepperoni pizzas with more salsa" };
var prediction = await runtimeClient.Prediction.GetSlotPredictionAsync(appId, "Production", request);
Console.Write(JsonConvert.SerializeObject(prediction, Formatting.Indented));

予測応答は、意図と検出されたエンティティを含む JSON オブジェクトです。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

アプリケーションの実行

自分のアプリケーション ディレクトリで dotnet run コマンドを使用してアプリケーションを実行します。

dotnet run

Node.js 用 Language Understanding (LUIS) クライアント ライブラリの用途は次のとおりです。

  • アプリを作成する
  • 発話の例を使用して、意図 (機械学習エンティティの 1 つ) を追加する
  • アプリをトレーニングして公開する
  • クエリ予測ランタイム

リファレンス ドキュメント | 作成予測 NPM | サンプル

前提条件

  • Node.js
  • Azure サブスクリプション - 無料アカウントを作成します
  • Azure サブスクリプションを入手したら、Azure portal で Language Understanding 作成リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • アプリケーションを Language Understanding 作成に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。 Free 価格レベル (F0) を利用して、サービスを試用できます。

設定

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

  1. コンソール ウィンドウで、アプリケーション用の新しいディレクトリを作成し、そのディレクトリに移動します。

    mkdir quickstart-sdk && cd quickstart-sdk
    
  2. package.json ファイルを作成して、ディレクトリを JavaScript アプリケーションとして初期化します。

    npm init -y
    
  3. JavaScript コード用に index.js という名前のファイルを作成します。

    touch index.js
    

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

次のコマンドを一度に 1 行ずつ実行して、アプリケーション ディレクトリ内に依存関係をインストールします。

npm install @azure/ms-rest-js
npm install @azure/cognitiveservices-luis-authoring
npm install @azure/cognitiveservices-luis-runtime

package.json は次のようになります。

{
  "name": "quickstart-sdk",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@azure/cognitiveservices-luis-authoring": "^4.0.0-preview.3",
    "@azure/cognitiveservices-luis-runtime": "^5.0.0",
    "@azure/ms-rest-js": "^2.0.8"
  }
}

作成オブジェクト モデル

Language Understanding (LUIS) 作成クライアントは、認証を経て作成キーの保管場所である Azure にアクセスする LUISAuthoringClient オブジェクトです。

作成のコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

予測オブジェクト モデル

Language Understanding (LUIS) 作成クライアントは、認証を経て作成キーの保管場所である Azure にアクセスする LUISAuthoringClient オブジェクトです。

予測ランタイムのコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

コード例

以下のコード スニペットは、Python 用 Language Understanding (LUIS) クライアント ライブラリを使用して次のことを実行する方法を示したものです。

依存関係を追加する

希望するエディターまたは IDE で index.js ファイルを開き、次の依存関係を追加します。

const msRest = require("@azure/ms-rest-js");
const LUIS_Authoring = require("@azure/cognitiveservices-luis-authoring");
const LUIS_Prediction = require("@azure/cognitiveservices-luis-runtime");

定型コードを追加する

  1. quickstart メソッドとその呼び出しを追加します。 このメソッドには、残りのコードの大部分が含まれています。 このメソッドは、ファイルの末尾で呼び出されます。

    const quickstart = async () => {
    
        // add calls here
    
    
    }
    quickstart()
        .then(result => console.log("Done"))
        .catch(err => {
            console.log(`Error: ${err}`)
            })
    
  2. 特に指定がなければ、quickstart メソッドの残りのコードを追加します。

アプリの変数を作成する

変数の 2 つのセットを作成します。最初のセットに変更を加え、2 番目のセットはコード サンプルに表示されるままにしておきます。

重要

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

  1. 作成キーとリソース名を保持する変数を作成します。

    const authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE';
    
    const authoringEndpoint = "PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE";
    const predictionEndpoint = "PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE";
    
  2. エンドポイント、アプリ名、バージョン、および意図名を保持する変数を作成します。

    const appName = "Contoso Pizza Company";
    const versionId = "0.1";
    const intentName = "OrderPizzaIntent";
    

クライアントを認証する

自分のキーを指定して CognitiveServicesCredentials オブジェクトを作成し、それを自分のエンドポイントと共に使用して LUISAuthoringClient オブジェクトを作成します。

const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
    inHeader: { "Ocp-Apim-Subscription-Key": authoringKey }
});
const client = new LUIS_Authoring.LUISAuthoringClient(
    luisAuthoringCredentials,
    authoringEndpoint
);

LUIS アプリの作成

LUIS アプリには、意図、エンティティ、発話例を備えた自然言語処理 (NLP) モデルが含まれています。

AppsOperation オブジェクトの add メソッドを作成してアプリを作成します。 名前と言語のカルチャは必須のプロパティです。

const create_app_payload = {
    name: appName,
    initialVersionId: versionId,
    culture: "en-us"
};

const createAppResult = await client.apps.add(
    create_app_payload
);

const appId = createAppResult.body

アプリの意図の作成

LUIS アプリのモデルの中で最も重要なオブジェクトが、意図です。 意図は、ユーザーが発話において "意図したこと" をグループ分けしたものに対応しています。 ユーザーが質問をしたり、言葉を発したりするのは、ボット (またはその他のクライアント アプリケーション) から "自らが意図した" 回答を得るためです。 意図の例は、フライトの予約、目的地の天気の確認、カスタマー サービスの連絡先情報の取得などが挙げられます。

意図の一意の名前と共に model.add_intent メソッドを使用し、アプリ ID とバージョン ID、新しい意図の名前を渡します。

intentName の値は、「intentName」セクションの変数の一部として OrderPizzaIntent にハードコーディングされます。

await client.model.addIntent(
    appId,
    versionId,
    { name: intentName }
);

アプリのエンティティの作成

必須ではないものの、ほとんどのアプリで見られるのがエンティティです。 エンティティは、ユーザーの発話からユーザーが意図した成果を達成するために必要な情報を抽出します。 事前構築済みエンティティとカスタム エンティティにはいくつかの種類があり、それぞれが専用のデータ変換オブジェクト (DTO) モデルを備えています。 事前構築済みエンティティのうち、アプリに追加することが多いものとしては、numberdatetimeV2geographyV2ordinal があります。

重要なのは、エンティティには 1 つの意図だけがマークされるわけではないという点です。 これらは多くの意図に適用することができますし、多くの意図に適用されるのが普通です。 特定の意図が 1 つだけマークされるのは、ユーザーの発話の例のみです。

エンティティ作成のためのメソッドは、Model クラスに含まれています。 エンティティは種類ごとに固有のデータ変換オブジェクト (DTO) モデルを備えています。

エンティティ作成コードによって、サブエンティティを備えた機械学習エンティティが作成され、さまざまな特徴が Quantity サブエンティティに適用されます。

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

// Add Prebuilt entity
await client.model.addPrebuilt(appId, versionId, ["number"]);

// Define ml entity with children and grandchildren
const mlEntityDefinition = {
    name: "Pizza order",
    children: [
        {
            name: "Pizza",
            children: [
                { name: "Quantity" },
                { name: "Type" },
                { name: "Size" }
            ]
        },
        {
            name: "Toppings",
            children: [
                { name: "Type" },
                { name: "Quantity" }
            ]
        }
    ]
};

// Add ML entity 
const response = await client.model.addEntity(appId, versionId, mlEntityDefinition);
const mlEntityId = response.body;

// Add phraselist feature
const phraselistResponse = await client.features.addPhraseList(appId, versionId, {
    enabledForAllModels: false,
    isExchangeable: true,
    name: "QuantityPhraselist",
    phrases: "few,more,extra"
});
const phraseListId = phraselistResponse.body;

// Get entity and subentities
const model = await client.model.getEntity(appId, versionId, mlEntityId);
const toppingQuantityId = getModelGrandchild(model, "Toppings", "Quantity");
const pizzaQuantityId = getModelGrandchild(model, "Pizza", "Quantity");

// add model as feature to subentity model
await client.features.addEntityFeature(appId, versionId, pizzaQuantityId, { modelName: "number", isRequired: true });
await client.features.addEntityFeature(appId, versionId, toppingQuantityId, { modelName: "number" });

// add phrase list as feature to subentity model
await client.features.addEntityFeature(appId, versionId, toppingQuantityId, { featureName: "QuantityPhraselist" });

Quantity サブエンティティに特徴を割り当てるために、次のメソッドを quickstart メソッドの上に配置して、Quantity サブエンティティの ID を検索します。

const getModelGrandchild = (model, childName, grandchildName) => {

    return model.children.find(c => c.name == childName).children.find(c => c.name == grandchildName).id

}

意図に対する発話の例の追加

アプリでは、発話の意図を特定し、エンティティを抽出するために、発話の例が必要になります。 例では、特定の 1 つの意図をターゲットとし、すべてのカスタム エンティティをマークする必要があります。 事前構築済みエンティティをマークする必要はありません。

ExampleLabelObject オブジェクトの一覧 (発話の例 1 件につき 1 つのオブジェクト) を作成し、発話の例を追加します。 それぞれの例では、エンティティの名前とエンティティの値から成る名前と値のペアのディクショナリを使用し、エンティティをすべてマークする必要があります。 エンティティの値は、発話の例のテキストに表示されているものと正確に一致している必要があります。

Partial screenshot showing the labeled example utterance in the portal.

アプリ ID、バージョン ID、および例を指定して examples.add を呼び出します。

// Define labeled example
const labeledExampleUtteranceWithMLEntity =
{
    text: "I want two small seafood pizzas with extra cheese.",
    intentName: intentName,
    entityLabels: [
        {
            startCharIndex: 7,
            endCharIndex: 48,
            entityName: "Pizza order",
            children: [
                {
                    startCharIndex: 7,
                    endCharIndex: 30,
                    entityName: "Pizza",
                    children: [
                        {
                            startCharIndex: 7,
                            endCharIndex: 9,
                            entityName: "Quantity"
                        },
                        {
                            startCharIndex: 11,
                            endCharIndex: 15,
                            entityName: "Size"
                        },
                        {
                            startCharIndex: 17,
                            endCharIndex: 23,
                            entityName: "Type"
                        }]
                },
                {
                    startCharIndex: 37,
                    endCharIndex: 48,
                    entityName: "Toppings",
                    children: [
                        {
                            startCharIndex: 37,
                            endCharIndex: 41,
                            entityName: "Quantity"
                        },
                        {
                            startCharIndex: 43,
                            endCharIndex: 48,
                            entityName: "Type"
                        }]
                }
            ]
        }
    ]
};

console.log("Labeled Example Utterance:", JSON.stringify(labeledExampleUtteranceWithMLEntity, null, 4 ));

// Add an example for the entity.
// Enable nested children to allow using multiple models with the same name.
// The quantity subentity and the phraselist could have the same exact name if this is set to True
await client.examples.add(appId, versionId, labeledExampleUtteranceWithMLEntity, { enableNestedChildren: true });

アプリをトレーニングする

モデルの作成を終えたら、このバージョンのモデルに合わせて LUIS アプリをトレーニングする必要があります。 トレーニングを済ませたモデルは、コンテナーで使用したり、ステージング スロットまたは製品スロットに公開したりできます。

train.trainVersion メソッドでは、アプリ ID とバージョン ID が必要です。

このクイックスタートで示したような非常に小さなモデルであれば、トレーニングが短時間で完了します。 運用レベルのアプリケーションの場合には、アプリのトレーニングに、トレーニングが成功したかどうかと、そのタイミングを確認するための get_status メソッドに対するポーリング呼び出しが含まれます。 応答は、オブジェクトごとの状態を格納した ModelTrainingInfo オブジェクトの一覧です。 トレーニングが完了したと判定されるには、オブジェクトがすべて成功している必要があります。

await client.train.trainVersion(appId, versionId);
while (true) {
    const status = await client.train.getStatus(appId, versionId);
    if (status.every(m => m.details.status == "Success")) {
        // Assumes that we never fail, and that eventually we'll always succeed.
        break;
    }
}

アプリを運用スロットに公開する

app.publish メソッドを使用して、LUIS アプリを公開します。 これにより、トレーニング済みの最新バージョンがエンドポイントの指定されたスロットに公開されます。 クライアント アプリケーションではこのエンドポイントを使用して、意図の予測とエンティティの抽出の対象となるユーザー発話を送信します。

await client.apps.publish(appId, { versionId: versionId, isStaging: false });

予測ランタイム クライアントを認証する

msRest.ApiKeyCredentials オブジェクトに自分のキーを指定し、これをエンドポイントと共に使用して LUIS.LUISRuntimeClient オブジェクトを作成します。

注意事項

このクイックスタートでは、ランタイム資格情報の一部として作成キーを使います。 作成キーを使用すると、いくつかのクエリを使用してランタイムにクエリを実行できます。 ステージングおよび運用レベルのコードでは、作成キーを予測ランタイム キーで置き換えます。

const luisPredictionClient = new LUIS_Prediction.LUISRuntimeClient(
    luisAuthoringCredentials,
    predictionEndpoint
);

ランタイムから予測を取得する

次のコードを追加して、予測ランタイムへの要求を作成します。 ユーザーの発話は、predictionRequest オブジェクトの一部です。

luisRuntimeClient.prediction.getSlotPrediction メソッドには、アプリ ID、スロット名、要求を満たす予測要求オブジェクトなど、いくつかのパラメーターが必要です。 詳細、すべての意図の表示、ログなど、その他のオプションは省略可能です。

// Production == slot name
const request = { query: "I want two small pepperoni pizzas with more salsa" };
const response = await luisPredictionClient.prediction.getSlotPrediction(appId, "Production", request);
console.log(JSON.stringify(response.prediction, null, 4 ));

予測応答は、意図と検出されたエンティティを含む JSON オブジェクトです。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

アプリケーションの実行

クイック スタート ファイルで node index.js コマンドを使用して、アプリケーションを実行します。

node index.js

Python 用 Language Understanding (LUIS) クライアント ライブラリを使用して次のことを行います。

  • アプリを作成する
  • 発話の例を使用して、意図 (機械学習エンティティの 1 つ) を追加する
  • アプリをトレーニングして公開する
  • クエリ予測ランタイム

リファレンス ドキュメント | 作成および予測 ライブラリ ソース コード | パッケージ (Pypi) | サンプル

前提条件

  • 最新バージョンの Python 3.x
  • Azure サブスクリプション - 無料アカウントを作成します
  • Azure サブスクリプションを入手したら、Azure portal で Language Understanding 作成リソースを作成し、キーとエンドポイントを取得します。 デプロイするまで待ち、 [リソースに移動] ボタンをクリックします。
    • アプリケーションを Language Understanding 作成に接続するには、作成したリソースのキーとエンドポイントが必要です。 このクイックスタートで後に示すコードに、自分のキーとエンドポイントを貼り付けます。 Free 価格レベル (F0) を利用して、サービスを試用できます。

設定

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

  1. コンソール ウィンドウで、アプリケーション用の新しいディレクトリを作成し、そのディレクトリに移動します。

    mkdir quickstart-sdk && cd quickstart-sdk
    
  2. Python コード用に authoring_and_predict.py という名前のファイルを作成します。

    touch authoring_and_predict.py
    

PIP を使用してクライアント ライブラリをインストールする

次のコマンドを使用して、アプリケーション ディレクトリ内に Python 用 Language Understanding (LUIS) クライアント ライブラリをインストールします。

pip install azure-cognitiveservices-language-luis

作成オブジェクト モデル

Language Understanding (LUIS) 作成クライアントは、認証を経て作成キーの保管場所である Azure にアクセスする LUISAuthoringClient オブジェクトです。

作成のコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

予測オブジェクト モデル

Language Understanding (LUIS) 予測ランタイム クライアントは、認証を経てリソース キーの保管場所である Azure にアクセスする LUISRuntimeClient オブジェクトです。

予測ランタイムのコード例

クライアントを作成したら、このクライアントを使用して次のような機能にアクセスします。

コード例

以下のコード スニペットは、Python 用 Language Understanding (LUIS) クライアント ライブラリを使用して次のことを実行する方法を示したものです。

依存関係を追加する

Python ファイルにクライアント ライブラリを追加します。

from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from azure.cognitiveservices.language.luis.authoring.models import ApplicationCreateObject
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials
from functools import reduce

import json, time, uuid

定型コードを追加する

  1. quickstart メソッドとその呼び出しを追加します。 このメソッドには、残りのコードの大部分が含まれています。 このメソッドは、ファイルの末尾で呼び出されます。

    def quickstart():
    
        # add calls here, remember to indent properly
    
    quickstart()
    
  2. 特に指定がなければ、quickstart メソッドの残りのコードを追加します。

アプリの変数を作成する

変数の 2 つのセットを作成します。最初のセットに変更を加え、2 番目のセットはコード サンプルに表示されるままにしておきます。

重要

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

  1. 作成キーとリソース名を保持する変数を作成します。

    authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE'
    authoringEndpoint = 'PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE'
    predictionKey = 'PASTE_YOUR_LUIS_PREDICTION_SUBSCRIPTION_KEY_HERE'
    predictionEndpoint = 'PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE'
    
  2. エンドポイント、アプリ名、バージョン、および意図名を保持する変数を作成します。

    # We use a UUID to avoid name collisions.
    appName = "Contoso Pizza Company " + str(uuid.uuid4())
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    

クライアントを認証する

自分のキーを指定して CognitiveServicesCredentials オブジェクトを作成し、それを自分のエンドポイントと共に使用して LUISAuthoringClient オブジェクトを作成します。

client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))

LUIS アプリの作成

LUIS アプリには、意図、エンティティ、発話例を備えた自然言語処理 (NLP) モデルが含まれています。

AppsOperation オブジェクトの add メソッドを作成してアプリを作成します。 名前と言語のカルチャは必須のプロパティです。

# define app basics
appDefinition = ApplicationCreateObject (name=appName, initial_version_id=versionId, culture='en-us')

# create app
app_id = client.apps.add(appDefinition)

# get app id - necessary for all other changes
print("Created LUIS app with ID {}".format(app_id))

アプリの意図の作成

LUIS アプリのモデルの中で最も重要なオブジェクトが、意図です。 意図は、ユーザーが発話において "意図したこと" をグループ分けしたものに対応しています。 ユーザーが質問をしたり、言葉を発したりするのは、ボット (またはその他のクライアント アプリケーション) から "自らが意図した" 回答を得るためです。 意図の例は、フライトの予約、目的地の天気の確認、カスタマー サービスの連絡先情報の取得などが挙げられます。

意図の一意の名前と共に model.add_intent メソッドを使用し、アプリ ID とバージョン ID、新しい意図の名前を渡します。

intentName の値は、「intentName」セクションの変数の一部として OrderPizzaIntent にハードコーディングされます。

client.model.add_intent(app_id, versionId, intentName)

アプリのエンティティの作成

必須ではないものの、ほとんどのアプリで見られるのがエンティティです。 エンティティは、ユーザーの発話からユーザーが意図した成果を達成するために必要な情報を抽出します。 事前構築済みエンティティとカスタム エンティティにはいくつかの種類があり、それぞれが専用のデータ変換オブジェクト (DTO) モデルを備えています。 事前構築済みエンティティのうち、アプリに追加することが多いものとしては、numberdatetimeV2geographyV2ordinal があります。

重要なのは、エンティティには 1 つの意図だけがマークされるわけではないという点です。 これらは多くの意図に適用することができますし、多くの意図に適用されるのが普通です。 特定の意図が 1 つだけマークされるのは、ユーザーの発話の例のみです。

エンティティ作成のためのメソッドは、ModelOperations クラスに含まれています。 エンティティは種類ごとに固有のデータ変換オブジェクト (DTO) モデルを備えています。

エンティティ作成コードによって、サブエンティティを備えた機械学習エンティティが作成され、さまざまな特徴が Quantity サブエンティティに適用されます。

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

# Add Prebuilt entity
client.model.add_prebuilt(app_id, versionId, prebuilt_extractor_names=["number"])

# define machine-learned entity
mlEntityDefinition = [
{
    "name": "Pizza",
    "children": [
        { "name": "Quantity" },
        { "name": "Type" },
        { "name": "Size" }
    ]
},
{
    "name": "Toppings",
    "children": [
        { "name": "Type" },
        { "name": "Quantity" }
    ]
}]

# add entity to app
modelId = client.model.add_entity(app_id, versionId, name="Pizza order", children=mlEntityDefinition)

# define phraselist - add phrases as significant vocabulary to app
phraseList = {
    "enabledForAllModels": False,
    "isExchangeable": True,
    "name": "QuantityPhraselist",
    "phrases": "few,more,extra"
}

# add phrase list to app
phraseListId = client.features.add_phrase_list(app_id, versionId, phraseList)

# Get entity and subentities
modelObject = client.model.get_entity(app_id, versionId, modelId)
toppingQuantityId = get_grandchild_id(modelObject, "Toppings", "Quantity")
pizzaQuantityId = get_grandchild_id(modelObject, "Pizza", "Quantity")

# add model as feature to subentity model
prebuiltFeatureRequiredDefinition = { "model_name": "number", "is_required": True }
client.features.add_entity_feature(app_id, versionId, pizzaQuantityId, prebuiltFeatureRequiredDefinition)

# add model as feature to subentity model
prebuiltFeatureNotRequiredDefinition = { "model_name": "number" }
client.features.add_entity_feature(app_id, versionId, toppingQuantityId, prebuiltFeatureNotRequiredDefinition)

# add phrase list as feature to subentity model
phraseListFeatureDefinition = { "feature_name": "QuantityPhraselist", "model_name": None }
client.features.add_entity_feature(app_id, versionId, toppingQuantityId, phraseListFeatureDefinition)

Quantity サブエンティティに特徴を割り当てるために、次のメソッドを quickstart メソッドの上に配置して、Quantity サブエンティティの ID を検索します。

def get_grandchild_id(model, childName, grandChildName):
    
    theseChildren = next(filter((lambda child: child.name == childName), model.children))
    theseGrandchildren = next(filter((lambda child: child.name == grandChildName), theseChildren.children))
    
    grandChildId = theseGrandchildren.id
    
    return grandChildId

意図に対する発話の例の追加

アプリでは、発話の意図を特定し、エンティティを抽出するために、発話の例が必要になります。 例では、特定の 1 つの意図をターゲットとし、すべてのカスタム エンティティをマークする必要があります。 事前構築済みエンティティをマークする必要はありません。

ExampleLabelObject オブジェクトの一覧 (発話の例 1 件につき 1 つのオブジェクト) を作成し、発話の例を追加します。 それぞれの例では、エンティティの名前とエンティティの値から成る名前と値のペアのディクショナリを使用し、エンティティをすべてマークする必要があります。 エンティティの値は、発話の例のテキストに表示されているものと正確に一致している必要があります。

Partial screenshot showing the labeled example utterance in the portal.

アプリ ID、バージョン ID、および例を指定して examples.add を呼び出します。

# Define labeled example
labeledExampleUtteranceWithMLEntity = {
    "text": "I want two small seafood pizzas with extra cheese.",
    "intentName": intentName,
    "entityLabels": [
        {
            "startCharIndex": 7,
            "endCharIndex": 48,
            "entityName": "Pizza order",
            "children": [
                {
                    "startCharIndex": 7,
                    "endCharIndex": 30,
                    "entityName": "Pizza",
                    "children": [
                        {
                            "startCharIndex": 7,
                            "endCharIndex": 9,
                            "entityName": "Quantity"
                        },
                        {
                            "startCharIndex": 11,
                            "endCharIndex": 15,
                            "entityName": "Size"
                        },
                        {
                            "startCharIndex": 17,
                            "endCharIndex": 23,
                            "entityName": "Type"
                        }]
                },
                {
                    "startCharIndex": 37,
                    "endCharIndex": 48,
                    "entityName": "Toppings",
                    "children": [
                        {
                            "startCharIndex": 37,
                            "endCharIndex": 41,
                            "entityName": "Quantity"
                        },
                        {
                            "startCharIndex": 43,
                            "endCharIndex": 48,
                            "entityName": "Type"
                        }]
                }
            ]
        }
    ]
}

print("Labeled Example Utterance:", labeledExampleUtteranceWithMLEntity)

# Add an example for the entity.
# Enable nested children to allow using multiple models with the same name.
# The quantity subentity and the phraselist could have the same exact name if this is set to True
client.examples.add(app_id, versionId, labeledExampleUtteranceWithMLEntity, { "enableNestedChildren": True })

アプリをトレーニングする

モデルの作成を終えたら、このバージョンのモデルに合わせて LUIS アプリをトレーニングする必要があります。 トレーニングを済ませたモデルは、コンテナーで使用したり、ステージング スロットまたは製品スロットに公開したりできます。

train.train_version メソッドでは、アプリ ID とバージョン ID が必要です。

このクイックスタートで示したような非常に小さなモデルであれば、トレーニングが短時間で完了します。 運用レベルのアプリケーションの場合には、アプリのトレーニングに、トレーニングが成功したかどうかと、そのタイミングを確認するための get_status メソッドに対するポーリング呼び出しが含まれます。 応答は、オブジェクトごとの状態を格納した ModelTrainingInfo オブジェクトの一覧です。 トレーニングが完了したと判定されるには、オブジェクトがすべて成功している必要があります。

client.train.train_version(app_id, versionId)
waiting = True
while waiting:
    info = client.train.get_status(app_id, versionId)

    # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
    waiting = any(map(lambda x: 'Queued' == x.details.status or 'InProgress' == x.details.status, info))
    if waiting:
        print ("Waiting 10 seconds for training to complete...")
        time.sleep(10)
    else: 
        print ("trained")
        waiting = False

アプリを運用スロットに公開する

app.publish メソッドを使用して、LUIS アプリを公開します。 これにより、トレーニング済みの最新バージョンがエンドポイントの指定されたスロットに公開されます。 クライアント アプリケーションではこのエンドポイントを使用して、意図の予測とエンティティの抽出の対象となるユーザー発話を送信します。

# Mark the app as public so we can query it using any prediction endpoint.
# Note: For production scenarios, you should instead assign the app to your own LUIS prediction endpoint. See:
# https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-how-to-azure-subscription#assign-a-resource-to-an-app
client.apps.update_settings(app_id, is_public=True)

responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)

予測ランタイム クライアントを認証する

自分のキーと共に資格情報オブジェクトを使用し、それを自分のエンドポイントと共に使用して LUISRuntimeClientConfiguration オブジェクトを作成します。

注意事項

このクイックスタートでは、ランタイム資格情報の一部として作成キーを使います。 作成キーを使用すると、いくつかのクエリを使用してランタイムにクエリを実行できます。 ステージングおよび運用レベルのコードでは、作成キーを予測ランタイム キーで置き換えます。

runtimeCredentials = CognitiveServicesCredentials(predictionKey)
clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)

ランタイムから予測を取得する

次のコードを追加して、予測ランタイムへの要求を作成します。

ユーザーの発話は、prediction_request オブジェクトの一部です。

get_slot_prediction メソッドには、アプリ ID、スロット名、要求を満たす予測要求オブジェクトなど、いくつかのパラメーターが必要です。 詳細、すべての意図の表示、ログなど、その他のオプションは省略可能です。 この要求により、PredictionResponse オブジェクトが返されます。

# Production == slot name
predictionRequest = { "query" : "I want two small pepperoni pizzas with more salsa" }

predictionResponse = clientRuntime.prediction.get_slot_prediction(app_id, "Production", predictionRequest)
print("Top intent: {}".format(predictionResponse.prediction.top_intent))
print("Sentiment: {}".format (predictionResponse.prediction.sentiment))
print("Intents: ")

for intent in predictionResponse.prediction.intents:
    print("\t{}".format (json.dumps (intent)))
print("Entities: {}".format (predictionResponse.prediction.entities))

予測応答は、意図と検出されたエンティティを含む JSON オブジェクトです。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

アプリケーションの実行

クイック スタート ファイルで python コマンドを使用して、アプリケーションを実行します。

python authoring_and_predict.py

このクイック スタートでは、3 つの REST 呼び出しを順番に実行します。

リファレンス ドキュメント

前提条件

  • 無料の LUIS アカウント。

  • Visual Studio Code などのテキスト エディター。

  • コマンド ライン プログラム cURL。 cURL プログラムは、macOS、ほとんどの Linux ディストリビューション、Windows 10 ビルド 1803 以降に既にインストールされています。

    cURL をインストールする必要がある場合は、cURL ダウンロード ページから cURL をダウンロードできます。

Pizza アプリを作成する

pizza アプリを作成します。

  1. pizza-app-for-luis-v6.json を選択し、pizza-app-for-luis.json ファイルの GitHub ページを表示します。
  2. [Raw] ボタンを右クリックするか長押しし、[名前を付けてリンク先を保存] を選択して pizza-app-for-luis.json をコンピューターに保存します。
  3. LUIS ポータルにサインインします。
  4. [マイ アプリ] を選択します。
  5. [マイアプリ] ページで、 [+ New app for conversation](+ 会話用の新しいアプリ) を選択します。
  6. [JSON としてインポート] を選択します。
  7. [Import new app](新しいアプリのインポート) ダイアログで、 [ファイルの選択] ボタンを選択します。
  8. ダウンロードした pizza-app-for-luis.json ファイルを選択し、pizza-app-for-luis.json を選択します。
  9. [新しいアプリのインポート] ダイアログの [名前] フィールドに Pizza アプリの名前を入力し、 [完了] ボタンを選択します。

アプリがインポートされます。

[How to create an effective LUIS app](効果的な LUIS アプリを作成する方法) ダイアログが表示されたら閉じます。

Pizza アプリをトレーニングして発行する

[意図] ページに Pizza アプリの意図一覧が表示されるはずです。

  1. LUIS Web サイトの右上にある [Train](トレーニング) ボタンを選択します。

    Train button

  2. [トレーニング] ボタンが無効になると、トレーニングが完了します。

チャットボットや他のクライアント アプリケーションで LUIS の予測を受け取るには、アプリを予測エンドポイントに公開する必要があります。

  1. 右上のナビゲーションで [公開] を選択します。

    A screenshot of the button for publishing to the endpoint.

  2. [運用] スロットを選択し、 [完了] を選択します。

    A screenshot of LUIS publishing to the endpoint.

  3. 通知の [エンドポイントの URL にアクセス] を選択して [Azure リソース] ページに移動します。 アプリに関連付けられている予測リソースがある場合にのみ、URL が表示されます。 また、 [管理] ページをクリックして [Azure リソース] ページを表示することもできます。

    A screenshot of a message showing the app has been published.

作成リソースを Pizza アプリに追加する

  1. [管理] を選択します。
  2. [Azure リソース] を選択します。
  3. [Authoring Resource](作成リソース) を選択します。
  4. [Change authoring resource](作成リソースを変更する) を選択します。

作成リソースがある場合は、作成リソースの [テナント名][サブスクリプション名] 、および [LUIS リソース名] を入力します。

作成リソースがない場合は、次のようにします。

  1. [新しいリソースの作成] を選択します。
  2. [テナント名][リソース名][サブスクリプション名][Azure リソース グループ名] を入力します。

これで Pizza アプリを使用する準備ができました。

Pizza アプリのアクセス値を記録する

新しい Pizza アプリを使用するには、Pizza アプリのアプリ ID、オーサリング キー、作成エンドポイントが必要です。 予測を取得するには、個別の予測エンドポイントと予測キーが必要です。

これらの値を見つけるには:

  1. [意図] ページから [管理] を選択します。
  2. [アプリケーション設定] ページから [アプリ ID] を記録します。
  3. [Azure リソース] を選択します。
  4. [Authoring Resource](作成リソース) を選択します。
  5. [Authoring Resource](作成リソース)[予測リソース] タブで、主キーを記録します。 この値が、オーサリング キーです。
  6. [エンドポイント URL] を記録します。 この値が、作成エンドポイントです。

Pizza アプリをトレーニングするための JSON ファイルを作成する

発話の 3 つの例を含む JSON ファイルを作成するには、次の JSON データを ExampleUtterances.JSON という名前のファイルに保存します。

[
  {
    "text": "order a pizza",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "order a large pepperoni pizza",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 6,
        "endCharIndex": 28
      },
      {
        "entityName": "FullPizzaWithModifiers",
        "startCharIndex": 6,
        "endCharIndex": 28
      },
      {
        "entityName": "PizzaType",
        "startCharIndex": 14,
        "endCharIndex": 28
      },
      {
        "entityName": "Size",
        "startCharIndex": 8,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "I want two large pepperoni pizzas on thin crust",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 7,
        "endCharIndex": 46
      },
      {
        "entityName": "FullPizzaWithModifiers",
        "startCharIndex": 7,
        "endCharIndex": 46
      },
      {
        "entityName": "PizzaType",
        "startCharIndex": 17,
        "endCharIndex": 32
      },
      {
        "entityName": "Size",
        "startCharIndex": 11,
        "endCharIndex": 15
      },
      {
        "entityName": "Quantity",
        "startCharIndex": 7,
        "endCharIndex": 9
      },
      {
        "entityName": "Crust",
        "startCharIndex": 37,
        "endCharIndex": 46
      }
    ]
  }
]`

発話の例の JSON は、特定の形式に従っています。

text フィールドには、サンプルの発話テキストが含まれています。 intentName フィールドは、LUIS アプリの既存の意図の名前と対応している必要があります。 entityLabels フィールドは必須です。 どのエンティティもラベル付けしない場合は、空の配列を指定します。

entityLabels 配列が空でない場合、entityName フィールドで示されるエンティティを startCharIndex および endCharIndex で指定する必要があります。 インデックスは 0 から始まります。 テキスト内のスペースでラベルを開始または終了すると、発話を追加する API 呼び出しは失敗します。

発話の例を追加する

  1. 発話の例のバッチをアップロードするには、次のコマンドをテキスト エディターにコピーします。

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/examples?verbose=true&show-all-intents=true" ^
          --request POST ^
          --header "Content-Type:application/json" ^
          --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***" ^
          --data "@ExampleUtterances.JSON"
    
  2. ***YOUR- で始まる値を実際の値に置き換えます。

    Information 目的
    ***YOUR-AUTHORING-ENDPOINT*** 作成 URL エンドポイント。 (例: https://REPLACE-WITH-YOUR-RESOURCE-NAME.api.cognitive.microsoft.com/")。 リソース名は、リソースの作成時に設定します。
    ***YOUR-APP-ID*** LUIS アプリ ID。
    ***YOUR-APP-VERSION*** LUIS アプリのバージョン。 Pizza アプリの場合、バージョン番号は "0.1" です (引用符は除く)。
    ***YOUR-AUTHORING-KEY*** 32 文字の実際の作成キー。

    割り当てられたキーとリソースは、LUIS ポータルの [Manage](管理) セクションの [Azure リソース] ページで確認できます。 アプリ ID は、同じ [Manage](管理) セクションの [アプリケーションの設定] ページで入手できます。

    重要

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

  3. コマンド プロンプト (Windows) またはターミナル (macOS と Linux) を起動し、ExampleUtterances.JSON ファイルを保存したディレクトリに移動します。

  4. エディターから cURL コマンドをコピーし、コマンド プロンプト (Windows) またはターミナル (macOS と Linux) に貼り付けます。 Enter キーを押してコマンドを実行します。

    次のような応答が表示されます。

    [{"value":{"ExampleId":1255129706,"UtteranceText":"order a pizza"},"hasError":false},{"value":{"ExampleId":1255129707,"UtteranceText":"order a large pepperoni pizza"},"hasError":false},{"value":{"ExampleId":1255129708,"UtteranceText":"i want two large pepperoni pizzas on thin crust"},"hasError":false}]
    

    読みやすいように書式設定された出力を次に示します。

    [
      {
        "value": {
          "ExampleId": 1255129706,
          "UtteranceText": "order a pizza"
        },
        "hasError": false
      },
      {
        "value": {
          "ExampleId": 1255129707,
          "UtteranceText": "order a large pepperoni pizza"
        },
        "hasError": false
      },
      {
        "value": {
          "ExampleId": 1255129708,
          "UtteranceText": "i want two large pepperoni pizzas on thin crust"
        },
        "hasError": false
      }
    ]
    

Pizza アプリ モデルをトレーニングする

  1. Pizza アプリのトレーニング セッションを開始するには、次のコマンドをテキスト エディターにコピーします。

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/train?verbose=true&show-all-intents=true" ^
          --data "" ^
          --request POST ^
          --header "Content-Type:application/json" ^
          --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***"
    
  2. 前の手順と同様に、***YOUR- で始まる値を実際の値に置き換えます。

  3. エディターから cURL コマンドをコピーし、コマンド プロンプト (Windows) またはターミナル (macOS と Linux) に貼り付けます。 Enter キーを押してコマンドを実行します。

    次のような応答が表示されます。

    {"statusId":2,"status":"UpToDate"}
    

    読みやすいように書式設定された出力を次に示します。

    {
      "statusId": 2,
      "status": "UpToDate"
    }
    

トレーニングの状態を取得する

  1. トレーニング セッションのトレーニング状態を取得するには、次のコマンドをテキスト エディターにコピーします。

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/train?verbose=true&show-all-intents=true" ^
            --request GET ^
            --header "Content-Type:application/json" ^
            --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***"
    
  2. 前の手順と同様に、***YOUR- で始まる値を実際の値に置き換えます。

  3. エディターから cURL コマンドをコピーし、コマンド プロンプト (Windows) またはターミナル (macOS と Linux) に貼り付けます。 Enter キーを押してコマンドを実行します。

    次のような応答が表示されます。

    [{"modelId":"8eb7ad8f-5db5-4c28-819b-ca3905fffd80","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6f53bc92-ae54-44ce-bc4e-010d1f8cfda0","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6cb17888-ad6e-464c-82c0-d37fd1f2c4f8","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"a16fc4fd-1949-4e77-9de3-30369f16c3a5","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6bacdb75-1889-4f93-8971-8c8995ff8960","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"be963f4c-4898-48d7-9eba-3c6af0867b9d","details":{"statusId":2,"status":"UpToDate","exampleCount":171}}]
    

    読みやすいように書式設定された出力を次に示します。

    [
      {
        "modelId": "8eb7ad8f-5db5-4c28-819b-ca3905fffd80",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6f53bc92-ae54-44ce-bc4e-010d1f8cfda0",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6cb17888-ad6e-464c-82c0-d37fd1f2c4f8",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "a16fc4fd-1949-4e77-9de3-30369f16c3a5",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6bacdb75-1889-4f93-8971-8c8995ff8960",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "be963f4c-4898-48d7-9eba-3c6af0867b9d",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      }
    ]
    

予測エンドポイントから意図を取得する

cURL を使用して、予測エンドポイントのクエリを実行し、予測結果を取得します。

Note

このコマンドは予測エンドポイントを使用します。

  1. 次のコマンドをテキスト エディターにコピーします。

    curl "https://***YOUR-PREDICTION-ENDPOINT***/luis/prediction/v3.0/apps/***YOUR-APP-ID***/slots/production/predict" ^
          --request GET ^
          --get ^
          --data "subscription-key=***YOUR-PREDICTION-KEY***" ^
          --data "verbose=true" ^
          --data "show-all-intents=true" ^
          --data-urlencode "query=I want two large pepperoni pizzas on thin crust please"
    
  2. ***YOUR- で始まる値を実際の値に置き換えます。

    Information 目的
    ***YOUR-PREDICTION-ENDPOINT*** 予測 URL エンドポイント。 LUIS ポータルのアプリの [Azure リソース] ページにあります。
    たとえば、「 https://westus.api.cognitive.microsoft.com/ 」のように入力します。
    ***YOUR-APP-ID*** アプリ ID。 LUIS ポータルのアプリの [アプリケーションの設定] ページにあります。
    ***YOUR-PREDICTION-KEY*** 32 文字の予測キー。 LUIS ポータルのアプリの [Azure リソース] ページにあります。
  3. テキストをコンソール ウィンドウにコピーし、Enter キーを押してコマンドを実行します。

  4. JSON として返される予測応答を確認します。

    {"query":"I want two large pepperoni pizzas on thin crust please","prediction":{"topIntent":"ModifyOrder","intents":{"ModifyOrder":{"score":1.0},"None":{"score":8.55E-09},"Greetings":{"score":1.82222226E-09},"CancelOrder":{"score":1.47272727E-09},"Confirmation":{"score":9.8125E-10}},"entities":{"Order":[{"FullPizzaWithModifiers":[{"PizzaType":["pepperoni pizzas"],"Size":[["Large"]],"Quantity":[2],"Crust":[["Thin"]],"$instance":{"PizzaType":[{"type":"PizzaType","text":"pepperoni pizzas","startIndex":17,"length":16,"score":0.9978157,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Size":[{"type":"SizeList","text":"large","startIndex":11,"length":5,"score":0.9984481,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Quantity":[{"type":"builtin.number","text":"two","startIndex":7,"length":3,"score":0.999770939,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Crust":[{"type":"CrustList","text":"thin crust","startIndex":37,"length":10,"score":0.933985531,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}]}}],"$instance":{"FullPizzaWithModifiers":[{"type":"FullPizzaWithModifiers","text":"two large pepperoni pizzas on thin crust","startIndex":7,"length":40,"score":0.90681237,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}]}}],"ToppingList":[["Pepperoni"]],"$instance":{"Order":[{"type":"Order","text":"two large pepperoni pizzas on thin crust","startIndex":7,"length":40,"score":0.9047088,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"ToppingList":[{"type":"ToppingList","text":"pepperoni","startIndex":17,"length":9,"modelTypeId":5,"modelType":"List Entity Extractor","recognitionSources":["model"]}]}}}}
    

    読みやすくするために書式設定された JSON 応答:

    {
      "query": "I want two large pepperoni pizzas on thin crust please",
      "prediction": {
        "topIntent": "ModifyOrder",
        "intents": {
          "ModifyOrder": {
            "score": 1.0
          },
          "None": {
            "score": 8.55e-9
          },
          "Greetings": {
            "score": 1.82222226e-9
          },
          "CancelOrder": {
            "score": 1.47272727e-9
          },
          "Confirmation": {
            "score": 9.8125e-10
          }
        },
        "entities": {
          "Order": [
            {
              "FullPizzaWithModifiers": [
                {
                  "PizzaType": [
                    "pepperoni pizzas"
                  ],
                  "Size": [
                    [
                      "Large"
                    ]
                  ],
                  "Quantity": [
                    2
                  ],
                  "Crust": [
                    [
                      "Thin"
                    ]
                  ],
                  "$instance": {
                    "PizzaType": [
                      {
                        "type": "PizzaType",
                        "text": "pepperoni pizzas",
                        "startIndex": 17,
                        "length": 16,
                        "score": 0.9978157,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Size": [
                      {
                        "type": "SizeList",
                        "text": "large",
                        "startIndex": 11,
                        "length": 5,
                        "score": 0.9984481,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Quantity": [
                      {
                        "type": "builtin.number",
                        "text": "two",
                        "startIndex": 7,
                        "length": 3,
                        "score": 0.999770939,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Crust": [
                      {
                        "type": "CrustList",
                        "text": "thin crust",
                        "startIndex": 37,
                        "length": 10,
                        "score": 0.933985531,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ]
                  }
                }
              ],
              "$instance": {
                "FullPizzaWithModifiers": [
                  {
                    "type": "FullPizzaWithModifiers",
                    "text": "two large pepperoni pizzas on thin crust",
                    "startIndex": 7,
                    "length": 40,
                    "score": 0.90681237,
                    "modelTypeId": 1,
                    "modelType": "Entity Extractor",
                    "recognitionSources": [
                      "model"
                    ]
                  }
                ]
              }
            }
          ],
          "ToppingList": [
            [
              "Pepperoni"
            ]
          ],
          "$instance": {
            "Order": [
              {
                "type": "Order",
                "text": "two large pepperoni pizzas on thin crust",
                "startIndex": 7,
                "length": 40,
                "score": 0.9047088,
                "modelTypeId": 1,
                "modelType": "Entity Extractor",
                "recognitionSources": [
                  "model"
                ]
              }
            ],
            "ToppingList": [
              {
                "type": "ToppingList",
                "text": "pepperoni",
                "startIndex": 17,
                "length": 9,
                "modelTypeId": 5,
                "modelType": "List Entity Extractor",
                "recognitionSources": [
                  "model"
                ]
              }
            ]
          }
        }
      }
    }
    

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

LUIS ポータルからアプリを削除し、Azure portal から Azure リソースを削除することができます。

REST API を使用している場合は、このクイック スタートが完了したら、ファイル システムから ExampleUtterances.JSON ファイルを削除してください。

トラブルシューティング

  • クライアント ライブラリへの認証 - 認証エラーは通常、間違ったキーとエンドポイントが使用されたことを示します。 このクイックスタートでは、便宜上、予測ランタイムの作成キーとエンドポイントを使用しますが、これは月間クォータをまだ使っていない場合にのみ機能します。 作成キーとエンドポイントを使用できない場合は、予測ランタイム SDK クライアント ライブラリにアクセスするときに予測ランタイム キーとエンドポイントを使用する必要があります。
  • エンティティの作成 - このチュートリアルで使用されている入れ子になった機械学習エンティティの作成でエラーが発生した場合は、コードをコピーした後で別のエンティティを作成するようにコードを変更していないことを確認してください。
  • 発話の例の作成 - このチュートリアルで使用されているラベル付きの発話の例の作成でエラーが発生した場合は、コードをコピーした後で別のラベル付きの例を作成するようにコードを変更していないことを確認してください。
  • トレーニング - トレーニング エラーが発生した場合、これは通常、(発話の例が含まれる意図がない) 空のアプリ、または無効な形式の意図またはエンティティが含まれるアプリを示します。
  • その他のエラー - コードではテキストおよび JSON オブジェクトを使用してクライアント ライブラリを呼び出すため、コードを変更していないことを確認してください。

これ以外のエラー - 上記の一覧に記載されていないエラーが発生した場合は、このページの下部でフィードバックを送信してお知らせください。 インストールしたクライアント ライブラリのプログラミング言語とバージョンを含めます。

次の手順