快速入门:使用 SDK 查询 V3 预测终结点Quickstart: Query V3 prediction endpoint with SDK

使用 SDK 向语言理解 (LUIS) 发送用户言语,并接收对用户意向的预测。Use the SDK, to send a user utterance to Language Understanding (LUIS) and receive a prediction of the user's intention.

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

  • 按槽获取预测Get prediction by slot
  • 按版本进行预测Prediction by Version

参考文档 | 库源代码 | 预测运行时包 (NuGet) | C# 示例Reference documentation | Library source code | Prediction runtime Package (NuGet) | C# Samples

先决条件Prerequisites

  • 语言理解 (LUIS) 门户帐户 - 免费创建Language Understanding (LUIS) portal account - Create one for free
  • .NET Core 的当前版本。The current version of .NET Core.
  • LUIS 应用 ID - 使用 df67dcdb-c37d-46af-88e1-8b97951ca1c2 的公共 IoT 应用 ID。A LUIS app ID - use the public IoT app ID of df67dcdb-c37d-46af-88e1-8b97951ca1c2. 快速入门代码中使用的用户查询特定于该应用。The user query used in the quickstart code is specific to that app.

设置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) prediction runtime client library for .NET with the following command:

dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime --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 进行身份验证的 LUISRuntimeClient 对象,其中包含资源密钥。The Language Understanding (LUIS) prediction runtime client is a LUISRuntimeClient object that authenticates to Azure, which contains your resource 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) prediction runtime 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:

// <snippet_using>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
// </snippet_using>

namespace UseRuntime
{
    class Program
    {
        // <snippet_variables>
        // Use Language Understanding (LUIS) prediction endpoint key
        // to create authentication credentials
        // Prediction key must be assigned in LUIS portal
        private static string predictionKey = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY";

        // Endpoint URL example value = "https://YOUR-RESOURCE-NAME.cognitiveservices.azure.cn"
        private static string predictionEndpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn";

        // App Id example value = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
        private static string appId = "REPLACE-WITH-YOUR-LUIS_APP_ID";
        // </snippet_variables>

        // <snippet_main>
        static void Main(string[] args)
        {

            // Get prediction
            var predictionResult = GetPredictionAsync().Result;

            var prediction = predictionResult.Prediction;

            // Display query
            Console.WriteLine("Query:'{0}'", predictionResult.Query);
            Console.WriteLine("TopIntent :'{0}' ", prediction.TopIntent);

            foreach (var i in prediction.Intents)
            {
                Console.WriteLine(string.Format("{0}:{1}", i.Key, i.Value.Score));
            }

            foreach (var e in prediction.Entities)
            {
                Console.WriteLine(string.Format("{0}:{1}", e.Key, e.Value));
            }

            Console.Write("done");

        }
        // </snippet_main>

        // <snippet_create_client>
        static LUISRuntimeClient CreateClient()
        {
            var credentials = new ApiKeyServiceClientCredentials(predictionKey);
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = predictionEndpoint
            };

            return luisClient;

        }
        // </snippet_create_client>

        // <snippet_maintask>
        static async Task<PredictionResponse> GetPredictionAsync()
        {

            // Get client 
            using (var luisClient = CreateClient())
            {

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference = DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the bedroom light",
                    Options = requestOptions
                };

                // get prediction
                return await luisClient.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName: "production",
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true,
                    log: true);
            }
        }
        // </snippet_maintask>
    }
}

验证客户端Authenticate the client

  1. 为密钥、资源名称、应用 ID 和发布槽创建变量。Create variables for the key, resource name, app ID, and publishing slot. 将应用 ID 设置为公共 IoT 应用:Set the app ID to the public IoT app:

    df67dcdb-c37d-46af-88e1-8b97951ca1c2

// <snippet_using>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
// </snippet_using>

namespace UseRuntime
{
    class Program
    {
        // <snippet_variables>
        // Use Language Understanding (LUIS) prediction endpoint key
        // to create authentication credentials
        // Prediction key must be assigned in LUIS portal
        private static string predictionKey = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY";

        // Endpoint URL example value = "https://YOUR-RESOURCE-NAME.cognitiveservices.azure.cn"
        private static string predictionEndpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn";

        // App Id example value = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
        private static string appId = "REPLACE-WITH-YOUR-LUIS_APP_ID";
        // </snippet_variables>

