快速入门:使用 REST API 获取意向Quickstart: Get intent with REST APIs

本快速入门使用可用的公共 LUIS 应用从会话文本中确定用户的意向。In this quickstart, use an available public LUIS app to determine a user's intention from conversational text. 将用户的意向作为文本发送到公共应用的 HTTP 预测终结点。Send the user's intention as text to the public app's HTTP prediction endpoint. 在终结点处,LUIS 应用公共应用的模型来分析自然语言文本的含义,确定总体意向并提取与应用的主题域相关的数据。At the endpoint, LUIS applies the public app's model to analyze the natural language text for meaning, determining overall intent and extracting data relevant to the app's subject domain.

本快速入门使用终结点 REST API。This quickstart uses the endpoint REST API. 有关详细信息,请参阅终结点 API 文档For more information, see the endpoint API documentation.

对于本文,需要一个免费的 LUIS 帐户。For this article, you need a free LUIS account.

先决条件Prerequisites

获取 LUIS 密钥Get LUIS key

LUIS 门户中的“Azure 资源”页上的“管理”部分提供密钥和终结点 。Keys and endpoints are provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. 登录到 LUIS 门户Sign in to the LUIS portal.
  2. 创建新应用,或从应用列表中选择现有应用。Create a new app, or select an existing app from the apps list.
  3. 选择“管理”,然后选择“Azure 资源” 。Select Manage then select Azure Resources.
  4. 复制入门资源的密钥和终结点的值。Copy the values for the key and endpoint for the Starter resource. 你将需要这些信息来运行下面的示例。You'll need these to run the sample below.

    Note

    入门密钥允许对创作 API 发出请求而无需付费,并允许每月为你的所有 LUIS 应用向预测终结点 API 发出最多 1000 个查询 。The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

以编程方式获取意向Get intent programmatically

