快速入门:语言理解 (LUIS) 创作客户端库Quickstart: Language Understanding (LUIS) authoring client library

语言理解 (LUIS) 客户端库入门。Get started with the Language Understanding (LUIS) client library. 请按照以下步骤安装 SDK 并试用基本任务的示例代码。Follow these steps to install the SDK and try out the example code for basic tasks. 使用语言理解 (LUIS) 可在用户的自然语言对话文本中应用自定义的机器学习智能,以预测整体含义并提炼出相关的详细信息。Language Understanding (LUIS) enables you to apply custom machine-learning intelligence to a user's conversational, natural language text to predict overall meaning, and pull out relevant, detailed information.

使用适用于 .NET 的语言理解 (LUIS) 创作客户端库可以:Use the Language Understanding (LUIS) authoring client library for .NET to:

  • 创建应用Create an app
  • 添加意向、实体和示例言语Add intents, entities, and example utterances
  • 添加短语列表等特征Add features such as a phrase list
  • 训练和发布应用Train and publish app

参考文档 | 库源代码 | 创作包 (NuGet) | C# 示例Reference documentation | Library source code | Authoring Package (NuGet) | C# Samples

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅Azure subscription - Create one for trial
  • .NET Core 的当前版本。The current version of .NET Core.
  • 有了 Azure 订阅后,在 Azure 门户中创建语言理解创作资源,以获取创作密钥和终结点。Once you have your Azure subscription, create a Language Understanding authoring resource in the Azure portal to get your key and endpoint. 等待其部署并单击“转到资源”按钮。Wait for it to deploy and click the Go to resource button.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到语言理解创作。You will need the key and endpoint from the resource you create to connect your application to Language Understanding authoring. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart. 可以使用免费定价层 (F0) 来试用该服务。You can use the free pricing tier (F0) to try the service.

设置Setting up

新建 C# 应用程序Create a new C# application

在首选编辑器或 IDE 中创建新的 .NET Core 应用程序。Create a new .NET Core application in your preferred editor or IDE.

  1. 在控制台窗口(例如 CMD、PowerShell 或 Bash)中,使用 dotnet new 命令创建名为 language-understanding-quickstart 的新控制台应用。In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name language-understanding-quickstart. 此命令将创建包含单个源文件的简单“Hello World”C# 项目:Program.csThis command creates a simple "Hello World" C# project with a single source file: Program.cs.

    dotnet new console -n language-understanding-quickstart
    
  2. 将目录更改为新创建的应用文件夹。Change your directory to the newly created app folder.

  3. 可使用以下代码生成应用程序:You can build the application with:

    dotnet build
    

    生成输出不应包含警告或错误。The build output should contain no warnings or errors.

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

安装 SDKInstall the SDK

在应用程序目录中,使用以下命令安装适用于 .NET 的语言理解 (LUIS) 创作客户端库:Within the application directory, install the Language Understanding (LUIS) authoring client library for .NET with the following command:

dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring --version 3.0.0

如果你使用的是 Visual Studio IDE,客户端库可用作可下载的 NuGet 包。If you're using the Visual Studio IDE, the client library is available as a downloadable NuGet package.

对象模型Object model

语言理解 (LUIS) 创作客户端是对 Azure 进行身份验证的 LUISAuthoringClient 对象,其中包含创作密钥。The Language Understanding (LUIS) authoring client is a LUISAuthoringClient object that authenticates to Azure, which contains your authoring key.

创建客户端后,可以使用此客户端访问如下所述的功能:Once the client is created, use this client to access functionality including:

代码示例Code examples

这些代码片段演示如何使用适用于 .NET 的语言理解 (LUIS) 创作客户端库来执行以下操作:These code snippets show you how to do the following with the Language Understanding (LUIS) authoring client library for .NET:

添加依赖项Add the dependencies

在首选的编辑器或 IDE 中,从项目目录打开 Program.cs 文件。From the project directory, open the Program.cs file in your preferred editor or IDE. 将现有 using 代码替换为以下 using 指令:Replace the existing using code with the following using directives:

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

验证客户端Authenticate the client

  1. 创建一个变量,用于保存创作密钥和创作终结点。Create a variable to hold your authoring key and authoring endpoint.
// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}
  1. 使用密钥创建 ApiKeyServiceClientCredentials 对象,并在终结点中使用该对象创建一个 LUISAuthoringClient 对象。Create an ApiKeyServiceClientCredentials object with your key, and use it with your endpoint to create an LUISAuthoringClient object.
// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

创建 LUIS 应用Create a LUIS app

  1. 创建一个 LUIS 应用,用于包含保存意向、实体和示例言语的自然语言处理 (NLP) 模型。Create a LUIS app to contain the natural language processing (NLP) model holding intents, entities, and example utterances.

  2. 创建 ApplicationCreateObjectCreate a ApplicationCreateObject. 名称和语言区域性是必需的属性。The name and language culture are required properties.

  3. 调用 Apps.AddAsync 方法。Call the Apps.AddAsync method. 响应为应用 ID。The response is the app ID.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

为应用创建意向Create intent for the app

LUIS 应用模型中的主要对象是意向。The primary object in a LUIS app's model is the intent. 意向与用户言语意向的分组相符。The intent aligns's with a grouping of user utterance intentions. 用户可以提问,或者做出表述,指出希望机器人(或其他客户端应用程序)提供特定的有针对性响应。A user may ask a question, or make a statement looking for a particular intended response from a bot (or other client application). 意向的示例包括预订航班、询问目的地城市的天气,以及询问客户服务的联系信息。Examples of intentions are booking a flight, asking about weather in a destination city, and asking about contact information for customer service.

使用唯一意向的名称创建 ModelCreateObject,然后将应用 ID、版本 ID 和 ModelCreateObject 传递给 Model.AddIntentAsync 方法。Create a ModelCreateObject with the name of the unique intent then pass the app ID, version ID, and the ModelCreateObject to the Model.AddIntentAsync method. 响应为意向 ID。The response is the intent ID.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