        // <snippet_main>
        static void Main(string[] args)
        {

            // Get prediction
            var predictionResult = GetPredictionAsync().Result;

            var prediction = predictionResult.Prediction;

            // Display query
            Console.WriteLine("Query:'{0}'", predictionResult.Query);
            Console.WriteLine("TopIntent :'{0}' ", prediction.TopIntent);

            foreach (var i in prediction.Intents)
            {
                Console.WriteLine(string.Format("{0}:{1}", i.Key, i.Value.Score));
            }

            foreach (var e in prediction.Entities)
            {
                Console.WriteLine(string.Format("{0}:{1}", e.Key, e.Value));
            }

            Console.Write("done");

        }
        // </snippet_main>

        // <snippet_create_client>
        static LUISRuntimeClient CreateClient()
        {
            var credentials = new ApiKeyServiceClientCredentials(predictionKey);
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = predictionEndpoint
            };

            return luisClient;

        }
        // </snippet_create_client>

        // <snippet_maintask>
        static async Task<PredictionResponse> GetPredictionAsync()
        {

            // Get client 
            using (var luisClient = CreateClient())
            {

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference = DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the bedroom light",
                    Options = requestOptions
                };

                // get prediction
                return await luisClient.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName: "production",
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true,
                    log: true);
            }
        }
        // </snippet_maintask>
    }
}
  1. 使用密钥创建 ApiKeyServiceClientCredentials 对象,并在终结点中使用该对象创建一个 LUISRuntimeClient 对象。Create an ApiKeyServiceClientCredentials object with your key, and use it with your endpoint to create an LUISRuntimeClient object.
// <snippet_using>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
// </snippet_using>

namespace UseRuntime
{
    class Program
    {
        // <snippet_variables>
        // Use Language Understanding (LUIS) prediction endpoint key
        // to create authentication credentials
        // Prediction key must be assigned in LUIS portal
        private static string predictionKey = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY";

        // Endpoint URL example value = "https://YOUR-RESOURCE-NAME.cognitiveservices.azure.cn"
        private static string predictionEndpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn";

        // App Id example value = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
        private static string appId = "REPLACE-WITH-YOUR-LUIS_APP_ID";
        // </snippet_variables>

        // <snippet_main>
        static void Main(string[] args)
        {

            // Get prediction
            var predictionResult = GetPredictionAsync().Result;

            var prediction = predictionResult.Prediction;

            // Display query
            Console.WriteLine("Query:'{0}'", predictionResult.Query);
            Console.WriteLine("TopIntent :'{0}' ", prediction.TopIntent);

            foreach (var i in prediction.Intents)
            {
                Console.WriteLine(string.Format("{0}:{1}", i.Key, i.Value.Score));
            }

            foreach (var e in prediction.Entities)
            {
                Console.WriteLine(string.Format("{0}:{1}", e.Key, e.Value));
            }

            Console.Write("done");

        }
        // </snippet_main>

        // <snippet_create_client>
        static LUISRuntimeClient CreateClient()
        {
            var credentials = new ApiKeyServiceClientCredentials(predictionKey);
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = predictionEndpoint
            };

            return luisClient;

        }
        // </snippet_create_client>

        // <snippet_maintask>
        static async Task<PredictionResponse> GetPredictionAsync()
        {

            // Get client 
            using (var luisClient = CreateClient())
            {

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference = DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the bedroom light",
                    Options = requestOptions
                };

                // get prediction
                return await luisClient.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName: "production",
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true,
                    log: true);
            }
        }
        // </snippet_maintask>
    }
}

从运行时获取预测Get prediction from runtime

添加以下方法以创建对预测运行时的请求。Add the following method to create the request to the prediction runtime.

用户言语是 PredictionRequest 对象的一部分。The user utterance is part of the PredictionRequest object.

GetSlotPredictionAsync 方法需要多个参数,如应用 ID、槽名称、用于满足请求的预测请求对象。The GetSlotPredictionAsync method needs several parameters such as the app ID, the slot name, the prediction request object to fulfill the request. 其他选项(如详细、显示所有意向和日志)都是可选的。The other options such as verbose, show all intents, and log are optional.

// <snippet_using>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
// </snippet_using>

namespace UseRuntime
{
    class Program
    {
        // <snippet_variables>
        // Use Language Understanding (LUIS) prediction endpoint key
        // to create authentication credentials
        // Prediction key must be assigned in LUIS portal
        private static string predictionKey = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY";

