快速入门:使用 REST API 更改模型Quickstart: Change model with REST APIs

在此快速入门中,你要将示例言语添加到披萨应用并训练该应用。In this quickstart, you will add example utterances to a Pizza app and train the app. 示例话语是映射到意向的对话式用户文本。Example utterances are conversational user text mapped to an intent. 通过提供意向的示例话语,可以教 LUIS 识别用户提供的文本类型属于哪种意向。By providing example utterances for intents, you teach LUIS what kinds of user-supplied text belongs to which intent.

先决条件Prerequisites

  • 初学者密钥。Starter key.
  • 从 cognitive-services-language-understanding GitHub 存储库中导入 TravelAgent 应用。Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 ID。The LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 接收言语的应用程序中的版本 ID。The version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".
  • .NET Core V2.2+.NET Core V2.2+
  • Visual Studio CodeVisual Studio Code

示例话语 JSON 文件Example utterances JSON file

示例言语采用特定格式。The example utterances follow a specific format.

text 字段包含示例话语的文本。The text field contains the text of the example utterance. intentName 字段必须对应于 LUIS 应用中的现有意向名称。The intentName field must correspond to the name of an existing intent in the LUIS app. entityLabels 字段是必填的。The entityLabels field is required. 如果不想标记任何实体,请提供一个空数组。If you don't want to label any entities, provide an empty array.

如果 entityLabels 数组不为空,则 startCharIndexendCharIndex 需要标记 entityName 字段中引用的实体。If the entityLabels array is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. 索引从零开始,这意味着顶部示例中的 6 表示西雅图的“S”而不是大写字母 S 之前的空格。如果你在文本中的空格处开始或结束标签,则用于添加话语的 API 调用将失败。The index is zero-based, meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S. If you begin or end the label at a space in the text, the API call to add the utterances fails.