为应用创建实体Create entities for the app

尽管实体不是必需的,但在大多数应用中都可以看到实体。While entities are not required, they are found in most apps. 实体从用户言语中提取信息,只有使用这些信息才能实现用户的意向。The entity extracts information from the user utterance, necessary to fullfil the user's intention. 有多种类型的预生成实体和自定义实体,每种实体具有自身的数据转换对象 (DTO) 模型。There are several types of prebuilt and custom entities, each with their own data transformation object (DTO) models. 在应用中添加的常见预生成实体包括 numberdatetimeV2geographyV2ordinalCommon prebuilt entities to add to your app include number, datetimeV2, geographyV2, ordinal.

AddEntities 方法创建一个包含两个角色的 Location 简单实体、一个 Class 简单实体和一个 Flight 复合实体,并添加多个预生成实体。This AddEntities method created a Location simple entity with two roles, a Class simple entity, a Flight composite entity and adds several prebuilt entities.

必须知道,实体不会使用意向进行标记。It is important to know that entities are not marked with an intent. 它们可以并且通常应用到多个意向。They can and usually do apply to many intents. 只会为特定的单个意向标记示例用户言语。Only example user utterances are marked for a specific, single intent.

实体的创建方法属于 Model 类的一部分。Creation methods for entities are part of the Model class. 每个实体类型有自身的数据转换对象 (DTO) 模型,该模型通常在 Models 命名空间中包含单词 modelEach entity type has its own data transformation object (DTO) model, usually containing the word model in the Models namespace.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

将示例言语添加到意向Add example utterance to intent

为了确定言语的意向并提取实体,应用需要言语示例。In order to determine an utterance's intention and extract entities, the app needs examples of utterances. 这些示例需要针对特定的单个意向,并且应该标记所有自定义实体。The examples need to target a specific, single intent and should mark all custom entities. 无需标记预生成实体。Prebuilt entities do not need to be marked.

通过创建 ExampleLabelObject 对象的列表来添加示例言语(每个示例言语对应于一个对象)。Add example utterances by creating a list of ExampleLabelObject objects, one object for each example utterance. 每个示例应使用实体名称和实体值的名称/值对字典来标记所有实体。Each example should mark all entities with a dictionary of name/value pairs of entity name and entity value. 实体值应与示例言语文本中显示的值完全相同。The entity value should be exactly as it appears in the text of the example utterance.

结合应用 ID、版本 ID 和示例列表调用 Examples.BatchAsyncCall Examples.BatchAsync with the app ID, version ID, and the list of examples. 该调用将以结果列表做出响应。The call responds with a list of results. 需要检查每个示例的结果,以确保该示例已成功添加到模型中。You need to check each example's result to make sure it was successfully added to the model.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

CreateUtteranceCreateLabel 方法是帮助你创建对象的实用工具方法。The CreateUtterance and CreateLabel methods are utility methods to help you create objects.

训练应用Train the app

创建模型后,需要为此模型版本训练 LUIS 应用。Once the model is created, the LUIS app needs to be trained for this version of the model. 训练后的模型可在容器中使用,或者将其发布到过渡槽或生产槽。A trained model can be used in a container, or published to the staging or product slots.

Train.TrainVersionAsync 方法需要应用 ID 和版本 ID。The Train.TrainVersionAsync method needs the app ID and the version ID.

极小的模型(如本快速入门中所示的模型)很快就能完成训练。A very small model, such as this quickstart shows, will train very quickly. 对于生产级应用程序,应用的训练应该包括轮询调用 GetStatusAsync 方法以确定训练何时或者是否成功。For production-level applications, training the app should include a polling call to the GetStatusAsync method to determine when or if the training succeeded. 响应是一个 ModelTrainingInfo 对象列表,其中分别列出了每个对象的状态。The response is a list of ModelTrainingInfo objects with a separate status for each object. 所有对象必须成功,才能将训练视为完成。All objects must be successful for the training to be considered complete.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

发布语言理解应用Publish a Language Understanding app

使用 PublishAsync 方法发布 LUIS 应用。Publish the LUIS app using the PublishAsync method. 这会将当前已训练的版本发布到终结点上的指定槽。This publishes the current trained version to the specified slot at the endpoint. 客户端应用程序使用此终结点发送用户言语,以预测意向和提取实体。Your client application uses this endpoint to send user utterances for prediction of intent and entity extraction.

// Note: Add the NuGet package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring to your solution.
// <Dependencies>
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
// </Dependencies>


/*
 * This sample builds a LUIS application, entities, and intents using the LUIS .NET SDK.
 * A separate sample trains and publishes the application.
 *
 * Be sure you understand how LUIS models work.  In particular, know what
 * intents, entities, and utterances are, and how they work together in the
 * context of a LUIS app. See the following:
 *
 * https://luis.azure.cn/welcome
 * /cognitive-services/luis/luis-concept-intent
 * /cognitive-services/luis/luis-concept-entity-types
 * /cognitive-services/luis/luis-concept-utterance
 */

namespace LUIS_CS
{
    // <ApplicationInfo>
    struct ApplicationInfo
    {
        public Guid ID;
        public string Version;
    }
    // </ApplicationInfo>

    class Program
    {
        // <Variables>
        private static readonly string authoring_key = "REPLACE-WITH-ASSIGNED-AUTHORING-KEY";
        
        private static readonly string authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/";
        // </Variables>

        static Program()
        {
            if (null == authoring_key)
            {
                throw new Exception("Please set variable: " + authoring_key);
            }
            if (null == authoring_endpoint)
            {
                throw new Exception("Please set variable: " + authoring_endpoint);
            }
        }