        // Endpoint URL example value = "https://YOUR-RESOURCE-NAME.cognitiveservices.azure.cn"
        private static string predictionEndpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn";

        // App Id example value = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
        private static string appId = "REPLACE-WITH-YOUR-LUIS_APP_ID";
        // </snippet_variables>

        // <snippet_main>
        static void Main(string[] args)
        {

            // Get prediction
            var predictionResult = GetPredictionAsync().Result;

            var prediction = predictionResult.Prediction;

            // Display query
            Console.WriteLine("Query:'{0}'", predictionResult.Query);
            Console.WriteLine("TopIntent :'{0}' ", prediction.TopIntent);

            foreach (var i in prediction.Intents)
            {
                Console.WriteLine(string.Format("{0}:{1}", i.Key, i.Value.Score));
            }

            foreach (var e in prediction.Entities)
            {
                Console.WriteLine(string.Format("{0}:{1}", e.Key, e.Value));
            }

            Console.Write("done");

        }
        // </snippet_main>

        // <snippet_create_client>
        static LUISRuntimeClient CreateClient()
        {
            var credentials = new ApiKeyServiceClientCredentials(predictionKey);
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = predictionEndpoint
            };

            return luisClient;

        }
        // </snippet_create_client>

        // <snippet_maintask>
        static async Task<PredictionResponse> GetPredictionAsync()
        {

            // Get client 
            using (var luisClient = CreateClient())
            {

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference = DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the bedroom light",
                    Options = requestOptions
                };

                // get prediction
                return await luisClient.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName: "production",
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true,
                    log: true);
            }
        }
        // </snippet_maintask>
    }
}

预测的主代码Main code for the prediction

使用以下主方法将变量和方法结合在一起,以获取预测。Use the following main method to tie the variables and methods together to get the prediction.

// <snippet_using>
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
// </snippet_using>

namespace UseRuntime
{
    class Program
    {
        // <snippet_variables>
        // Use Language Understanding (LUIS) prediction endpoint key
        // to create authentication credentials
        // Prediction key must be assigned in LUIS portal
        private static string predictionKey = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY";

        // Endpoint URL example value = "https://YOUR-RESOURCE-NAME.cognitiveservices.azure.cn"
        private static string predictionEndpoint = "https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn";

        // App Id example value = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
        private static string appId = "REPLACE-WITH-YOUR-LUIS_APP_ID";
        // </snippet_variables>

        // <snippet_main>
        static void Main(string[] args)
        {

            // Get prediction
            var predictionResult = GetPredictionAsync().Result;

            var prediction = predictionResult.Prediction;

            // Display query
            Console.WriteLine("Query:'{0}'", predictionResult.Query);
            Console.WriteLine("TopIntent :'{0}' ", prediction.TopIntent);

            foreach (var i in prediction.Intents)
            {
                Console.WriteLine(string.Format("{0}:{1}", i.Key, i.Value.Score));
            }

            foreach (var e in prediction.Entities)
            {
                Console.WriteLine(string.Format("{0}:{1}", e.Key, e.Value));
            }

            Console.Write("done");

        }
        // </snippet_main>

        // <snippet_create_client>
        static LUISRuntimeClient CreateClient()
        {
            var credentials = new ApiKeyServiceClientCredentials(predictionKey);
            var luisClient = new LUISRuntimeClient(credentials, new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = predictionEndpoint
            };

            return luisClient;

        }
        // </snippet_create_client>

        // <snippet_maintask>
        static async Task<PredictionResponse> GetPredictionAsync()
        {

            // Get client 
            using (var luisClient = CreateClient())
            {

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference = DateTime.Parse("2019-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the bedroom light",
                    Options = requestOptions
                };

                // get prediction
                return await luisClient.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName: "production",
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true,
                    log: true);
            }
        }
        // </snippet_maintask>
    }
}

运行应用程序Run the application

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

dotnet run

清理资源Clean up resources

完成预测后,通过删除 program.cs 文件及其子目录来清理此快速入门中的工作。When you are done with your predictions, clean up the work from this quickstart by deleting the program.cs file and its subdirectories.

可以使用适用于 Node.js 的语言理解 (LUIS) 运行时客户端库执行以下操作:Use the Language Understanding (LUIS) runtime client library for Node.js to:

  • 按槽进行预测Prediction by slot
  • 按版本进行预测Prediction by Version

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