使用 C# (.NET Core) 查询预测终结点并获取预测结果。Use C# (.NET Core) to query the prediction endpoint and get a prediction result.

  1. 使用项目和名为 predict-with-rest 的文件夹创建一个面向 C# 语言的新控制台应用程序。Create a new console application targeting the C# language, with a project and folder name of predict-with-rest.

    dotnet new console -lang C# -n predict-with-rest
    
  2. 更改为刚才创建的 predict-with-rest 目录,并使用以下命令安装所需的依赖项:Change to the predict-with-rest directory you just created, and install required dependencies with these commands:

    cd predict-with-rest
    dotnet add package System.Net.Http
    
  3. 在喜好的 IDE 或编辑器中打开 Program.csOpen Program.cs in your favorite IDE or editor. 然后使用以下代码覆盖 Program.csThen overwrite Program.cs with the following code:

     using System;
     using System.Net.Http;
     using System.Web;
    
     namespace predict_with_rest
     {
         class Program
         {
             static void Main(string[] args)
             {
                 // YOUR-KEY: for example, the starter key
                 var key = "YOUR-KEY";
    
                 // YOUR-ENDPOINT: example is chinaeast2.api.cognitive.azure.cn
                 var endpoint = "YOUR-ENDPOINT";
    
                 // //public sample app
                 var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"; 
    
                 var utterance = "turn on all lights";
    
                 MakeRequest(key, endpoint, appId, utterance);
    
                 Console.WriteLine("Hit ENTER to exit...");
                 Console.ReadLine();
             }
             static async void MakeRequest(string key, string endpoint, string appId, string utterance)
             {
                 var client = new HttpClient();
                 var queryString = HttpUtility.ParseQueryString(string.Empty);
    
                 // The request header contains your subscription key
                 client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
    
                 // The "q" parameter contains the utterance to send to LUIS
                 queryString["query"] = utterance;
    
                 // These optional request parameters are set to their default values
                 queryString["verbose"] = "true";
                 queryString["show-all-intents"] = "true";
                 queryString["staging"] = "false";
                 queryString["timezoneOffset"] = "0";
    
                 var endpointUri = String.Format("https://{0}/luis/prediction/v3.0/apps/{1}/slots/production/predict?query={2}", endpoint, appId, queryString);
    
                 var response = await client.GetAsync(endpointUri);
    
                 var strResponseContent = await response.Content.ReadAsStringAsync();
    
                 // Display the JSON result from LUIS
                 Console.WriteLine(strResponseContent.ToString());
             }
         }
     }
    
    
  4. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥。YOUR-KEY with your starter key.
    • YOUR-ENDPOINT 替换为终结点。YOUR-ENDPOINT with your endpoint. 例如,chinaeast2.api.cognitive.azure.cnFor example, chinaeast2.api.cognitive.azure.cn.
  5. 使用以下命令生成控制台应用程序:Build the console application with this command:

    dotnet build
    
  6. 运行控制台应用程序。Run the console application. 控制台输出会显示前面在浏览器窗口中显示的相同 JSON。The console output displays the same JSON that you saw earlier in the browser window.

    dotnet run
    
  7. 查看以 JSON 形式返回的预测响应:Review the prediction response, which is returned as JSON:

    Hit ENTER to exit...
    {'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']}]}}}}
    

    已通过格式化提高可读性的 JSON 响应:The JSON response formatted for readability:

    {
        "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"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS 密钥LUIS keys

为方便起见,本快速入门使用初学者密钥。This quickstart uses the starter key for convenience. 该密钥主要用于创作模型,但允许少量(1000 个)终结点请求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 当你准备在测试环境、过渡环境或生产环境中处理更多终结点请求时,请在 Azure 门户中创建一个语言理解资源,并将其分配给 LUIS 门户中的 LUIS 应用。When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

清理资源Clean up resources

完成本快速入门后,请从文件系统中删除该文件。When you are finished with this quickstart, delete the file from the file system.

后续步骤Next steps

先决条件Prerequisites

  • JDK SE(Java 开发工具包,标准版)JDK SE (Java Development Kit, Standard Edition)
  • Visual Studio Code 或你喜欢用的 IDEVisual Studio Code or your favorite IDE
  • 公共应用 ID:df67dcdb-c37d-46af-88e1-8b97951ca1c2Public app ID: df67dcdb-c37d-46af-88e1-8b97951ca1c2

获取 LUIS 密钥Get LUIS key

LUIS 门户中的“Azure 资源”页上的“管理”部分提供密钥和终结点 。Keys and endpoints are provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. 登录到 LUIS 门户Sign in to the LUIS portal.
  2. 创建新应用,或从应用列表中选择现有应用。Create a new app, or select an existing app from the apps list.
  3. 选择“管理”,然后选择“Azure 资源” 。Select Manage then select Azure Resources.
  4. 复制入门资源的密钥和终结点的值。Copy the values for the key and endpoint for the Starter resource. 你将需要这些信息来运行下面的示例。You'll need these to run the sample below.

    Note

    入门密钥允许对创作 API 发出请求而无需付费,并允许每月为你的所有 LUIS 应用向预测终结点 API 发出最多 1000 个查询 。The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

以编程方式获取意向Get intent programmatically

使用 Java 查询预测终结点并获取预测结果。Use Java to query the prediction endpoint and get a prediction result.

  1. 创建一个名为 lib 的子目录,并将其复制到以下 Java 库中:Make a subdirectory named lib and copy in the following java libs:

  2. 复制以下代码以在名为 Predict.java 的文件中创建一个类:Copy the following code to create a class in a file named Predict.java:

    import java.io.*;
    import java.net.URI;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    public class Predict {
    
        public static void main(String[] args) 
        {
            HttpClient httpclient = HttpClients.createDefault();
    
            try
            {
    
                // The ID of a public sample LUIS app that recognizes intents for turning on and off lights
                String AppId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";
    
                // Add your endpoint key 
                String Key = "YOUR-KEY";
    
                // Add your endpoint, example is chinaeast2.api.cognitive.azure.cn
                String Endpoint = "YOUR-ENDPOINT";
    
                String Utterance = "turn on all lights";
    
                // Begin endpoint URL string building
                URIBuilder endpointURLbuilder = new URIBuilder("https://" + Endpoint + "/luis/prediction/v3.0/apps/" + AppId + "/slots/production/predict?");
    
                // query string params
                endpointURLbuilder.setParameter("query", Utterance);
                endpointURLbuilder.setParameter("subscription-key", Key);
                endpointURLbuilder.setParameter("show-all-intents", "true");
                endpointURLbuilder.setParameter("verbose", "true");
    
                // create URL from string
                URI endpointURL = endpointURLbuilder.build();
    
                // create HTTP object from URL
                HttpGet request = new HttpGet(endpointURL);
    
                // access LUIS endpoint - analyze text
                HttpResponse response = httpclient.execute(request);
    
                // get response
                HttpEntity entity = response.getEntity();
    
    
                if (entity != null) 
                {
                    System.out.println(EntityUtils.toString(entity));
                }
            }
    
            catch (Exception e)
            {
                System.out.println(e.getMessage());
            }
        }   
    }    
    
  3. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥YOUR-KEY with your starter key
    • YOUR-ENDPOINT 替换为终结点。YOUR-ENDPOINT with your endpoint. 例如,chinaeast2.api.cognitive.azure.cnFor example, chinaeast2.api.cognitive.azure.cn.
  4. 通过命令行编译 Java 程序:Compile the java program from the command line:

    javac -cp ":lib/*" Predict.java
    
  5. 通过命令行运行 Java 程序:Run the java program from the command line:

    java -cp ":lib/*" Predict
    
  6. 查看以 JSON 形式返回的预测响应:Review the prediction response, which is returned as JSON:

    {'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']}]}}}}
    

    已通过格式化提高可读性的 JSON 响应:The JSON response formatted for readability:

    {
        "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"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS 密钥LUIS keys

为方便起见,本快速入门使用初学者密钥。This quickstart uses the starter key for convenience. 该密钥主要用于创作模型,但允许少量(1000 个)终结点请求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 当你准备在测试环境、过渡环境或生产环境中处理更多终结点请求时,请在 Azure 门户中创建一个语言理解资源,并将其分配给 LUIS 门户中的 LUIS 应用。When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

清理资源Clean up resources

完成本快速入门后,请从文件系统中删除该文件。When you are finished with this quickstart, delete the file from the file system.

后续步骤Next steps

先决条件Prerequisites

获取 LUIS 密钥Get LUIS key

LUIS 门户中的“Azure 资源”页上的“管理”部分提供密钥和终结点 。Keys and endpoints are provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. 登录到 LUIS 门户Sign in to the LUIS portal.
  2. 创建新应用,或从应用列表中选择现有应用。Create a new app, or select an existing app from the apps list.
  3. 选择“管理”,然后选择“Azure 资源” 。Select Manage then select Azure Resources.
  4. 复制入门资源的密钥和终结点的值。Copy the values for the key and endpoint for the Starter resource. 你将需要这些信息来运行下面的示例。You'll need these to run the sample below.

    Note

    入门密钥允许对创作 API 发出请求而无需付费,并允许每月为你的所有 LUIS 应用向预测终结点 API 发出最多 1000 个查询 。The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

从预测终结点获取意向Get intent from the prediction endpoint

使用 Python 查询预测终结点并获取预测结果。Use Python to query the prediction endpoint and get a prediction result.

  1. 将以下代码片段复制到名为 predict.py 的文件中:Copy this code snippet into a file called predict.py:

    ########### Python 3.6 #############
    import requests
    
    try:
    
        key = 'YOUR-KEY'
        endpoint = 'YOUR-ENDPOINT' # such as 'chinaeast2.api.cognitive.azure.cn' 
        appId = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
        utterance = 'turn on all lights'
    
        headers = {
        }
    
        params ={
            'query': utterance,
            'timezoneOffset': '0',
            'verbose': 'true',
            'show-all-intents': 'true',
            'spellCheck': 'false',
            'staging': 'false',
            'subscription-key': key
        }
    
        r = requests.get(f'https://{endpoint}/luis/prediction/v3.0/apps/{appId}/slots/production/predict',headers=headers, params=params)
        print(r.json())
    
    except Exception as e:
        print(f'{e}')
    
  2. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥。YOUR-KEY with your starter key.
    • YOUR-ENDPOINT 替换为终结点。YOUR-ENDPOINT with your endpoint. 例如,chinaeast2.api.cognitive.azure.cnFor example, chinaeast2.api.cognitive.azure.cn.
  3. 安装 requests 依赖项。Install the requests dependency. 这用于发出 HTTP 请求:This is used to make HTTP requests:

    pip install requests
    
  4. 使用以下控制台命令运行脚本:Run your script with this console command:

    python predict.py
    
  5. 查看以 JSON 形式返回的预测响应:Review the prediction response, which is returned as JSON:

    {'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']}]}}}}
    

    以下为经过格式设置提高了可读性的 JSON 响应:Here's the JSON response formatted for readability:

    {
        "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"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS 密钥LUIS keys

为方便起见,本快速入门使用初学者密钥。This quickstart uses the starter key for convenience. 该密钥主要用于创作模型,但允许少量(1000 个)终结点请求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 当你准备在测试环境、过渡环境或生产环境中处理更多终结点请求时,请在 Azure 门户中创建一个语言理解资源,并将其分配给 LUIS 门户中的 LUIS 应用。When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

清理资源Clean up resources

完成本快速入门后,请从文件系统中删除该文件。When you are finished with this quickstart, delete the file from the file system.

后续步骤Next steps

先决条件Prerequisites

获取 LUIS 密钥Get LUIS key

LUIS 门户中的“Azure 资源”页上的“管理”部分提供密钥和终结点 。Keys and endpoints are provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. 登录到 LUIS 门户Sign in to the LUIS portal.
  2. 创建新应用,或从应用列表中选择现有应用。Create a new app, or select an existing app from the apps list.
  3. 选择“管理”,然后选择“Azure 资源” 。Select Manage then select Azure Resources.
  4. 复制入门资源的密钥和终结点的值。Copy the values for the key and endpoint for the Starter resource. 你将需要这些信息来运行下面的示例。You'll need these to run the sample below.

    Note

    入门密钥允许对创作 API 发出请求而无需付费,并允许每月为你的所有 LUIS 应用向预测终结点 API 发出最多 1000 个查询 。The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

以编程方式获取意向Get intent programmatically

使用 Node.js 查询预测终结点并获取预测结果。Use Node.js to query the prediction endpoint and get a prediction result.

  1. 将以下代码片段复制到名为 predict.js 的文件中:Copy the following code snippet to a file named predict.js:

    var request = require('request');
    var requestpromise = require('request-promise');
    var querystring = require('querystring');
    
    // Analyze text
    //
    getPrediction = async () => {
    
        // YOUR-KEY - Language Understanding starter key
        var endpointKey = "YOUR-KEY";
    
        // YOUR-ENDPOINT Language Understanding endpoint URL, an example is chinaeast2.api.cognitive.azure.cn
        var endpoint = "YOUR-ENDPOINT";
    
        // Set the LUIS_APP_ID environment variable 
        // to df67dcdb-c37d-46af-88e1-8b97951ca1c2, which is the ID
        // of a public sample application.    
        var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";
    
        var utterance = "turn on all lights";
    
        // Create query string 
        var queryParams = {
            "show-all-intents": true,
            "verbose":  true,
            "query": utterance,
            "subscription-key": endpointKey
        }
    
        // append query string to endpoint URL
        var URI = `https://${endpoint}/luis/prediction/v3.0/apps/${appId}/slots/production/predict?${querystring.stringify(queryParams)}`
    
        // HTTP Request
        const response = await requestpromise(URI);
    
        // HTTP Response
        console.log(response);
    
    }
    
    // Pass an utterance to the sample LUIS app
    getPrediction().then(()=>console.log("done")).catch((err)=>console.log(err));
    
  2. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥。YOUR-KEY to your starter key.
    • YOUR-ENDPOINT 替换为终结点 URL。YOUR-ENDPOINT to your endpoint URL. 例如,chinaeast2.api.cognitive.azure.cnFor example, chinaeast2.api.cognitive.azure.cn.
  3. 使用以下命令安装 requestrequest-promisequerystring 依赖项:Install the request, request-promise, and querystring dependencies with this command:

    npm install request request-promise querystring
    
  4. 使用以下命令运行应用:Run your app with this command:

    node predict.js
    
  5. 查看以 JSON 形式返回的预测响应:Review the prediction response, which is returned as JSON:

    {"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"]}]}}}}
    

    已通过格式化提高可读性的 JSON 响应:The JSON response formatted for readability:

    {
        "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"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS 密钥LUIS keys

为方便起见,本快速入门使用初学者密钥。This quickstart uses the starter key for convenience. 该密钥主要用于创作模型,但允许少量(1000 个)终结点请求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 当你准备在测试环境、过渡环境或生产环境中处理更多终结点请求时,请在 Azure 门户中创建一个语言理解资源,并将其分配给 LUIS 门户中的 LUIS 应用。When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

清理资源Clean up resources

完成本快速入门后,请从文件系统中删除该文件。When you are finished with this quickstart, delete the file from the file system.

后续步骤Next steps

先决条件Prerequisites

获取 LUIS 密钥Get LUIS key

LUIS 门户中的“Azure 资源”页上的“管理”部分提供密钥和终结点 。Keys and endpoints are provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. 登录到 LUIS 门户Sign in to the LUIS portal.
  2. 创建新应用,或从应用列表中选择现有应用。Create a new app, or select an existing app from the apps list.
  3. 选择“管理”,然后选择“Azure 资源” 。Select Manage then select Azure Resources.
  4. 复制入门资源的密钥和终结点的值。Copy the values for the key and endpoint for the Starter resource. 你将需要这些信息来运行下面的示例。You'll need these to run the sample below.

    Note

    入门密钥允许对创作 API 发出请求而无需付费,并允许每月为你的所有 LUIS 应用向预测终结点 API 发出最多 1000 个查询 。The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

以编程方式获取意向Get intent programmatically

使用 Go 查询预测终结点并获取预测结果。Use Go to query the prediction endpoint and get a prediction result.

  1. 创建名为 predict.go 的新文件。Create a new file named predict.go. 添加以下代码:Add the following code:

    package main
    
    /* Do dependencies */
    import (
        "fmt"
        "net/http"
        "net/url"
        "io/ioutil"
        "log"
    )
    func main() {
    
        // public app
        var appID = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
    
        // utterance for public app
        var utterance = "turn on all lights"
    
        // YOUR-KEY - your starter or prediction key
        var endpointKey = "YOUR-KEY"
    
        // YOUR-ENDPOINT - example is chinaeast2.api.cognitive.azure.cn
        var endpoint = "YOUR-ENDPOINT"
    
        endpointPrediction(appID, endpointKey, endpoint, utterance)
    }
    func endpointPrediction(appID string, endpointKey string, endpoint string, utterance string) {
    
        var endpointUrl = fmt.Sprintf("https://%s/luis/prediction/v3.0/apps/%s/slots/production/predict?subscription-key=%s&verbose=true&show-all-intents=true&query=%s", endpoint, appID, endpointKey, url.QueryEscape(utterance))
    
        response, err := http.Get(endpointUrl)
    
        if err!=nil {
            // handle error
            fmt.Println("error from Get")
            log.Fatal(err)
        }
    
        response2, err2 := ioutil.ReadAll(response.Body)
    
        if err2!=nil {
            // handle error
            fmt.Println("error from ReadAll")
            log.Fatal(err2)
        }
    
        fmt.Println("response")
        fmt.Println(string(response2))
    }
    
  2. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥。YOUR-KEY with your starter key.
    • YOUR-ENDPOINT 替换为终结点。YOUR-ENDPOINT with your endpoint. 例如,chinaeast2.api.cognitive.azure.cnFor example, chinaeast2.api.cognitive.azure.cn.
  3. 在创建该文件的同一目录中,在命令提示符下输入以下命令来编译 Go 文件:With a command prompt in the same directory as where you created the file, enter the following command to compile the Go file:

    go build predict.go
    
  4. 通过在命令提示符下输入以下文本从命令行运行 Go 应用程序:Run the Go application from the command line by entering the following text in the command prompt:

    go run predict.go
    

    命令提示符响应为:The command prompt response is:

    appID has value df67dcdb-c37d-46af-88e1-8b97951ca1c2
    endpointKey has value a7b206911f714e71a1ddae36928a61cc
    endpoint has value chinaeast2.api.cognitive.azure.cn
    utterance has value turn on all lights
    response
    {"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"]}]}}}}
    

    JSON 格式以提高可读性:JSON formatted for readability:

    {
        "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"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS 密钥LUIS keys

为方便起见,本快速入门使用初学者密钥。This quickstart uses the starter key for convenience. 该密钥主要用于创作模型,但允许少量(1000 个)终结点请求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 当你准备在测试环境、过渡环境或生产环境中处理更多终结点请求时,请在 Azure 门户中创建一个语言理解资源,并将其分配给 LUIS 门户中的 LUIS 应用。When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

清理资源Clean up resources

完成本快速入门后,请从文件系统中删除该文件。When you are finished with this quickstart, delete the file from the file system.

后续步骤Next steps