        // <AuthoringCreateApplication>
        // Return the application ID and version.
        async static Task<ApplicationInfo> CreateApplication(LUISAuthoringClient client)
        {
            string app_name =           String.Format("Contoso {0}", DateTime.Now);
            string app_description =    "Flight booking app built with LUIS .NET SDK.";
            string app_version =        "0.1";
            string app_culture =        "en-us";

            var app_info = new ApplicationCreateObject()
            {
                Name = app_name,
                InitialVersionId = app_version,
                Description = app_description,
                Culture = app_culture
            };
            var app_id = await client.Apps.AddAsync(app_info);
            Console.WriteLine("Created new LUIS application {0}\n with ID {1}.", app_info.Name, app_id);
            return new ApplicationInfo() { ID = app_id, Version = app_version };
        }
        // </AuthoringCreateApplication>

        // <AuthoringAddEntities>
        // Create entity objects
        async static Task AddEntities(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            // Add simple entity
            var simpleEntityIdLocation = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Location"
            });

            // Add 'Origin' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Origin"
            });

            // Add 'Destination' role to simple entity
            await client.Model.CreateEntityRoleAsync(app_info.ID, app_info.Version, simpleEntityIdLocation, new EntityRoleCreateObject()
            {
                Name = "Destination"
            });

            // Add simple entity
            var simpleEntityIdClass = await client.Model.AddEntityAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "Class"
            });


            // Add prebuilt number and datetime
            await client.Model.AddPrebuiltAsync(app_info.ID, app_info.Version, new List<string>
            {
                "number",
                "datetimeV2",
                "geographyV2",
                "ordinal"
            });

            // Composite entity
            await client.Model.AddCompositeEntityAsync(app_info.ID, app_info.Version, new CompositeEntityModel()
            {
                Name = "Flight",
                Children = new List<string>() { "Location", "Class", "number", "datetimeV2", "geographyV2", "ordinal" }
            });
            Console.WriteLine("Created entities Location, Class, number, datetimeV2, geographyV2, ordinal.");
        }
        // </AuthoringAddEntities>

        // <AuthoringAddIntents>
        async static Task AddIntents(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            await client.Model.AddIntentAsync(app_info.ID, app_info.Version, new ModelCreateObject()
            {
                Name = "FindFlights"
            });
            Console.WriteLine("Created intent FindFlights");
        }
        // </AuthoringAddIntents>

        // <AuthoringBatchAddUtterancesForIntent>
        async static Task AddUtterances(LUISAuthoringClient client, ApplicationInfo app_info)
        {
            var utterances = new List<ExampleLabelObject>()
            {
                CreateUtterance ("FindFlights", "find flights in economy to Madrid on July 1st", new Dictionary<string, string>() { {"Flight", "economy to Madrid"}, { "Location", "Madrid" }, { "Class", "economy" } }),
                CreateUtterance ("FindFlights", "find flights from seattle to London in first class", new Dictionary<string, string>() { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),
                CreateUtterance ("FindFlights", "find flights to London in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location", "London" }, { "Class", "first" } }),

                //Role not supported in SDK yet
                //CreateUtterance ("FindFlights", "find flights to Paris in first class", new Dictionary<string, string>()  { { "Flight", "London in first class" }, { "Location::Destination", "Paris" }, { "Class", "first" } })
            };
            var resultsList = await client.Examples.BatchAsync(app_info.ID, app_info.Version, utterances);

            foreach (var x in resultsList)
            {
                var result = (!x.HasError.GetValueOrDefault()) ? "succeeded": "failed";
                Console.WriteLine("{0} {1}", x.Value.ExampleId, result);
            }
        }
        // Create utterance with marked text for entities
        static ExampleLabelObject CreateUtterance(string intent, string utterance, Dictionary<string, string> labels)
        {
            var entity_labels = labels.Select(kv => CreateLabel(utterance, kv.Key, kv.Value)).ToList();
            return new ExampleLabelObject()
            {
                IntentName = intent,
                Text = utterance,
                EntityLabels = entity_labels
            };
        }
        // Mark beginning and ending of entity text in utterance
        static EntityLabelObject CreateLabel(string utterance, string key, string value)
        {
            var start_index = utterance.IndexOf(value, StringComparison.InvariantCultureIgnoreCase);
            return new EntityLabelObject()
            {
                EntityName = key,
                StartCharIndex = start_index,
                EndCharIndex = start_index + value.Length
            };
        }
        // </AuthoringBatchAddUtterancesForIntent>


        // <AuthoringTrainVersion>
        async static Task Train_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            var response = await client.Train.TrainVersionAsync(app.ID, app.Version);
            Console.WriteLine("Training status: " + response.Status);
        }
        // </AuthoringTrainVersion>


        // <AuthoringPublishVersionAndSlot>
        // Publish app, display endpoint URL for the published application.
        async static Task Publish_App(LUISAuthoringClient client, ApplicationInfo app)
        {
            ApplicationPublishObject obj = new ApplicationPublishObject
            {
                VersionId = app.Version,
                IsStaging = true
            };
            var info = await client.Apps.PublishAsync(app.ID, obj);
            Console.WriteLine("Endpoint URL: " + info.EndpointUrl);
        }
        // </AuthoringPublishVersionAndSlot>



        async static Task RunQuickstart()
        {
            // <AuthoringCreateClient>
            // Generate the credentials and create the client.
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(authoring_key);
            var client = new LUISAuthoringClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = authoring_endpoint
            };
            // </AuthoringCreateClient>


            Console.WriteLine("Creating application...");
            var app = await CreateApplication(client);
            Console.WriteLine();

            Console.WriteLine("Adding entities to application...");
            await AddEntities(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding intents to application...");
            await AddIntents(client, app);
            Console.WriteLine();

            Console.WriteLine("Adding utterances to application...");
            await AddUtterances(client, app);
            Console.WriteLine();

            Console.WriteLine("Training application...");
            await Train_App(client, app);
            Console.WriteLine("Waiting 30 seconds for training to complete...");
            System.Threading.Thread.Sleep(30000);
            Console.WriteLine();

            Console.WriteLine("Publishing application...");
            await Publish_App(client, app);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Task.WaitAll(RunQuickstart());
            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
    }
}

运行应用程序Run the application

从应用程序目录使用 dotnet run 命令运行应用程序。Run the application with the dotnet run command from your application directory.