先决条件Prerequisites

  • 语言理解运行时资源:在 Azure 门户中创建一个Language Understanding runtime resource: Create one in the Azure portal
  • Node.jsNode.js
  • LUIS 应用 ID - 使用 df67dcdb-c37d-46af-88e1-8b97951ca1c2 的公共 IoT 应用 ID。A LUIS app ID - use the public IoT app ID of df67dcdb-c37d-46af-88e1-8b97951ca1c2. 快速入门代码中使用的用户查询特定于该应用。The user query used in the quickstart code is specific to that app.

设置Setting up

获取语言理解 (LUIS) 运行时密钥Get your Language Understanding (LUIS) runtime key

通过创建 LUIS 运行时资源,获取运行时密钥Get your runtime key by creating a LUIS runtime resource. 保留密钥和密钥的终结点,以便用于下一步。Keep your key, and the endpoint of the key for the next step.

创建新的 JavaScript (Node.js) 文件Create a new JavaScript (Node.js) file

在你喜欢使用的编辑器或 IDE 中创建名为 luis_prediction.js 的新 JavaScript 文件。Create a new JavaScript file in your preferred editor or IDE, named luis_prediction.js.

安装适用于 LUIS 运行时的 NPM 库Install the NPM library for the LUIS runtime

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

npm install @azure/cognitiveservices-luis-runtime @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

这些代码片段演示如何使用语言理解 (LUIS) 预测运行时客户端库执行以下操作:These code snippets show you how to do the following with the Language Understanding (LUIS) prediction runtime client library:

添加依赖项Add the dependencies

在偏好的编辑器或 IDE 中打开项目目录中的 luis_prediction.js 文件。From the project directory, open the luis_prediction.js file in your preferred editor or IDE. 添加以下依赖项:Add the following dependencies:

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

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

验证客户端Authenticate the client

  1. 为自己所需的 LUIS 信息创建变量:Create variables for your own required LUIS information:

    添加用于管理预测密钥和终结点密钥的变量。Add variables to manage your prediction key and endpoint key.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

try {
    quickstart();
} catch (error) {
    console.log(error);
}
// </Main>
  1. 为名为 LUIS_APP_ID 的应用程序 ID 创建变量。Create a variable for the app ID named LUIS_APP_ID. 将变量设置为公共 IoT 应用 df67dcdb-c37d-46af-88e1-8b97951ca1c2Set the variable to the public IoT app, df67dcdb-c37d-46af-88e1-8b97951ca1c2 . 创建用于设置 production 发布槽的变量。Create a variable to set the production published slot.
"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

try {
    quickstart();
} catch (error) {
    console.log(error);
}
// </Main>
  1. 使用密钥创建 msRest.ApiKeyCredentials 对象,并在终结点中使用该对象创建一个 LUIS.LUISRuntimeClient 对象。Create an msRest.ApiKeyCredentials object with your key, and use it with your endpoint to create an LUIS.LUISRuntimeClient object.
"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

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

从运行时获取预测Get prediction from runtime

添加以下方法以创建对预测运行时的请求。Add the following method to create the request to the prediction runtime.

用户言语是 predictionRequest 对象的一部分。The user utterance is part of the predictionRequest object.

luisRuntimeClient.prediction.getSlotPrediction 方法需要多个参数,如应用 ID、槽名称、用于满足请求的预测请求对象。The luisRuntimeClient.prediction.getSlotPrediction method needs several parameters such as the app ID, the slot name, and the prediction request object to fulfill the request. 其他选项(如详细、显示所有意向和日志)都是可选的。The other options such as verbose, show all intents, and log are optional.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

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

预测的主代码Main code for the prediction

使用以下主方法将变量和方法结合在一起,以获取预测。Use the following main method to tie the variables and methods together to get the prediction.

"use strict";

/* This sample for the Azure Cognitive Services LUIS API shows how to:
 * - Query by slot name
 */

/* To run this sample, install the following modules.
 * npm install @azure/ms-rest-js
 * npm install @azure/cognitiveservices-luis-runtime
 */

// For more information about LUIS, see
//
// LUIS portal - https://luis.azure.cn/welcome
// LUIS conceptual docs - /cognitive-services/luis
// LUIS JS SDK docs for prediction - https://docs.microsoft.com/javascript/api/@azure/cognitiveservices-luis-runtime/predictionoperations?view=azure-node-latest
// LUIS Runtime NPM - https://www.npmjs.com/package/@azure/cognitiveservices-luis-runtime