[
  {
    "text": "go to Seattle today",
    "intentName": "BookFlight",
    "entityLabels": [
      {
        "entityName": "Location::LocationTo",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "purple dogs are difficult to work with",
    "intentName": "BookFlight",
    "entityLabels": []
  }
]

获取 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.

    备注

    入门密钥允许对创作 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.

以编程方式更改模型Change model programmatically

使用 C# 将机器学习实体 API 添加到应用程序。Use C# to add a machine-learned entity API to the application.

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

    dotnet new console -lang C# -n model-with-rest
    
  2. 使用以下 dotnet CLI 命令安装所需的依赖项。Install required dependencies with the following dotnet CLI commands.

    dotnet add package System.Net.Http
    dotnet add package JsonFormatterPlus
    
  3. 将 Program.cs 改写为以下代码:Overwrite Program.cs with the following code:

    using System;
    using System.IO;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    
    // 3rd party NuGet packages
    using JsonFormatterPlus;
    
    namespace AddUtterances
    {
        class Program
        {
            // NOTE: use your starter key value
            static string authoringKey = "YOUR-KEY";
    
            // NOTE: Replace this endpoint with your starter key endpoint
            // for example, chinaeast2.api.cognitive.azure.cn
            static string endpoint = "YOUR-ENDPOINT";
    
            // NOTE: Replace this with the ID of your LUIS application
            static string appID = "YOUR-APP-ID";
    
            // NOTE: Replace this your version number
            static string appVersion = "0.1";
    
            static string host = String.Format("https://{0}/luis/authoring/v3.0-preview/apps/{1}/versions/{2}/", endpoint, appID, appVersion);
    
            // GET request with authentication
            async static Task<HttpResponseMessage> SendGet(string uri)
            {
                using (var client = new HttpClient())
                using (var request = new HttpRequestMessage())
                {
                    request.Method = HttpMethod.Get;
                    request.RequestUri = new Uri(uri);
                    request.Headers.Add("Ocp-Apim-Subscription-Key", authoringKey);
                    return await client.SendAsync(request);
                }
            }
            // POST request with authentication
            async static Task<HttpResponseMessage> SendPost(string uri, string requestBody)
            {
                using (var client = new HttpClient())
                using (var request = new HttpRequestMessage())
                {
                    request.Method = HttpMethod.Post;
                    request.RequestUri = new Uri(uri);
    
                    if (!String.IsNullOrEmpty(requestBody))
                    {
                        request.Content = new StringContent(requestBody, Encoding.UTF8, "text/json");
                    }
    
                    request.Headers.Add("Ocp-Apim-Subscription-Key", authoringKey);
                    return await client.SendAsync(request);
                }
            }        
            // Add utterances as string with POST request
            async static Task AddUtterances(string utterances)
            {
                string uri = host + "examples";
    
                var response = await SendPost(uri, utterances);
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Added utterances.");
                Console.WriteLine(JsonFormatter.Format(result));
            }
            // Train app after adding utterances
            async static Task Train()
            {
                string uri = host  + "train";
    
                var response = await SendPost(uri, null);
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Sent training request.");
                Console.WriteLine(JsonFormatter.Format(result));
            }    
            // Check status of training
            async static Task Status()
            {
                var response = await SendGet(host  + "train");
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Requested training status.");
                Console.WriteLine(JsonFormatter.Format(result));
            }    
            // Add utterances, train, check status
            static void Main(string[] args)
            {
                string utterances = @"
                [
                    {
                    'text': 'go to Seattle today',
                    'intentName': 'BookFlight',
                    'entityLabels': [
                        {
                        'entityName': 'Location::LocationTo',
                        'startCharIndex': 6,
                        'endCharIndex': 12
                        }
                    ]
                    },
                    {
                        'text': 'a barking dog is annoying',
                        'intentName': 'None',
                        'entityLabels': []
                    }
                ]
                ";            
                AddUtterances(utterances).Wait();
                Train().Wait();
                Status().Wait();
            }
        }
    }
    
  4. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥YOUR-KEY with your starter key
    • YOUR-ENDPOINT 替换为终结点,例如 chinaeast2.api.cognitive.azure.cnYOUR-ENDPOINT with your endpoint, for example, chinaeast2.api.cognitive.azure.cn
    • YOUR-APP-ID 替换为应用 IDYOUR-APP-ID with your app's ID
  5. 生成控制台应用程序。Build the console application.

    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
    

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

  • 初学者密钥。Starter key.
  • 从 cognitive-services-language-understanding GitHub 存储库中导入 TravelAgent 应用。Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 ID。The LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 接收言语的应用程序中的版本 ID。The version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".
  • JDK SE(Java 开发工具包,标准版)JDK SE (Java Development Kit, Standard Edition)
  • Visual Studio Code 或你喜欢用的 IDEVisual Studio Code or your favorite IDE

示例话语 JSON 文件Example utterances JSON file

示例言语采用特定格式。The example utterances follow a specific format.

text 字段包含示例话语的文本。The text field contains the text of the example utterance. intentName 字段必须对应于 LUIS 应用中的现有意向名称。The intentName field must correspond to the name of an existing intent in the LUIS app. entityLabels 字段是必填的。The entityLabels field is required. 如果不想标记任何实体,请提供一个空数组。If you don't want to label any entities, provide an empty array.

如果 entityLabels 数组不为空,则 startCharIndexendCharIndex 需要标记 entityName 字段中引用的实体。If the entityLabels array is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. 索引从零开始,这意味着顶部示例中的 6 表示西雅图的“S”而不是大写字母 S 之前的空格。如果你在文本中的空格处开始或结束标签,则用于添加话语的 API 调用将失败。The index is zero-based, meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S. If you begin or end the label at a space in the text, the API call to add the utterances fails.

[
  {
    "text": "go to Seattle today",
    "intentName": "BookFlight",
    "entityLabels": [
      {
        "entityName": "Location::LocationTo",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "purple dogs are difficult to work with",
    "intentName": "BookFlight",
    "entityLabels": []
  }
]

获取 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.

    备注

    入门密钥允许对创作 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.

以编程方式更改模型Change model programmatically

使用 Go 将经过机器学习的实体 API 添加到应用程序中。Use Go to add a machine-learned entity API to the application.

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

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

    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.methods.HttpPost;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    //javac -cp ":lib/*" Model.java
    //java -cp ":lib/*" Model
    
    public class Model {
    
        public static void main(String[] args) 
        {
            try
            {
    
                // The ID of a public sample LUIS app that recognizes intents for turning on and off lights
                String AppId = "YOUR-APP-ID";
    
                // Add your endpoint key 
                String Key = "YOUR-KEY";
    
                // Add your endpoint, example is chinaeast2.api.cognitive.azure.cn
                String Endpoint = "YOUR-ENDPOINT";
    
                String Utterance = "[{'text': 'go to Seattle today','intentName': 'BookFlight','entityLabels': [{'entityName': 'Location::LocationTo',"
                    + "'startCharIndex': 6,'endCharIndex': 12}]},{'text': 'a barking dog is annoying','intentName': 'None','entityLabels': []}]";
    
                String Version = "1.0";
    
                // Begin endpoint URL string building
                URIBuilder addUtteranceURL = new URIBuilder("https://" + Endpoint + "/luis/authoring/v3.0-preview/apps/" + AppId + "/versions/" + Version + "/examples");
                URIBuilder trainURL = new URIBuilder("https://" + Endpoint + "/luis/authoring/v3.0-preview/apps/" + AppId + "/versions/" + Version + "/train");
    
                // create URL from string
                URI addUtterancesURI = addUtteranceURL.build();
                URI trainURI = trainURL.build();
    
                // add utterances POST
                HttpClient addUtterancesClient = HttpClients.createDefault();
                HttpPost addutterancesRequest = new HttpPost(addUtterancesURI);
                addutterancesRequest.setHeader("Ocp-Apim-Subscription-Key",Key);
                addutterancesRequest.setHeader("Content-type","application/json");
                HttpResponse addutterancesResponse = addUtterancesClient.execute(addutterancesRequest);
                HttpEntity addutterancesEntity = addutterancesResponse.getEntity();
                if (addutterancesEntity != null) 
                {
                    System.out.println(EntityUtils.toString(addutterancesEntity));
                }
    
                // train POST
                HttpClient trainClient = HttpClients.createDefault();
                HttpPost trainRequest = new HttpPost(trainURI);
                trainRequest.setHeader("Ocp-Apim-Subscription-Key",Key);
                trainRequest.setHeader("Content-type","application/json");
                HttpResponse trainResponse = trainClient.execute(trainRequest);
                HttpEntity trainEntity = trainResponse.getEntity();
                if (trainEntity != null) 
                {
                    System.out.println(EntityUtils.toString(trainEntity));
                }
    
                // training status GET
                HttpClient trainStatusClient = HttpClients.createDefault();
                HttpGet trainStatusRequest = new HttpGet(trainURI);
                trainStatusRequest.setHeader("Ocp-Apim-Subscription-Key",Key);
                trainStatusRequest.setHeader("Content-type","application/json");
                HttpResponse trainStatusResponse = trainStatusClient.execute(trainStatusRequest);
                HttpEntity trainStatusEntity = trainStatusResponse.getEntity();
                if (trainStatusEntity != null) 
                {
                    System.out.println(EntityUtils.toString(trainStatusEntity));
                }            
            }
    
            catch (Exception e)
            {
                System.out.println(e.getMessage());
            }
        }   
    }
    
  3. 请替换以下值:Replace the following values:

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

    javac -cp ":lib/*" Model.java
    
  5. 通过在命令提示符下输入以下文本从命令行运行 Java 应用程序:Run the Java application from the command line by entering the following text in the command prompt:

    java -cp ":lib/*" 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

  • 初学者密钥。Starter key.
  • 从 cognitive-services-language-understanding GitHub 存储库中导入 TravelAgent 应用。Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 ID。The LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 接收言语的应用程序中的版本 ID。The version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".
  • Go 编程语言Go programming language
  • Visual Studio CodeVisual Studio Code

示例话语 JSON 文件Example utterances JSON file

示例言语采用特定格式。The example utterances follow a specific format.

text 字段包含示例话语的文本。The text field contains the text of the example utterance. intentName 字段必须对应于 LUIS 应用中的现有意向名称。The intentName field must correspond to the name of an existing intent in the LUIS app. entityLabels 字段是必填的。The entityLabels field is required. 如果不想标记任何实体,请提供一个空数组。If you don't want to label any entities, provide an empty array.

如果 entityLabels 数组不为空,则 startCharIndexendCharIndex 需要标记 entityName 字段中引用的实体。If the entityLabels array is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. 索引从零开始,这意味着顶部示例中的 6 表示西雅图的“S”而不是大写字母 S 之前的空格。如果你在文本中的空格处开始或结束标签,则用于添加话语的 API 调用将失败。The index is zero-based, meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S. If you begin or end the label at a space in the text, the API call to add the utterances fails.

[
  {
    "text": "go to Seattle today",
    "intentName": "BookFlight",
    "entityLabels": [
      {
        "entityName": "Location::LocationTo",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "purple dogs are difficult to work with",
    "intentName": "BookFlight",
    "entityLabels": []
  }
]

获取 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.

    备注

    入门密钥允许对创作 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.

以编程方式更改模型Change model programmatically

使用 Go 将经过机器学习的实体 API 添加到应用程序中。Use Go to add a machine-learned entity API to the application.

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

    // dependencies
    package main
    import (
        "fmt"
        "net/http"
        "io/ioutil"
        "log"
        "strings"
    )
    
    // main function
    func main() {
    
        // NOTE: change to your app ID
        var appID = "YOUR-APP-ID"
    
        // NOTE: change to your starter key
        var authoringKey = "YOUR-KEY"
    
        // NOTE: change to your starter key's endpoint, for example, chinaeast2.api.cognitive.azure.cn
        var endpoint = "YOUR-ENDPOINT"  
    
        var version = "0.1"
    
        var exampleUtterances = `
        [
            {
              'text': 'go to Seattle today',
              'intentName': 'BookFlight',
              'entityLabels': [
                {
                  'entityName': 'Location::LocationTo',
                  'startCharIndex': 6,
                  'endCharIndex': 12
                }
              ]
            },
            {
                'text': 'a barking dog is annoying',
                'intentName': 'None',
                'entityLabels': []
            }
          ]
        `
    
        fmt.Println("add example utterances requested")
        addUtterance(authoringKey, appID, version, exampleUtterances, endpoint)
    
        fmt.Println("training selected")
        requestTraining(authoringKey, appID, version, endpoint)
    
        fmt.Println("training status selected")
        getTrainingStatus(authoringKey, appID, version, endpoint)
    }
    
    // get utterances from file and add to model
    func addUtterance(authoringKey string, appID string,  version string, labeledExampleUtterances string, endpoint string){
    
        var authoringUrl = fmt.Sprintf("https://%s/luis/authoring/v3.0-preview/apps/%s/versions/%s/examples", endpoint, appID, version)
    
        httpRequest("POST", authoringUrl, authoringKey, labeledExampleUtterances)
    }
    func requestTraining(authoringKey string, appID string,  version string, endpoint string){
    
        trainApp("POST", authoringKey, appID, version, endpoint)
    }
    func trainApp(httpVerb string, authoringKey string, appID string,  version string, endpoint string){
    
        var authoringUrl = fmt.Sprintf("https://%s/luis/authoring/v3.0-preview/apps/%s/versions/%s/train", endpoint, appID, version)
    
        httpRequest(httpVerb,authoringUrl, authoringKey, "")
    }
    func getTrainingStatus(authoringKey string, appID string, version string, endpoint string){
    
        trainApp("GET", authoringKey, appID, version, endpoint)
    }
    // generic HTTP request
    // includes setting header with authoring key
    func httpRequest(httpVerb string, url string, authoringKey string, body string){
    
        client := &http.Client{}
    
        request, err := http.NewRequest(httpVerb, url, strings.NewReader(body))
        request.Header.Add("Ocp-Apim-Subscription-Key", authoringKey)
    
        fmt.Println("body")
        fmt.Println(body)
    
        response, err := client.Do(request)
        if err != nil {
            log.Fatal(err)
        } else {
            defer response.Body.Close()
            contents, err := ioutil.ReadAll(response.Body)
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println("   ", response.StatusCode)
            fmt.Println(string(contents))
        }
    }    
    
  2. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥YOUR-KEY with your starter key
    • YOUR-ENDPOINT 替换为终结点,例如 chinaeast2.api.cognitive.azure.cnYOUR-ENDPOINT with your endpoint, for example, chinaeast2.api.cognitive.azure.cn
    • YOUR-APP-ID 替换为应用 IDYOUR-APP-ID with your app's ID
  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 model.go
    
  4. 通过在命令提示符下输入以下文本从命令行运行 Go 应用程序:Run the Go application from the command line by entering the following text in the command prompt:

    go run model.go
    

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

  • 初学者密钥。Starter key.
  • 从 cognitive-services-language-understanding GitHub 存储库中导入 TravelAgent 应用。Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 ID。The LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 接收言语的应用程序中的版本 ID。The version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".
  • Node.js 编程语言Node.js programming language
  • Visual Studio CodeVisual Studio Code

示例话语 JSON 文件Example utterances JSON file

示例言语采用特定格式。The example utterances follow a specific format.

text 字段包含示例话语的文本。The text field contains the text of the example utterance. intentName 字段必须对应于 LUIS 应用中的现有意向名称。The intentName field must correspond to the name of an existing intent in the LUIS app. entityLabels 字段是必填的。The entityLabels field is required. 如果不想标记任何实体,请提供一个空数组。If you don't want to label any entities, provide an empty array.

如果 entityLabels 数组不为空,则 startCharIndexendCharIndex 需要标记 entityName 字段中引用的实体。If the entityLabels array is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. 索引从零开始,这意味着顶部示例中的 6 表示西雅图的“S”而不是大写字母 S 之前的空格。如果你在文本中的空格处开始或结束标签,则用于添加话语的 API 调用将失败。The index is zero-based, meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S. If you begin or end the label at a space in the text, the API call to add the utterances fails.

[
  {
    "text": "go to Seattle today",
    "intentName": "BookFlight",
    "entityLabels": [
      {
        "entityName": "Location::LocationTo",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "purple dogs are difficult to work with",
    "intentName": "BookFlight",
    "entityLabels": []
  }
]

获取 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.

    备注

    入门密钥允许对创作 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.

以编程方式更改模型Change model programmatically

使用 Go 将经过机器学习的实体 API 添加到应用程序中。Use Go to add a machine-learned entity API to the application.

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

    var request = require('request');
    var requestpromise = require('request-promise');
    
    const LUIS_authoringKey = "YOUR-KEY";
    const LUIS_endpoint = "YOUR-ENDPOINT";
    const LUIS_appId = "YOUR-APP-ID";
    const LUIS_versionId = "0.1";
    const addUtterancesURI = `https://${LUIS_endpoint}/luis/authoring/v3.0-preview/apps/${LUIS_appId}/versions/${LUIS_versionId}/examples`;
    const addTrainURI = `https://${LUIS_endpoint}/luis/authoring/v3.0-preview/apps/${LUIS_appId}/versions/${LUIS_versionId}/train`;
    
    const utterances = [
            {
              'text': 'go to Seattle today',
              'intentName': 'BookFlight',
              'entityLabels': [
                {
                  'entityName': 'Location::LocationTo',
                  'startCharIndex': 6,
                  'endCharIndex': 12
                }
              ]
            },
            {
                'text': 'a barking dog is annoying',
                'intentName': 'None',
                'entityLabels': []
            }
          ];
    
    const main = async() =>{
    
    
        await addUtterance();
        await train("POST");
        await trainStatus("GET");
    
    }
    const addUtterance = async () => {
    
        const options = {
            uri: addUtterancesURI,
            method: 'POST',
            headers: {
                'Ocp-Apim-Subscription-Key': LUIS_authoringKey
            },
            json: true,
            body: utterances
        };
    
        const reponse = await requestpromise(options)
        console.log(reponse.body);
    }
    const train = async (verb) => {
    
        const options = {
            uri: addTrainURI,
            method: verb, 
            headers: {
                'Ocp-Apim-Subscription-Key': LUIS_authoringKey
            },
            json: true,
            body: null // The body can be empty for a training request
        };
    
        const reponse = await requestpromise(options)
        console.log(reponse.body);
    }
    
    // MAIN
    main().then(() => console.log("done")).catch((err)=> console.log(err returned));
    
  2. 请替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥YOUR-KEY with your starter key
    • YOUR-ENDPOINT 替换为终结点,例如 chinaeast2.api.cognitive.azure.cnYOUR-ENDPOINT with your endpoint, for example, chinaeast2.api.cognitive.azure.cn
    • YOUR-APP-ID 替换为应用 IDYOUR-APP-ID with your app's ID
  3. 在创建该文件的同一目录中,在命令提示符下输入以下命令来运行文件:With a command prompt in the same directory as where you created the file, enter the following command to run the file:

    node model.js
    

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

  • 初学者密钥。Starter key.
  • 从 cognitive-services-language-understanding GitHub 存储库中导入 TravelAgent 应用。Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 ID。The LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 接收言语的应用程序中的版本 ID。The version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".
  • Python 3.6 或更高版本。Python 3.6 or later.
  • Visual Studio CodeVisual Studio Code

示例话语 JSON 文件Example utterances JSON file

示例言语采用特定格式。The example utterances follow a specific format.

text 字段包含示例话语的文本。The text field contains the text of the example utterance. intentName 字段必须对应于 LUIS 应用中的现有意向名称。The intentName field must correspond to the name of an existing intent in the LUIS app. entityLabels 字段是必填的。The entityLabels field is required. 如果不想标记任何实体,请提供一个空数组。If you don't want to label any entities, provide an empty array.

如果 entityLabels 数组不为空,则 startCharIndexendCharIndex 需要标记 entityName 字段中引用的实体。If the entityLabels array is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. 索引从零开始,这意味着顶部示例中的 6 表示西雅图的“S”而不是大写字母 S 之前的空格。如果你在文本中的空格处开始或结束标签,则用于添加话语的 API 调用将失败。The index is zero-based, meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S. If you begin or end the label at a space in the text, the API call to add the utterances fails.

[
  {
    "text": "go to Seattle today",
    "intentName": "BookFlight",
    "entityLabels": [
      {
        "entityName": "Location::LocationTo",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "purple dogs are difficult to work with",
    "intentName": "BookFlight",
    "entityLabels": []
  }
]

获取 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.

    备注

    入门密钥允许对创作 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.

以编程方式更改模型Change model programmatically

使用 Go 将经过机器学习的实体 API 添加到应用程序中。Use Go to add a machine-learned entity API to the application.

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

    ########### Python 3.6 #############
    import requests
    
    # Starter key
    LUIS_authoringKey  = "YOUR-KEY"
    
    LUIS_APP_ID = "YOUR-APP-ID"
    
    # Authoring endpoint, example: chinaeast2.api.cognitive.azure.cn
    LUIS_ENDPOINT = "YOUR-ENDPOINT"
    
    # The version number of your LUIS app
    LUIS_APP_VERSION = "0.1"
    
    URI_AddUtterances = f'https://{LUIS_ENDPOINT}/luis/authoring/v3.0-preview/apps/{LUIS_APP_ID}/versions/{LUIS_APP_ID}/examples'
    URI_Train = f'https://{LUIS_ENDPOINT}/luis/authoring/v3.0-preview/apps/{LUIS_APP_ID}/versions/{LUIS_APP_ID}/train'
    
    HEADERS = {'Ocp-Apim-Subscription-Key': LUIS_authoringKey}
    
    def addUtterances():
        r = requests.post(URI_AddUtterances,headers=HEADERS)
        print(r.json())
    
    def train():
        r = requests.post(URI_Train,headers=HEADERS)
        print(r.json())
    
    def trainStatus():
        r = requests.get(URI_Train,headers=HEADERS)
        print(r.json())
    
    addUtterances()
    train()
    trainStatus()
    
  2. 替换以下值:Replace the following values:

    • YOUR-KEY 替换为初学者密钥YOUR-KEY with your starter key
    • YOUR-ENDPOINT 替换为终结点,例如 chinaeast2.api.cognitive.azure.cnYOUR-ENDPOINT with your endpoint, for example, chinaeast2.api.cognitive.azure.cn
    • YOUR-APP-ID 替换为应用 IDYOUR-APP-ID with your app's ID
  3. 在创建该文件的同一目录中,在命令提示符下输入以下命令来运行文件:With a command prompt in the same directory as where you created the file, enter the following command to run the file:

    python model.py
    

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