dotnet run

清理资源Clean up resources

如果需要清理,可以删除 LUIS 应用。If you want to clean up, you can delete the LUIS app. 可以使用 DeleteAsync 方法删除应用。Deleting the app is done with the Apps.DeleteAsync method. 也可以从 LUIS 门户删除应用。You can also delete the app from the LUIS portal.

使用适用于 Node.js 的语言理解 (LUIS) 创作客户端库可以:Use the Language Understanding (LUIS) authoring client library for Node.js to:

  • 创建应用。Create an app.
  • 添加意向、实体和示例话语。Add intents, entities, and example utterances.
  • 添加短语列表等特征。Add features, such as a phrase list.
  • 训练和发布应用。Train and publish an app.
  • 删除应用Delete app

参考文档 | 库源代码 | 创作包 (NPM)运行时包 (NPM) | 示例Reference documentation | Library source code | Authoring Package (NPM), Runtime Package (NPM) | Samples

先决条件Prerequisites

设置Setting up

获取语言理解 (LUIS) 初学者密钥Get your Language Understanding (LUIS) starter key

通过创建 LUIS 创作资源,获取创作密钥Get your authoring key by creating a LUIS authoring resource. 保留密钥和密钥的终结点,你需要在代码文件的顶部将这些内容添加为字符串。Keep your key, and the endpoint of the key, you need to add these are strings at the top of the code file.

安装适用于 LUIS 创作的 NPM 库Install the NPM library for LUIS authoring

在应用程序目录中,使用以下命令安装依赖项:Within the application directory, install the dependencies with the following command:

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

对象模型Object model

语言理解 (LUIS) 创作客户端是对 Azure 进行身份验证的 LUISAuthoringClient 对象,其中包含创作密钥。The Language Understanding (LUIS) authoring client is a LUISAuthoringClient object that authenticates to Azure, which contains your authoring key.

创建客户端后,可以使用此客户端访问如下所述的功能:Once the client is created, use this client to access functionality including:

代码示例Code examples

这些代码片段展示了如何使用适用于 Node.js 的语言理解 (LUIS) 创作客户端库来执行以下操作:These code snippets show you how to do the following with the Language Understanding (LUIS) authoring client library for Node.js:

创建新的 Node.js 应用程序Create a new Node.js application

在你喜欢使用的编辑器或 IDE 中创建名为 luis_authoring_quickstart.js 的新文本文件。Create a new text file in your preferred editor or IDE named luis_authoring_quickstart.js. 然后,添加以下依赖项。Then add the following dependencies.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>
"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

验证客户端Authenticate the client

使用密钥创建 CognitiveServicesCredentials 对象,并在终结点中使用该对象创建一个 LUISAuthoringClient 对象。Create an CognitiveServicesCredentials object with your key, and use it with your endpoint to create an LUISAuthoringClient object.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

创建 LUIS 应用Create a LUIS app

  1. 创建一个 LUIS 应用,用于包含保存意向、实体和示例言语的自然语言处理 (NLP) 模型。Create a LUIS app to contain the natural language processing (NLP) model holding intents, entities, and example utterances.

  2. 创建 AppsOperation 对象的 add 方法,用于创建应用。Create a AppsOperation object's add method to create the app. 名称和语言区域性是必需的属性。The name and language culture are required properties.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

为应用创建意向Create intent for the app

LUIS 应用模型中的主要对象是意向。The primary object in a LUIS app's model is the intent. 意向与用户言语意向的分组相符。The intent aligns's with a grouping of user utterance intentions. 用户可以提问,或者做出表述,指出希望机器人(或其他客户端应用程序)提供特定的有针对性响应。A user may ask a question, or make a statement looking for a particular intended response from a bot (or other client application). 意向的示例包括预订航班、询问目的地城市的天气,以及询问客户服务的联系信息。Examples of intentions are booking a flight, asking about weather in a destination city, and asking about contact information for customer service.

model.add_intent 方法与唯一意向的名称配合使用,然后传递应用 ID、版本 ID 和新的意向名称。Use the model.add_intent method with the name of the unique intent then pass the app ID, version ID, and new intent name.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

为应用创建实体Create entities for the app

尽管实体不是必需的,但在大多数应用中都可以看到实体。While entities are not required, they are found in most apps. 实体从用户言语中提取信息,只有使用这些信息才能实现用户的意向。The entity extracts information from the user utterance, necessary to fullfil the user's intention. 有多种类型的预生成实体和自定义实体,每种实体具有自身的数据转换对象 (DTO) 模型。There are several types of prebuilt and custom entities, each with their own data transformation object (DTO) models. 在应用中添加的常见预生成实体包括 numberdatetimeV2geographyV2ordinalCommon prebuilt entities to add to your app include number, datetimeV2, geographyV2, ordinal.

add_entities 方法创建一个包含两个角色的 Location 简单实体、一个 Class 简单实体和一个 Flight 复合实体,并添加多个预生成实体。This add_entities method created a Location simple entity with two roles, a Class simple entity, a Flight composite entity and adds several prebuilt entities.

必须知道,实体不会使用意向进行标记。It is important to know that entities are not marked with an intent. 它们可以并且通常应用到多个意向。They can and usually do apply to many intents. 只会为特定的单个意向标记示例用户言语。Only example user utterances are marked for a specific, single intent.

实体的创建方法属于 Model 类的一部分。Creation methods for entities are part of the Model class. 每个实体类型有自身的数据转换对象 (DTO) 模型。Each entity type has its own data transformation object (DTO) model.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

将示例言语添加到意向Add example utterance to intent

为了确定言语的意向并提取实体,应用需要言语示例。In order to determine an utterance's intention and extract entities, the app needs examples of utterances. 这些示例需要针对特定的单个意向,并且应该标记所有自定义实体。The examples need to target a specific, single intent and should mark all custom entities. 无需标记预生成实体。Prebuilt entities do not need to be marked.