// <Dependencies>
const msRest = require("@azure/ms-rest-js");
const LUIS = require("@azure/cognitiveservices-luis-runtime");
// </Dependencies>

// <Variables>
const key = "REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY"

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

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

// <OtherVariables>
// Use public app ID or replace with your own trained and published app's ID
// to query your own app
// public appID = `df67dcdb-c37d-46af-88e1-8b97951ca1c2`
// with slot of `production`
const luisAppID = "REPLACE-WITH-YOUR-LUIS_APP_ID"

// `production` or `staging`
const luisSlotName = "production"
// </OtherVariables>

// <predict>
const predict = async (app_id, slot_name) => {

    const predictionRequest = {
        query: "turn on all lights",
        options: {
            datetimeReference: new Date(),
            preferExternalEntities: false
        },
        externalEntities: [],
        dynamicLists: []
    };
    const verbose = true;
    const showAllIntents = true;

    // Note be sure to specify, using the slot_name parameter, whether your application is in staging or production.
    const predictionResult = await luisRuntimeClient.prediction
        .getSlotPrediction(luisAppID, luisSlotName, predictionRequest, { verbose, showAllIntents });

    console.log(JSON.stringify(predictionResult));
}
// </predict>

// <Main>
const quickstart = async () => {
    await predict();
}

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

运行应用程序Run the application

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

node luis_prediction.js

预测结果返回一个 JSON 对象:The prediction result returns a JSON object:

{
   "query":"turn on all lights",
   "prediction":{
      "topIntent":"HomeAutomation.TurnOn",
      "intents":{
         "HomeAutomation.TurnOn":{
            "score":0.5375382
         },
         "None":{
            "score":0.08687421
         },
         "HomeAutomation.TurnOff":{
            "score":0.0207554
         }
      },
      "entities":{
         "HomeAutomation.Operation":[
            "on"
         ],
         "$instance":{
            "HomeAutomation.Operation":[
               {
                  "type":"HomeAutomation.Operation",
                  "text":"on",
                  "startIndex":5,
                  "length":2,
                  "score":0.724984169,
                  "modelTypeId":-1,
                  "modelType":"Unknown",
                  "recognitionSources":[
                     "model"
                  ]
               }
            ]
         }
      }
   }
}

清理资源Clean up resources

完成预测后,请删除文件及其子目录,对此快速入门中的工作进行清理。When you are done with your predictions, clean up the work from this quickstart by deleting the file and its subdirectories.

使用适用于 Python 的语言理解 (LUIS) 预测客户端库可以:Use the Language Understanding (LUIS) prediction client library for Python to:

  • 按槽获取预测Get prediction by slot
  • 按版本获取预测Get prediction by version

参考文档 | 库源代码 | 预测运行时包 (PyPi) | 示例Reference documentation | Library source code | Prediction runtime Package (PyPi) | Samples

先决条件Prerequisites

  • 语言理解 (LUIS) 门户帐户 - 免费创建Language Understanding (LUIS) portal account - Create one for free
  • Python 3.xPython 3.x
  • LUIS 应用 ID - 使用 df67dcdb-c37d-46af-88e1-8b97951ca1c2 的公共 IoT 应用 ID。A LUIS app ID - use the public IoT app ID of df67dcdb-c37d-46af-88e1-8b97951ca1c2. 快速入门代码中使用的用户查询特定于该应用。The user query used in the quickstart code is specific to that app.

设置Setting up

获取语言理解 (LUIS) 运行时密钥Get your Language Understanding (LUIS) runtime key

通过创建 LUIS 运行时资源,获取运行时密钥Get your runtime key by creating a LUIS runtime resource. 保留密钥和密钥的终结点,以便用于下一步。Keep your key, and the endpoint of the key for the next step.

创建新的 Python 文件Create a new python file

在偏好的编辑器或 IDE 中创建名为 prediction_quickstart.py 的新 Python 文件。Create a new python file in your preferred editor or IDE, named prediction_quickstart.py.

安装 SDKInstall the SDK

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

python -m pip install azure-cognitiveservices-language-luis

对象模型Object model

