快速入门:使用 Node.js 更改模型Quickstart: Change model using Node.js

  • LUIS 创作密钥Your LUIS authoring key.
  • 从 cognitive-services-language-understanding GitHub 存储库导入 TravelAgent 应用Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 IDThe LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 包含要导入的示例话语的 utterances.json 文件。The utterances.json file containing the example utterances to import.
  • 接收陈述的应用程序中的版本 IDThe version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".

先决条件Prerequisites

  • LUIS 创作密钥Your LUIS authoring key.
  • 从 cognitive-services-language-understanding GitHub 存储库导入 TravelAgent 应用Import the TravelAgent app from the cognitive-services-language-understanding GitHub repository.
  • 导入的 TravelAgent 应用的 LUIS 应用程序 IDThe LUIS application ID for the imported TravelAgent app. 应用程序仪表板中显示了应用程序 ID。The application ID is shown in the application dashboard.
  • 包含要导入的示例话语的 utterances.json 文件。The utterances.json file containing the example utterances to import.
  • 接收陈述的应用程序中的版本 IDThe version ID within the application that receives the utterances. 默认 ID 为“0.1”。The default ID is "0.1".

Note

完整的解决方案(包括示例 utterances.json 文件)可从 cognitive-services-language-understanding GitHub 存储库获得。The complete solution including an example utterances.json file are available from the cognitive-services-language-understanding GitHub repository.

示例话语 JSON 文件Example utterances JSON file

示例话语文件 utterances.json 遵循特定格式。The example utterances file, utterances.json, follows 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": []
  }
]

创建快速入门代码Create quickstart code

将 NPM 依赖项添加到名为 add-utterances.js 的文件。Add the NPM dependencies to the file named add-utterances.js.

  // NPM Dependencies
  var rp = require('request-promise');
  var fse = require('fs-extra');
  var path = require('path');

将 LUIS 常量添加到文件。Add the LUIS constants to the file. 复制以下代码,并将相应的占位符更改为自己的创作密钥、应用程序 ID 和版本 ID。Copy the following code and change to your authoring key, application ID, and version ID.

   // To run this sample, change these constants.

   // Authoring key, available in https://luis.azure.cn under Account Settings
   const LUIS_authoringKey = "YOUR-AUTHORING-KEY";

   // ID of your LUIS app to which you want to add an utterance
   const LUIS_appId = "YOUR-APP-ID";

   // The version number of your LUIS app
   const LUIS_versionId = "0.1";

添加包含陈述的上传文件的名称和位置。Add the name and location of the upload file containing your utterances.

   // uploadFile is the file containing JSON for utterance(s) to add to the LUIS app.
   // The contents of the file must be in this format described at: https://aka.ms/add-utterance-json-format
   const uploadFile = "./utterances.json"

添加 addUtterance 函数的方法和对象。Add method and object for addUtterance function.

   // upload configuration 
   var configAddUtterance = {
      LUIS_authoringKey: LUIS_authoringKey,
      LUIS_appId: LUIS_appId,
      LUIS_versionId: LUIS_versionId,
      inFile: path.join(__dirname, uploadFile),
      uri: "https://chinaeast2.api.cognitive.azure.cn/luis/api/v2.0/apps/{appId}/versions/{versionId}/examples".replace("{appId}", LUIS_appId).replace("{versionId}", LUIS_versionId)
   };


   // Call add-utterance
   var addUtterance = async (config) => {

      try {

         // Extract the JSON for the request body
         // The contents of the file to upload need to be in this format described in the comments above.
         var jsonUtterance = await fse.readJson(config.inFile);

         // Add an utterance
         var utterancePromise = sendUtteranceToApi({
               uri: config.uri,
               method: 'POST',
               headers: {
                  'Ocp-Apim-Subscription-Key': config.LUIS_authoringKey
               },
               json: true,
               body: jsonUtterance
         });

         let results = await utterancePromise;

         console.log(JSON.stringify(results));

      } catch (err) {
         console.log(`Error adding utterance:  ${err.message} `);
         //throw err;
      }

   }

添加 train 函数的方法和对象。Add method and object for train function.

   // training configuration 
   var configTrain = {
      LUIS_authoringKey: LUIS_authoringKey,
      LUIS_appId: LUIS_appId,
      LUIS_versionId: LUIS_versionId,
      uri: "https://chinaeast2.api.cognitive.azure.cn/luis/api/v2.0/apps/{appId}/versions/{versionId}/train".replace("{appId}", LUIS_appId).replace("{versionId}", LUIS_versionId),
      method: 'POST', // POST to request training, GET to get training status
   };

   // Call train
   var train = async (config) => {

      try {

         var trainingPromise = sendUtteranceToApi({
               uri: config.uri,
               method: config.method, // Use POST to request training, GET to get training status 
               headers: {
                  'Ocp-Apim-Subscription-Key': config.LUIS_authoringKey
               },
               json: true,
               body: null      // The body can be empty for a training request
         });

         let results = await trainingPromise;
         console.log(JSON.stringify(results));
         
      } catch (err) {
         console.log(`Error in Training:  ${err.message} `);
         // throw err;
      }

   }