通过创建 ExampleLabelObject 对象的列表来添加示例言语(每个示例言语对应于一个对象)。Add example utterances by creating a list of ExampleLabelObject objects, one object for each example utterance. 每个示例应使用实体名称和实体值的名称/值对字典来标记所有实体。Each example should mark all entities with a dictionary of name/value pairs of entity name and entity value. 实体值应与示例言语文本中显示的值完全相同。The entity value should be exactly as it appears in the text of the example utterance.

结合应用 ID、版本 ID 和示例列表调用 examples.batchCall examples.batch with the app ID, version ID, and the list of examples. 该调用将以结果列表做出响应。The call responds with a list of results. 需要检查每个示例的结果,以确保该示例已成功添加到模型中。You need to check each example's result to make sure it was successfully added to the model.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

训练应用Train the app

创建模型后,需要为此模型版本训练 LUIS 应用。Once the model is created, the LUIS app needs to be trained for this version of the model. 训练后的模型可在容器中使用,或者将其发布到过渡槽或生产槽。A trained model can be used in a container, or published to the staging or product slots.

train.trainVersion 方法需要应用 ID 和版本 ID。The train.trainVersion method needs the app ID and the version ID.

极小的模型(如本快速入门中所示的模型)很快就能完成训练。A very small model, such as this quickstart shows, will train very quickly. 对于生产级应用程序,应用的训练应该包括轮询调用 get_status 方法以确定训练何时成功或者是否成功。For production-level applications, training the app should include a polling call to the get_status method to determine when or if the training succeeded. 响应是一个 ModelTrainingInfo 对象列表,其中分别列出了每个对象的状态。The response is a list of ModelTrainingInfo objects with a separate status for each object. 所有对象必须成功,才能将训练视为完成。All objects must be successful for the training to be considered complete.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

训练所有模型会花费一些时间。Training all models takes time. 使用 operationResult 检查训练状态。Use the operationResult to check the training status.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

发布语言理解应用Publish a Language Understanding app

使用 app.publish 方法发布 LUIS 应用。Publish the LUIS app using the app.publish method. 这会将当前已训练的版本发布到终结点上的指定槽。This publishes the current trained version to the specified slot at the endpoint. 客户端应用程序使用此终结点发送用户言语,以预测意向和提取实体。Your client application uses this endpoint to send user utterances for prediction of intent and entity extraction.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

删除语言理解应用Delete a Language Understanding app

使用 app.deleteMethod 方法删除 LUIS 应用。Delete the LUIS app using the app.deleteMethod method. 这将删除当前应用。This deletes the current app.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

列出语言理解应用List Language understanding apps

列出与语言理解密钥关联的应用列表Get a list of apps associated with the Language understanding key

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Create an application.
 * - Add intents to an application.
 * - Add entities to an application.
 * - Add utterances to an application.
 * - Train an application.
 * - Publish an application.
 * - Delete an application.
 * - List all applications.
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-authoring
 */
// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-authoring");
// </Dependencies>

// <Variables>
const key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY';

const endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
// </Variables>

// <AuthoringCreateClient>
const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
  inHeader: { "Ocp-Apim-Subscription-Key": key }
});
const luisAuthoringClient = new LUIS.LUISAuthoringClient(
  luisAuthoringCredentials,
  endpoint
);
// </AuthoringCreateClient>

// <utilForQuickstartOnlyToSimulateAsyncOperation >
const delayTimer = async timeInMs => {
  return await new Promise(resolve => {
    setTimeout(resolve, timeInMs);
  });
};
// </utilForQuickstartOnlyToSimulateAsyncOperation >

// <AuthoringCreateApplication>
const create_app = async () => {
  const create_app_payload = {
    name: "Contoso",
    description: "Flight booking app built with Azure SDK for Java.",
    initialVersionId: "0.1",
    culture: "en-us"
  };

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

  console.log(`Created LUIS app with ID ${createAppResult.body}`);

  return {
    id: createAppResult.body,
    version: create_app_payload.initialVersionId
  };
}
// </AuthoringCreateApplication>

// <AuthoringAddEntities>
const add_entities = async app_info => {
  const addEntityDestinationResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Destination" }
  );
  console.log("Entity Destination created.");

  const addEntityClassResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Class" }
  );
  console.log("Entity Class created.");

  const addEntityFlightResult = await luisAuthoringClient.model.addEntity(
    app_info.id,
    app_info.version,
    { name: "Flight" }
  );
  console.log("Entity Flight created.");
}
// </AuthoringAddEntities>

// <AuthoringAddIntents>
const add_intents = async app_info => {
  const addIntentFindFlightsResult = await luisAuthoringClient.model.addIntent(
    app_info.id,
    app_info.version,
    { name: "FindFlights" }
  );
  console.log("Intent FindFlights added.");
};
// </AuthoringAddIntents>

// <AuthoringBatchAddUtterancesForIntent>
const create_utterance = (intent, text, labels) => {
  var entityLabels = new Array();

  labels.forEach((value, key, map) => {
    const start_index = text.toLowerCase().indexOf(value.toLowerCase());
    const end_index = start_index + value.length;

    if (start_index > -1) {
      entityLabels.push({
        entityName: key,
        startCharIndex: start_index,
        endCharIndex: end_index
      });
    }
  });

  console.log(`Created ${entityLabels.length} entity labels.`);

  return { text: text, entityLabels: entityLabels, intentName: intent };
}

const add_utterances = async app_info => {
  const utterance_1 = create_utterance(
    "FindFlights",
    "find flights in economy to Madrid",
    new Map([
      ["Flight", "economy to Madrid"],
      ["Destination", "Madrid"],
      ["Class", "economy"]
    ])
  );
  const utterance_2 = create_utterance(
    "FindFlights",
    "find flights to London in first class",
    new Map([
      ["Flight", "London in first class"],
      ["Destination", "London"],
      ["Class", "first"]
    ])
  );
  const utterance_3 = create_utterance(
    "FindFlights",
    "find flights from seattle to London in first class",
    new Map([
      ["Flight", "flights from seattle to London in first class"],
      ["Location", "London"],
      ["Location", "Seattle"],
      ["Class", "first"]
    ])
  );

  const luisExamplesBatchResult = await luisAuthoringClient.examples.batch(
    app_info.id,
    app_info.version,
    [utterance_1, utterance_2, utterance_3]
  );
  console.log("Example utterances added.");
}
// </AuthoringBatchAddUtterancesForIntent>