语言理解 (LUIS) 预测运行时客户端是对 Azure 进行身份验证的 LUISRuntimeClient 对象,其中包含资源密钥。The Language Understanding (LUIS) prediction runtime client is a LUISRuntimeClient object that authenticates to Azure, which contains your resource 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) prediction runtime client library for Python:

添加依赖项Add the dependencies

在偏好的编辑器或 IDE 中打开项目目录中的 prediction_quickstart.py 文件。From the project directory, open the prediction_quickstart.py file in your preferred editor or IDE. 添加以下依赖项:Add the following dependencies:

# Azure Language Understanding (LUIS) - Build App
#
# This script queries a public LUIS app for IoT using the Python
# LUIS SDK.
#
# 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.

# For more information about LUIS, see
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis

# <Dependencies>
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

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

# <AuthorizationVariables>
runtime_key = 'REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY'
print("runtime_key: {}".format(runtime_key))

runtime_endpoint = 'https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn'
print("runtime_endpoint: {}".format(runtime_endpoint))
# </AuthorizationVariables>

# <OtherVariables>
# Use public app ID or replace with your own trained and published app's ID
# to query your own app
# public appID = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
luisAppID = 'REPLACE-WITH-YOUR-LUIS_APP_ID'
print("luisAppID: {}".format(luisAppID))

# `production` or `staging`
luisSlotName = 'production'
print("luisSlotName: {}".format(luisSlotName))
# </OtherVariables>


# <Client>
# Instantiate a LUIS runtime client
clientRuntime = LUISRuntimeClient(runtime_endpoint, CognitiveServicesCredentials(runtime_key))
# </Client>


# <predict>
def predict(app_id, slot_name):

    request = { "query" : "turn on all lights" }

    # 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>

predict(luisAppID, luisSlotName)

验证客户端Authenticate the client

  1. 为自己所需的 LUIS 信息创建变量:预测密钥和终结点。Create variables for your own required LUIS information: your prediction key and endpoint.
# Azure Language Understanding (LUIS) - Build App
#
# This script queries a public LUIS app for IoT using the Python
# LUIS SDK.
#
# 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.

# For more information about LUIS, see
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis

# <Dependencies>
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

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

# <AuthorizationVariables>
runtime_key = 'REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY'
print("runtime_key: {}".format(runtime_key))

runtime_endpoint = 'https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn'
print("runtime_endpoint: {}".format(runtime_endpoint))
# </AuthorizationVariables>

# <OtherVariables>
# Use public app ID or replace with your own trained and published app's ID
# to query your own app
# public appID = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
luisAppID = 'REPLACE-WITH-YOUR-LUIS_APP_ID'
print("luisAppID: {}".format(luisAppID))

# `production` or `staging`
luisSlotName = 'production'
print("luisSlotName: {}".format(luisSlotName))
# </OtherVariables>


# <Client>
# Instantiate a LUIS runtime client
clientRuntime = LUISRuntimeClient(runtime_endpoint, CognitiveServicesCredentials(runtime_key))
# </Client>


# <predict>
def predict(app_id, slot_name):

    request = { "query" : "turn on all lights" }

    # 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>

predict(luisAppID, luisSlotName)
  1. 为设置为公共 IoT 应用 df67dcdb-c37d-46af-88e1-8b97951ca1c2 的应用 ID 创建变量。Create a variable for the app ID set to the public IoT app, df67dcdb-c37d-46af-88e1-8b97951ca1c2 . 创建用于设置 production 发布槽的变量。Create a variable to set the production published slot.
# Azure Language Understanding (LUIS) - Build App
#
# This script queries a public LUIS app for IoT using the Python
# LUIS SDK.
#
# 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.

# For more information about LUIS, see
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis

# <Dependencies>
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

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

# <AuthorizationVariables>
runtime_key = 'REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY'
print("runtime_key: {}".format(runtime_key))

runtime_endpoint = 'https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn'
print("runtime_endpoint: {}".format(runtime_endpoint))
# </AuthorizationVariables>

# <OtherVariables>
# Use public app ID or replace with your own trained and published app's ID
# to query your own app
# public appID = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
luisAppID = 'REPLACE-WITH-YOUR-LUIS_APP_ID'
print("luisAppID: {}".format(luisAppID))

# `production` or `staging`
luisSlotName = 'production'
print("luisSlotName: {}".format(luisSlotName))
# </OtherVariables>


