快速入门:使用 Python 更改模型Quickstart: Change model using Python

本快速入门使用可用的公共 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 创作密钥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

  1. 将以下代码片段复制到名为 add-utterances-3-6.py 的文件中:Copy the following code snippet into file named add-utterances-3-6.py:
   ########### Python 3.6 #############
   # -*- coding: utf-8 -*-

   import http.client, sys, os.path, json

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

   # ID of your LUIS app to which you want to add an utterance
   LUIS_APP_ID      = "YOUR-APP-ID"

   # The version number of your LUIS app
   LUIS_APP_VERSION = "0.1"

   # Update the host if your LUIS subscription is not in the China East region
   LUIS_HOST       = "chinaeast2.api.cognitive.azure.cn"

   # 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
   UTTERANCE_FILE   = "./utterances.json"
   RESULTS_FILE     = "./utterances.results.json"

   # LUIS client class for adding and training utterances
   class LUISClient:
      
      # endpoint method names
      TRAIN    = "train"
      EXAMPLES = "examples"

      # HTTP verbs
      GET  = "GET"
      POST = "POST"

      # Encoding
      UTF8 = "UTF8"

      # path template for LUIS endpoint URIs
      PATH     = "/luis/api/v2.0/apps/{app_id}/versions/{app_version}/"

      # default HTTP status information for when we haven't yet done a request
      http_status = 200
      reason = ""
      result = ""

      def __init__(self, host, app_id, app_version, key):
         self.key = key
         self.host = host
         self.path = self.PATH.format(app_id=app_id, app_version=app_version)

      def call(self, luis_endpoint, method, data=""):
         path = self.path + luis_endpoint
         headers = {'Ocp-Apim-Subscription-Key': self.key}
         conn = http.client.HTTPSConnection(self.host)
         conn.request(method, path, data.encode(self.UTF8) or None, headers)
         response = conn.getresponse()
         self.result = json.dumps(json.loads(response.read().decode(self.UTF8)),
                                    indent=2)
         self.http_status = response.status
         self.reason = response.reason
         print(self.result)
         return self

      def add_utterances(self, filename=UTTERANCE_FILE):
         with open(filename, encoding=self.UTF8) as utterance:
               data = utterance.read()
         return self.call(self.EXAMPLES, self.POST, data)
         
      def train(self):
         return self.call(self.TRAIN, self.POST)

      def status(self):
         return self.call(self.TRAIN, self.GET)

      def print(self):
         if self.result:
               print(self.result)
         return self

      def raise_for_status(self):
         if 200 <= self.http_status < 300:
               return self
         raise http.client.HTTPException("{} {}".format(
               self.http_status, self.reason))

   if __name__ == "__main__":

      luis = LUISClient(LUIS_HOST, LUIS_APP_ID, LUIS_APP_VERSION,
                        LUIS_authoringKey)

      try:
         print("Adding utterance(s).")
         luis.add_utterances().raise_for_status()

         print("Requesting training.")
         luis.train().raise_for_status()

         print("Requesting training status.")
         luis.status().raise_for_status()

      except Exception as ex:
         luis.print()    # JSON response may have more details
         print("{0.__name__}: {1}".format(type(ex), ex))

运行代码Run code

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

从命令行添加话语Add utterances from the command-line

调用不带参数的 add-utterance 会将陈述添加到应用,但不训练应用。Calling add-utterance with no arguments adds an utterance to the app, without training it.

> python add-utterances-3-6.py

将话语添加到模型时,将返回以下响应。The following response returns when the utterances are added to the model.

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

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

{
    "request": null,
    "response": {
        "statusId": 9,
        "status": "Queued"
    }
}
Requested training status.
[
   {
      "modelId": "eb2f117c-e10a-463e-90ea-1a0176660acc",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "c1bdfbfc-e110-402e-b0cc-2af4112289fb",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "863023ec-2c96-4d68-9c44-34c1cbde8bc9",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "82702162-73ba-4ae9-a6f6-517b5244c555",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "37121f4c-4853-467f-a9f3-6dfc8cad2763",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "de421482-753e-42f5-a765-ad0a60f50d69",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "80f58a45-86f2-4e18-be3d-b60a2c88312e",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "c9eb9772-3b18-4d5f-a1e6-e0c31f91b390",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "2afec2ff-7c01-4423-bb0e-e5f6935afae8",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   },
   {
      "modelId": "95a81c87-0d7b-4251-8e07-f28d180886a1",
      "details": {
         "statusId": 0,
         "status": "Success",
         "exampleCount": 33,
         "trainingDateTime": "2017-11-20T18:09:11Z"
      }
   }
]

清理资源Clean up resources

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

后续步骤Next steps