// <AuthoringWaitForOperation>
const wait_for_operation = async app_info => {
  let operationResult = null;
  let modelUniqueStatus = ["InProgress"];

  while (
    modelUniqueStatus.includes("InProgress") ||
    modelUniqueStatus.includes("Queued")
  ) {
    await delayTimer(1000);

    operationResult = await luisAuthoringClient.train.getStatus(
      app_info.id,
      app_info.version
    );

    modelUniqueStatus = [
      ...new Set(operationResult.map(op => op.details.status))
    ];

    console.log(`Current model status: ${JSON.stringify(modelUniqueStatus)}`);
  }

  return operationResult;
}
// </AuthoringWaitForOperation>

// <AuthoringTrainVersion>
const train_app = async app_info => {
  const trainResult = await luisAuthoringClient.train.trainVersion(
    app_info.id,
    app_info.version
  );

  console.log("Waiting for train operation to finish...");

  const operationResult = await wait_for_operation(app_info);
}
// </AuthoringTrainVersion>

// <AuthoringPublishVersion>
const publish_app = async app_info => {
  const publishResult = await luisAuthoringClient.apps.publish(app_info.id, {
    versionId: app_info.version,
    isStaging: true
  });

  console.log(
    `Application published. Endpoint URL: ${publishResult.endpointUrl}`
  );
}
// </AuthoringPublishVersion>

// <AuthoringDeleteApp>
const delete_app = async app_info => {
  const deleteResult = await luisAuthoringClient.apps.deleteMethod(app_info.id);

  console.log(
    `Application with ID ${app_info.id} deleted. Operation result: ${deleteResult.message}`
  );
}
// </AuthoringDeleteApp>

// <AuthoringListApps>
const list_apps = async () => {
  const apps = await luisAuthoringClient.apps.list;

  for (let app of apps) {
    console.log(`ID ${app.id}, NAME ${app.name}`);
  }
}
// </AuthoringListApps>

// <Main>
const quickstart = async () => {
  //    list_apps();
  var app_info = await create_app();
  await add_entities(app_info);
  await add_intents(app_info);
  await add_utterances(app_info);
  await train_app(app_info);
  await publish_app(app_info);
  await delete_app(app_info);
}

try {
  quickstart();
} catch (error) {
  console.log(error);
}
// </Main>

运行应用程序Run the application

在快速入门文件中使用 node luis_authoring_quickstart.js 命令运行应用程序。Run the application with the node luis_authoring_quickstart.js command on your quickstart file.

node luis_authoring_quickstart.js

应用程序的命令行输出为:The command line output of the application is:

Created LUIS app with ID e137a439-b3e0-4e16-a7a8-a9746e0715f7
Entity Destination created.
Entity Class created.
Entity Flight created.
Intent FindFlights added.
Created 3 entity labels.
Created 3 entity labels.
Created 3 entity labels.
Example utterances added.
Waiting for train operation to finish...
Current model status: ["Queued"]
Current model status: ["InProgress"]
Current model status: ["InProgress"]
Current model status: ["InProgress"]
Current model status: ["Success"]
Application published. Endpoint URL: https://api.cognitive.azure.cn/luis/v2.0/apps/e137a439-b3e0-4e16-a7a8-a9746e0715f7
Application with ID e137a439-b3e0-4e16-a7a8-a9746e0715f7 deleted. Operation result: Operation Successful

可以使用适用于 Python 的语言理解 (LUIS) 创作客户端库执行以下操作:Use the Language Understanding (LUIS) authoring client library for Python to:

  • 创建应用。Create an app.
  • 添加意向、实体和示例话语。Add intents, entities, and example utterances.
  • 添加短语列表等特征。Add features, such as a phrase list.
  • 训练和发布应用。Train and publish an app.

参考文档 | 库源代码 | 创作包 (Pypi) | 示例Reference documentation | Library source code | Authoring Package (Pypi) | Samples

先决条件Prerequisites

  • Azure 订阅 - 创建试用订阅Azure subscription - Create one for trial
  • 最新版本的 Python 3.xThe current version of Python 3.x.
  • 有了 Azure 订阅后,在 Azure 门户中创建语言理解创作资源,以获取创作密钥和终结点。Once you have your Azure subscription, create a Language Understanding authoring resource in the Azure portal to get your key and endpoint. 等待其部署并单击“转到资源”按钮****。Wait for it to deploy and click the Go to resource button.
    • 需要从创建的资源获取密钥和终结点,以便将应用程序连接到语言理解创作。You will need the key and endpoint from the resource you create to connect your application to Language Understanding authoring. 你稍后会在快速入门中将密钥和终结点粘贴到下方的代码中。You'll paste your key and endpoint into the code below later in the quickstart. 可以使用免费定价层 (F0) 来试用该服务。You can use the free pricing tier (F0) to try the service.

设置Setting up

安装适用于 LUIS 的 Python 库Install the Python library for LUIS

在应用程序目录中,使用以下命令安装适用于 Python 的语言理解 (LUIS) 创作客户端库:Within the application directory, install the Language Understanding (LUIS) authoring client library for python with the following command:

pip install azure-cognitiveservices-language-luis

对象模型Object model

语言理解 (LUIS) 创作客户端是对 Azure 进行身份验证的 LUISAuthoringClient 对象,其中包含创作密钥。The Language Understanding (LUIS) authoring client is a LUISAuthoringClient object that authenticates to Azure, which contains your authoring key.

创建客户端后,可以使用此客户端访问如下所述的功能:Once the client is created, use this client to access functionality including:

代码示例Code examples