# <Client>
# Instantiate a LUIS runtime client
clientRuntime = LUISRuntimeClient(runtime_endpoint, CognitiveServicesCredentials(runtime_key))
# </Client>


# <predict>
def predict(app_id, slot_name):

    request = { "query" : "turn on all lights" }

    # 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>

predict(luisAppID, luisSlotName)
  1. 使用密钥创建 credentials 对象,并在终结点中使用该对象创建一个 LUISRuntimeClientConfiguration 对象。Create a credentials object with your key, and use it with your endpoint to create an LUISRuntimeClientConfiguration object.
# Azure Language Understanding (LUIS) - Build App
#
# This script queries a public LUIS app for IoT using the Python
# LUIS SDK.
#
# 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.

# For more information about LUIS, see
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis

# <Dependencies>
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

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

# <AuthorizationVariables>
runtime_key = 'REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY'
print("runtime_key: {}".format(runtime_key))

runtime_endpoint = 'https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn'
print("runtime_endpoint: {}".format(runtime_endpoint))
# </AuthorizationVariables>

# <OtherVariables>
# Use public app ID or replace with your own trained and published app's ID
# to query your own app
# public appID = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
luisAppID = 'REPLACE-WITH-YOUR-LUIS_APP_ID'
print("luisAppID: {}".format(luisAppID))

# `production` or `staging`
luisSlotName = 'production'
print("luisSlotName: {}".format(luisSlotName))
# </OtherVariables>


# <Client>
# Instantiate a LUIS runtime client
clientRuntime = LUISRuntimeClient(runtime_endpoint, CognitiveServicesCredentials(runtime_key))
# </Client>


# <predict>
def predict(app_id, slot_name):

    request = { "query" : "turn on all lights" }

    # 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>

predict(luisAppID, luisSlotName)

从运行时获取预测Get prediction from runtime

添加以下方法以创建对预测运行时的请求。Add the following method to create the request to the prediction runtime.

用户言语是 prediction_request 对象的一部分。The user utterance is part of the prediction_request object.

get_slot_prediction 方法需要多个参数,如应用 ID、槽名称,以及用于履行请求的预测请求对象。The get_slot_prediction method needs several parameters such as the app ID, the slot name, and the prediction request object to fulfill the request. 其他选项(如详细、显示所有意向和日志)都是可选的。The other options such as verbose, show all intents, and log are optional. 该请求返回 PredictionResponse 对象。The request returns a PredictionResponse object.

# Azure Language Understanding (LUIS) - Build App
#
# This script queries a public LUIS app for IoT using the Python
# LUIS SDK.
#
# 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.

# For more information about LUIS, see
#
# https://luis.azure.cn/welcome
# /cognitive-services/luis

# <Dependencies>
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials

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

# <AuthorizationVariables>
runtime_key = 'REPLACE-WITH-YOUR-ASSIGNED-PREDICTION-KEY'
print("runtime_key: {}".format(runtime_key))

runtime_endpoint = 'https://REPLACE-WITH-YOUR-RESOURCE-NAME.cognitiveservices.azure.cn'
print("runtime_endpoint: {}".format(runtime_endpoint))
# </AuthorizationVariables>

# <OtherVariables>
# Use public app ID or replace with your own trained and published app's ID
# to query your own app
# public appID = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
luisAppID = 'REPLACE-WITH-YOUR-LUIS_APP_ID'
print("luisAppID: {}".format(luisAppID))

# `production` or `staging`
luisSlotName = 'production'
print("luisSlotName: {}".format(luisSlotName))
# </OtherVariables>


# <Client>
# Instantiate a LUIS runtime client
clientRuntime = LUISRuntimeClient(runtime_endpoint, CognitiveServicesCredentials(runtime_key))
# </Client>


# <predict>
def predict(app_id, slot_name):

    request = { "query" : "turn on all lights" }

    # 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>

predict(luisAppID, luisSlotName)

预测的主代码Main code for the prediction

使用以下主方法将变量和方法结合在一起,以获取预测。Use the following main method to tie the variables and methods together to get the prediction.

predict(luisAppID, luisSlotName)

运行应用程序Run the application

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

python prediction_quickstart.py

快速入门控制台将显示输出:The quickstart console displays the output:

Top intent: HomeAutomation.TurnOn
Sentiment: None
Intents:
        "HomeAutomation.TurnOn"
Entities: {'HomeAutomation.Operation': ['on']}

清理资源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