添加函数 sendUtteranceToApi,以发送和接收 HTTP 调用。Add the function sendUtteranceToApi to send and receive HTTP calls.

   // Send JSON as the body of the POST request to the API
   var sendUtteranceToApi = async (options) => {
      try {

         var response; 
         if (options.method === 'POST') {
               response = await rp.post(options);
         } else if (options.method === 'GET') {
               response = await rp.get(options);
         }
         
         return { request: options.body, response: response };

      } catch (err) {
         throw err;
      }
   }

添加用于选择操作的 main 代码。Add the main code that chooses which action.

   var main = async() =>{
      try{

         console.log("Add utterances complete.");
         await addUtterance(configAddUtterance);

         console.log("Train");
         configTrain.method = 'POST';
         await train(configTrain, false);

         console.log("Train status.");
         configTrain.method = 'GET';
         await train(configTrain, true);

         console.log("process done");

      }catch(err){
         throw err;
      }
   }

   // MAIN
   main();

安装依赖项Install dependencies

创建具有以下文本的 package.json 文件:Create package.json file with the following text:

   {
   "name": "node",
   "version": "1.0.0",
   "description": "",
   "main": "add-utterances.js",
   "scripts": {
      "start":"node add-utterances.js",
      "test": "echo \"Error: no test specified\" && exit 1"
   },
   "author": "",
   "license": "ISC",
   "dependencies": {
      "fs-extra": "^5.0.0",
      "request": "^2.83.0",
      "request-promise": "^4.2.2"
   }
   }

在命令行上,从包含 package.json 的目录中使用 NPM 安装依赖项:npm installOn the command-line, from the directory that has the package.json, install dependencies with NPM: npm install.

运行代码Run code

使用 Node.js 在命令行中运行该应用程序。Run the application from a command-line with Node.js.

调用 npm start 将添加话语、进行训练并获取训练状态。Calling npm startadds the utterances, trains, and gets training status.

> npm start 

此命令行显示调用“添加陈述”API 的结果。This command-line displays the results of calling the add utterances API.

用于添加示例话语的 response 数组指示每个具有 hasError 属性的示例话语是成功还是失败。The response array for adding the example utterances indicates success or failure for each example utterance with the hasError property. 以下 JSON 响应显示两个话语都已成功添加。The following JSON response shows both utterances were added successfully.

    "response": [
        {
            "value": {
                "UtteranceText": "go to seattle today",
                "ExampleId": -5123383
            },
            "hasError": false
        },
        {
            "value": {
                "UtteranceText": "book a flight",
                "ExampleId": -169157
            },
            "hasError": false
        }
    ]

以下 JSON 显示了训练请求成功的结果:The following JSON shows the result of a successful request to train:

{
    "request": null,
    "response": {
        "statusId": 9,
        "status": "Queued"
    }
}

以下 JSON 显示了成功请求训练状态的结果。The following JSON shows the result of a successful request for training status. 每个 modelID 都是一个意向。Each modelID is an intent. 每个意向都必须针对所有话语进行训练,以正确识别属于该意向的话语以及不属于该意向的话语。Each intent has to be trained on all the utterances to correctly identify utterances to do belong to the intent as well as utterances that do not belong to the intent.

[
    {
        "modelId": "0c694cf9-8c32-44b8-9ea0-3d30a7d901ca",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "10e53836-ade4-494e-9531-3bd6a944c510",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "21e48732-a512-4c33-b5ed-8ea629465269",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "edee15b1-9999-45c2-bbab-591d3a643033",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "aa78e06e-df81-4bb2-b2d9-a2fbb2f81c54",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "e39bb7bd-b417-41a9-a24f-caf4c47fc62c",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "3782eac7-db84-4d66-ba00-0598dffb48ee",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "a941d926-cb0f-47a8-ab7e-deba4378b96f",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "8137f40e-ce6d-40a5-881f-dfd46a05f7e0",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "dc08f95a-58b4-4064-a210-03fe34f75a3c",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    },
    {
        "modelId": "4fabdbed-5697-4562-8c7d-36e174efff2e",
        "details": {
            "statusId": 3,
            "status": "InProgress",
            "exampleCount": 48
        }
    }
]

清理资源Clean up resources

完成本快速入门后,删除在本快速入门中创建的所有文件。When you are done with the quickstart, remove all the files created in this quickstart.

后续步骤Next steps