这些代码片段演示如何使用适用于 Python 的语言理解 (LUIS) 创作客户端库来执行以下操作:These code snippets show you how to do the following with the Language Understanding (LUIS) authoring client library for python:

创建新的 Python 应用程序Create a new python application

在首选编辑器或 IDE 中创建新的 Python 应用程序。Create a new Python application in your preferred editor or IDE. 然后导入以下库。Then import the following libraries.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)
# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

验证客户端Authenticate the client

使用密钥创建 CognitiveServicesCredentials 对象,并在终结点中使用该对象创建一个 LUISAuthoringClient 对象。Create an CognitiveServicesCredentials object with your key, and use it with your endpoint to create an LUISAuthoringClient object.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

创建 LUIS 应用Create a LUIS app

  1. 创建一个 LUIS 应用,用于包含保存意向、实体和示例言语的自然语言处理 (NLP) 模型。Create a LUIS app to contain the natural language processing (NLP) model holding intents, entities, and example utterances.

  2. 创建 AppsOperation 对象的 add 方法,用于创建应用。Create a AppsOperation object's add method to create the app. 名称和语言区域性是必需的属性。The name and language culture are required properties.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

为应用创建意向Create intent for the app

LUIS 应用模型中的主要对象是意向。The primary object in a LUIS app's model is the intent. 意向与用户言语意向的分组相符。The intent aligns's with a grouping of user utterance intentions. 用户可以提问,或者做出表述,指出希望机器人(或其他客户端应用程序)提供特定的有针对性响应。A user may ask a question, or make a statement looking for a particular intended response from a bot (or other client application). 意向的示例包括预订航班、询问目的地城市的天气,以及询问客户服务的联系信息。Examples of intentions are booking a flight, asking about weather in a destination city, and asking about contact information for customer service.

model.add_intent 方法与唯一意向的名称配合使用,然后传递应用 ID、版本 ID 和新的意向名称。Use the model.add_intent method with the name of the unique intent then pass the app ID, version ID, and new intent name.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

为应用创建实体Create entities for the app

尽管实体不是必需的,但在大多数应用中都可以看到实体。While entities are not required, they are found in most apps. 实体从用户言语中提取信息,只有使用这些信息才能实现用户的意向。The entity extracts information from the user utterance, necessary to fullfil the user's intention. 有多种类型的预生成实体和自定义实体,每种实体具有自身的数据转换对象 (DTO) 模型。There are several types of prebuilt and custom entities, each with their own data transformation object (DTO) models. 在应用中添加的常见预生成实体包括 numberdatetimeV2geographyV2ordinalCommon prebuilt entities to add to your app include number, datetimeV2, geographyV2, ordinal.

add_entities 方法创建一个包含两个角色的 Location 简单实体、一个 Class 简单实体和一个 Flight 复合实体,并添加多个预生成实体。This add_entities method created a Location simple entity with two roles, a Class simple entity, a Flight composite entity and adds several prebuilt entities.

必须知道,实体不会使用意向进行标记。It is important to know that entities are not marked with an intent. 它们可以并且通常应用到多个意向。They can and usually do apply to many intents. 只会为特定的单个意向标记示例用户言语。Only example user utterances are marked for a specific, single intent.

实体的创建方法属于 ModelOperations 类的一部分。Creation methods for entities are part of the ModelOperations class. 每个实体类型有自身的数据转换对象 (DTO) 模型。Each entity type has its own data transformation object (DTO) model.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

将示例言语添加到意向Add example utterance to intent

为了确定言语的意向并提取实体,应用需要言语示例。In order to determine an utterance's intention and extract entities, the app needs examples of utterances. 这些示例需要针对特定的单个意向,并且应该标记所有自定义实体。The examples need to target a specific, single intent and should mark all custom entities. 无需标记预生成实体。Prebuilt entities do not need to be marked.

通过创建 ExampleLabelObject 对象的列表来添加示例言语(每个示例言语对应于一个对象)。Add example utterances by creating a list of ExampleLabelObject objects, one object for each example utterance. 每个示例应使用实体名称和实体值的名称/值对字典来标记所有实体。Each example should mark all entities with a dictionary of name/value pairs of entity name and entity value. 实体值应与示例言语文本中显示的值完全相同。The entity value should be exactly as it appears in the text of the example utterance.

结合应用 ID、版本 ID 和示例列表调用 examples.batchCall examples.batch with the app ID, version ID, and the list of examples. 该调用将以结果列表做出响应。The call responds with a list of results. 需要检查每个示例的结果,以确保该示例已成功添加到模型中。You need to check each example's result to make sure it was successfully added to the model.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

训练应用Train the app

创建模型后,需要为此模型版本训练 LUIS 应用。Once the model is created, the LUIS app needs to be trained for this version of the model. 训练后的模型可在容器中使用,或者将其发布到过渡槽或生产槽。A trained model can be used in a container, or published to the staging or product slots.

train.train_version 方法需要应用 ID 和版本 ID。The train.train_version method needs the app ID and the version ID.

极小的模型(如本快速入门中所示的模型)很快就能完成训练。A very small model, such as this quickstart shows, will train very quickly. 对于生产级应用程序,应用的训练应该包括轮询调用 get_status 方法以确定训练何时成功或者是否成功。For production-level applications, training the app should include a polling call to the get_status method to determine when or if the training succeeded. 响应是一个 ModelTrainingInfo 对象列表,其中分别列出了每个对象的状态。The response is a list of ModelTrainingInfo objects with a separate status for each object. 所有对象必须成功,才能将训练视为完成。All objects must be successful for the training to be considered complete.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

发布语言理解应用Publish a Language Understanding app

使用 app.publish 方法发布 LUIS 应用。Publish the LUIS app using the app.publish method. 这会将当前已训练的版本发布到终结点上的指定槽。This publishes the current trained version to the specified slot at the endpoint. 客户端应用程序使用此终结点发送用户言语,以预测意向和提取实体。Your client application uses this endpoint to send user utterances for prediction of intent and entity extraction.

# Azure Language Understanding (LUIS) - Build App
#
# This script builds a LUIS app, entities, and intents using the Python
# LUIS SDK.  A separate sample trains and publishes the app.
#
# This script requires the Cognitive Services LUIS Python module:
#     python -m pip install azure-cognitiveservices-language-luis
#
# This script runs under Python 3.4 or later.

# Be sure you understand how LUIS models work.  In particular, know what
# intents, entities, and utterances are, and how they work together in the
# context of a LUIS app. See the following:
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis/luis-concept-intent
# /cognitive-services/luis/luis-concept-entity-types
# /cognitive-services/luis/luis-concept-utterance

# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.cn/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint, CognitiveServicesCredentials(authoring_key))
# </Client>

# <createApp>
def create_app():
    # Create a new LUIS app
    app_name    = "Contoso {}".format(datetime.datetime.now())
    app_desc    = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale  = "en-us"

    app_id = client.apps.add(dict(name=app_name,
                                    initial_version_id=app_version,
                                    description=app_desc,
                                    culture=app_locale))

    print("Created LUIS app {}\n    with ID {}".format(app_name, app_id))
    return app_id, app_version
# </createApp>

# Declare entities:
#
#   Destination - A simple entity that will hold the flight destination
#
#   Class - A hierarchical entity that will hold the flight class
#           (First, Business, or Economy)
#
#   Flight - A composite entity represeting the flight (including
#               class and destination)
#
# Creating an entity (or other LUIS object) returns its ID.
# We don't use IDs further in this script, so we don't keep the return value.
# <addEntities>
def add_entities(app_id, app_version):

    destinationEntityId = client.model.add_entity(app_id, app_version, name="Destination")
    print("destinationEntityId {} added.".format(destinationEntityId))

    classEntityId = client.model.add_entity(app_id, app_version, name="Class")
    print("classEntityId {} added.".format(classEntityId))

    flightEntityId = client.model.add_entity(app_id, app_version, name="Flight")
    print("flightEntityId {} added.".format(flightEntityId))

# </addEntities>

# Declare an intent, FindFlights, that recognizes a user's Flight request
# Creating an intent returns its ID, which we don't need, so don't keep.
# <addIntents>
def add_intents(app_id, app_version):
    intentId = client.model.add_intent(app_id, app_version, "FindFlights")

    print("Intent FindFlights {} added.".format(intentId))
# </addIntents>


# Helper function for creating the utterance data structure.
# <createUtterance>
def create_utterance(intent, utterance, *labels):
    """Add an example LUIS utterance from utterance text and a list of
       labels.  Each label is a 2-tuple containing a label name and the
       text within the utterance that represents that label.

       Utterances apply to a specific intent, which must be specified."""

    text = utterance.lower()

    def label(name, value):
        value = value.lower()
        start = text.index(value)
        return dict(entity_name=name, start_char_index=start,
                    end_char_index=start + len(value))

    return dict(text=text, intent_name=intent,
                entity_labels=[label(n, v) for (n, v) in labels])
# </createUtterance>

# Add example utterances for the intent.  Each utterance includes labels
# that identify the entities within each utterance by index.  LUIS learns
# how to find entities within user utterances from the provided examples.
#
# Example utterance: "find flights in economy to Madrid"
# Labels: Flight -> "economy to Madrid" (composite of Destination and Class)
#         Destination -> "Madrid"
#         Class -> "economy"
# <addUtterances>
def add_utterances(app_id, app_version):
    # Now define the utterances
    utterances = [create_utterance("FindFlights", "find flights in economy to Madrid",
                            ("Flight", "economy to Madrid"),
                            ("Destination", "Madrid"),
                            ("Class", "economy")),

                  create_utterance("FindFlights", "find flights to London in first class",
                            ("Flight", "London in first class"),
                            ("Destination", "London"),
                            ("Class", "first")),

                  create_utterance("FindFlights", "find flights from seattle to London in first class",
                            ("Flight", "flights from seattle to London in first class"),
                            ("Destination", "London"),
                            ("Class", "first"))]

    # Add the utterances in batch. You may add any number of example utterances
    # for any number of intents in one call.
    client.examples.batch(app_id, app_version, utterances)
    print("{} example utterance(s) added.".format(len(utterances)))
# </addUtterances>

# <train>
def train_app(app_id, app_version):
    response = client.train.train_version(app_id, app_version)
    waiting = True
    while waiting:
        info = client.train.get_status(app_id, app_version)

        # 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)
# </train>

# <publish>
def publish_app(app_id, app_version):
    responseEndpointInfo = client.apps.publish(app_id, app_version, is_staging=True)
    print("Application published. Endpoint URL: " + responseEndpointInfo.endpoint_url)
# </publish>

# <predict>
def predict(app_id, publishInfo, slot_name):

    request = { "query" : "Find flight to seattle" }

    # Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    response = clientRuntime.prediction.get_slot_prediction(app_id=app_id, slot_name=slot_name, prediction_request=request)

    print("Top intent: {}".format(response.prediction.top_intent))
    print("Sentiment: {}".format (response.prediction.sentiment))
    print("Intents: ")

    for intent in response.prediction.intents:
        print("\t{}".format (json.dumps (intent)))
    print("Entities: {}".format (response.prediction.entities))
# </predict>

print("Creating application...")
app_id, app_version = create_app()
print()

print ("Adding entities to application...")
add_entities(app_id, app_version)
print ()

print ("Adding intents to application...")
add_intents(app_id, app_version)
print ()

print ("Adding utterances to application...")
add_utterances(app_id, app_version)
print ()

print ("Training application...")
train_app(app_id, app_version)
print ()

print ("Publishing application...")
publish_app(app_id, app_version)

运行应用程序Run the application

在快速入门文件中使用 python 命令运行应用程序。Run the application with the python command on your quickstart file.

python quickstart-file.py

清理资源Clean up resources

完成预测后,请删除文件及其子目录,对此快速入门中的工作进行清理。When you are done with your predictions, clean up the work from this quickstart by deleting the file and its subdirectories.

后续步骤Next steps