Share via


快速入門:Language Understanding (LUIS) 客戶端連結庫和 REST API

重要

LUIS 將於 2025 年 10 月 1 日淘汰,而自 2023 年 4 月 1 日開始,您將無法建立新的 LUIS 資源。 建議移轉 LUIS 應用程式交談語言理解,以享有產品持續支援和多語言功能的優點。

使用 C#、Python 或 JavaScript 透過本快速入門,使用 LUIS SDK 用戶端連結庫建立及查詢 Azure LUIS 人工智慧 (AI) 應用程式。 您也可以使用 cURL 來使用 REST API 傳送要求。

Language Understanding (LUIS) 可讓您將自然語言處理 (NLP) 套用至使用者的交談式、自然語言文字,以預測整體意義,並提取相關的詳細資訊。

  • 撰寫用戶端連結庫和 REST API 可讓您建立、編輯、定型和發佈 LUIS 應用程式。
  • 預測運行時間用戶端連結庫和 REST API 可讓您查詢已發佈的應用程式。

使用適用於 .NET 的 Language Understanding (LUIS) 用戶端連結庫來:

  • 建立應用程式
  • 使用範例語句新增意圖、機器學習實體
  • 定型和發佈應用程式
  • 查詢預測運行時間

參考檔案 | 撰寫預測連結庫原始碼 | 撰寫和預測 NuGet | C# 範例

必要條件

設定

建立新的 C# 應用程式

在慣用的編輯器或 IDE 中建立新的 .NET Core 應用程式。

  1. 在主控台視窗中(例如 cmd、PowerShell 或 Bash),使用 dotnet new 命令建立名稱為 language-understanding-quickstart的新控制台應用程式。 此命令會建立簡單的 "Hello World" C# 專案,內含單一原始程式檔:Program.cs

    dotnet new console -n language-understanding-quickstart
    
  2. 將目錄變更為新建立的應用程式資料夾。

    cd language-understanding-quickstart
    
  3. 您可以使用下列命令來建置應用程式:

    dotnet build
    

    建置輸出應該不會有警告或錯誤。

    ...
    Build succeeded.
     0 Warning(s)
     0 Error(s)
    ...
    

安裝 NuGet 連結庫

在應用程式目錄中,使用下列命令安裝適用於 .NET 的 Language Understanding (LUIS) 用戶端連結庫:

dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring --version 3.2.0-preview.3
dotnet add package Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime --version 3.1.0-preview.1

撰寫物件模型

Language Understanding (LUIS) 撰寫用戶端是 LUISAuthoringClient 物件,可向 Azure 進行驗證,其中包含您的撰寫密鑰。

撰寫的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

預測物件模型

Language Understanding (LUIS) 預測運行時間用戶端是 LUISRuntimeClient 物件,可向 Azure 進行驗證,其中包含您的資源密鑰。

預測運行時間的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

程式碼範例

這些代碼段示範如何使用適用於 Python 的 Language Understanding (LUIS) 用戶端連結庫來執行下列動作:

新增相依性

從專案目錄,在慣用的編輯器或 IDE 中開啟 Program.cs 檔案。 以下列using指示詞取代現有的using程式代碼:

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime;
using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime.Models;
using Newtonsoft.Json;

新增未定案程序代碼

  1. 變更 方法的 Main 簽章以允許異步呼叫:

    public static async Task Main()
    
  2. 除非另有指定,否則請在 類別的方法ProgramMain新增其餘的程序代碼。

建立應用程式的變數

建立兩組變數:您變更的第一組變數,第二組會在程式代碼範例中出現時保留。

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  1. 建立變數來保存撰寫金鑰和資源名稱。

    var key = "PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE";
    
    var authoringEndpoint = "PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE";
    var predictionEndpoint = "PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE";
    
  2. 建立變數來保存您的端點、應用程式名稱、版本和意圖名稱。

    var appName = "Contoso Pizza Company";
    var versionId = "0.1";
    var intentName = "OrderPizzaIntent";
    

驗證用戶端

使用您的密鑰建立 ApiKeyServiceClientCredentials 物件,並將其與您的端點搭配使用,以建立 LUISAuthoringClient 物件。

var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(key);
var client = new LUISAuthoringClient(credentials) { Endpoint = authoringEndpoint };

建立 LUIS 應用程式

LUIS 應用程式包含自然語言處理 (NLP) 模型,包括意圖、實體和範例語句。

建立 ApplicationCreateObject。 名稱和語言文化特性是必要屬性。 呼叫 Apps.AddAsync 方法。 回應是應用程式識別碼。

var newApp = new ApplicationCreateObject
{
    Culture = "en-us",
    Name = appName,
    InitialVersionId = versionId
};

var appId = await client.Apps.AddAsync(newApp);

建立應用程式的意圖

LUIS 應用程式模型中的主要對像是意圖。 意圖會與用戶語句 意圖的群組一致。 使用者可能會提出問題,或提出語句,尋找來自 Bot 的特定 預期 回應(或其他用戶端應用程式)。 意圖的範例包括預訂航班、詢問目的地城市中的天氣,以及詢問客戶服務的連絡資訊。

使用唯一意圖的名稱建立 ModelCreateObject ,然後將應用程式識別碼、版本標識碼和 ModelCreateObject 傳遞給 Model.AddIntentAsync 方法。 回應是意圖識別碼。

intentName 會硬式編碼為 OrderPizzaIntent ,做為應用程式區段中的 [建立變數] 區段中的變數 一部分。

await client.Model.AddIntentAsync(appId, versionId, new ModelCreateObject()
{
    Name = intentName
});

建立應用程式的實體

雖然不需要實體,但在大部分的應用程式中都會找到這些實體。 實體會從用戶語句中擷取資訊,以完整定義使用者的意圖。 有數種類型的 預先建置 和自定義實體,每個實體都有自己的數據轉換物件 (DTO) 模型。 要新增至應用程式的常見預先建置實體包括 number、datetimeV2、geographyV2序數。

請務必知道實體未標示意圖。 它們通常適用於許多意圖。 只有範例用戶語句會標示為特定單一意圖。

實體的建立方法是 Model 類別的一部分。 每個實體類型都有自己的數據轉換物件 (DTO) 模型,通常包含 Models 命名空間中的單字model

實體建立程式代碼會建立機器學習實體,其子實體和功能會套用至 Quantity 子實體。

入口網站的部分螢幕快照,其中顯示已建立的實體、具有子實體的機器學習實體,以及套用至 'Quantity' 子實體的功能。

// Add Prebuilt entity
await client.Model.AddPrebuiltAsync(appId, versionId, new[] { "number" });

// Define ml entity with children and grandchildren
var mlEntityDefinition = new EntityModelCreateObject
{
    Name = "Pizza order",
    Children = new[]
    {
        new ChildEntityModelCreateObject
        {
            Name = "Pizza",
            Children = new[]
            {
                new ChildEntityModelCreateObject { Name = "Quantity" },
                new ChildEntityModelCreateObject { Name = "Type" },
                new ChildEntityModelCreateObject { Name = "Size" }
            }
        },
        new ChildEntityModelCreateObject
        {
            Name = "Toppings",
            Children = new[]
            {
                new ChildEntityModelCreateObject { Name = "Type" },
                new ChildEntityModelCreateObject { Name = "Quantity" }
            }
        }
    }
};

// Add ML entity 
var mlEntityId = await client.Model.AddEntityAsync(appId, versionId, mlEntityDefinition); ;

// Add phraselist feature
var phraselistId = await client.Features.AddPhraseListAsync(appId, versionId, new PhraselistCreateObject
{
    EnabledForAllModels = false,
    IsExchangeable = true,
    Name = "QuantityPhraselist",
    Phrases = "few,more,extra"
});

// Get entity and subentities
var model = await client.Model.GetEntityAsync(appId, versionId, mlEntityId);
var toppingQuantityId = GetModelGrandchild(model, "Toppings", "Quantity");
var pizzaQuantityId = GetModelGrandchild(model, "Pizza", "Quantity");

// add model as feature to subentity model
await client.Features.AddEntityFeatureAsync(appId, versionId, pizzaQuantityId, new ModelFeatureInformation { ModelName = "number", IsRequired = true });
await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { ModelName = "number"});

// add phrase list as feature to subentity model
await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { FeatureName = "QuantityPhraselist" });

使用下列方法對 類別尋找 Quantity 子實體的標識碼,以便將特徵指派給該子實體。

static Guid GetModelGrandchild(NDepthEntityExtractor model, string childName, string grandchildName)
{
    return model.Children.
        Single(c => c.Name == childName).
        Children.
        Single(c => c.Name == grandchildName).Id;
}

將範例語句新增至意圖

為了判斷語句的意圖並擷取實體,應用程式需要語句的範例。 這些範例需要以特定單一意圖為目標,而且應該標示所有自定義實體。 預先建置的實體不需要標示。

藉由建立 ExampleLabelObject 物件清單來新增範例語句,每個範例語句各有一個物件。 每個範例都應該使用實體名稱和實體值的名稱/值組字典來標記所有實體。 實體值應該與範例語句的文字中出現的完全相同。

部分螢幕快照,顯示入口網站中標示的範例語句。

使用 應用程式標識碼、版本標識碼和範例呼叫 Examples.AddAsync

// Define labeled example
var labeledExampleUtteranceWithMLEntity = new ExampleLabelObject
{
    Text = "I want two small seafood pizzas with extra cheese.",
    IntentName = intentName,
    EntityLabels = new[]
    {
        new EntityLabelObject
        {
            StartCharIndex = 7,
            EndCharIndex = 48,
            EntityName = "Pizza order",
            Children = new[]
            {
                new EntityLabelObject
                {
                    StartCharIndex = 7,
                    EndCharIndex = 30,
                    EntityName = "Pizza",
                    Children = new[]
                    {
                        new EntityLabelObject { StartCharIndex = 7, EndCharIndex = 9, EntityName = "Quantity" },
                        new EntityLabelObject { StartCharIndex = 11, EndCharIndex = 15, EntityName = "Size" },
                        new EntityLabelObject { StartCharIndex = 17, EndCharIndex = 23, EntityName = "Type" }
                    }
                },
                new EntityLabelObject
                {
                    StartCharIndex = 37,
                    EndCharIndex = 48,
                    EntityName = "Toppings",
                    Children = new[]
                    {
                        new EntityLabelObject { StartCharIndex = 37, EndCharIndex = 41, EntityName = "Quantity" },
                        new EntityLabelObject { StartCharIndex = 43, EndCharIndex = 48, EntityName = "Type" }
                    }
                }
            }
        },
    }
};

// Add an example for the entity.
// Enable nested children to allow using multiple models with the same name.
// The quantity subentity and the phraselist could have the same exact name if this is set to True
await client.Examples.AddAsync(appId, versionId, labeledExampleUtteranceWithMLEntity, enableNestedChildren: true); 

進行應用程式定型

建立模型之後,必須針對此版本的模型定型 LUIS 應用程式。 定型的模型可用於 容器中,或 發佈 至預備或產品位置。

Train.TrainVersionAsync 方法需要應用程式標識碼和版本標識碼。

非常小型的模型,例如本快速入門示範,將會非常快速地定型。 針對生產層級應用程式,訓練應用程式應該包含 GetStatusAsync 方法的輪詢呼叫,以判斷定型何時或是否成功。 回應是一份 ModelTrainingInfo 物件清單,每個物件都有個別的狀態。 所有物件都必須成功,才能將定型視為完成。

await client.Train.TrainVersionAsync(appId, versionId);
while (true)
{
    var status = await client.Train.GetStatusAsync(appId, versionId);
    if (status.All(m => m.Details.Status == "Success"))
    {
        // Assumes that we never fail, and that eventually we'll always succeed.
        break;
    }
}

將應用程式發佈至生產位置

使用 PublishAsync 方法發佈 LUIS 應用程式。 這會將目前定型的版本發佈至端點的指定位置。 用戶端應用程式會使用此端點傳送用戶語句,以預測意圖和實體擷取。

await client.Apps.PublishAsync(appId, new ApplicationPublishObject { VersionId = versionId, IsStaging=false});

驗證預測運行時間用戶端

使用 ApiKeyServiceClientCredentials 物件搭配您的密鑰,並將它與您的端點搭配使用,以建立 LUISRuntimeClient 物件。

警告

本快速入門會使用撰寫密鑰作為運行時間認證的一部分。 撰寫金鑰允許使用一些查詢來查詢運行時間。 針對預備和生產層級程式代碼,請將撰寫金鑰取代為預測運行時間密鑰。

var runtimeClient = new LUISRuntimeClient(credentials) { Endpoint = predictionEndpoint };

從運行時間取得預測

新增下列程序代碼,以建立預測運行時間的要求。

用戶語句是 PredictionRequest 物件的一部分。

GetSlotPredictionAsync 方法需要數個參數,例如應用程式識別碼、位置名稱、預測要求物件以符合要求。 其他選項,例如詳細資訊、顯示所有意圖,以及記錄都是選擇性的。

// Production == slot name
var request = new PredictionRequest { Query = "I want two small pepperoni pizzas with more salsa" };
var prediction = await runtimeClient.Prediction.GetSlotPredictionAsync(appId, "Production", request);
Console.Write(JsonConvert.SerializeObject(prediction, Formatting.Indented));

預測回應是 JSON 物件,包括意圖和找到的任何實體。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

執行應用程式

使用來自應用程式目錄的 dotnet run 命令執行應用程式。

dotnet run

使用 Language Understanding (LUIS) 用戶端連結庫來Node.js:

  • 建立應用程式
  • 使用範例語句新增意圖、機器學習實體
  • 定型和發佈應用程式
  • 查詢預測運行時間

參考文件 | 製作預測NPM | 範例

必要條件

設定

建立新的 JavaScript 應用程式

  1. 在主控台視窗中,為您的應用程式建立新的目錄,並移至該目錄。

    mkdir quickstart-sdk && cd quickstart-sdk
    
  2. 藉由建立 package.json 檔案,將目錄初始化為 JavaScript 應用程式。

    npm init -y
    
  3. 為您的 JavaScript 程式代碼建立名為 index.js 的檔案。

    touch index.js
    

安裝 NPM 連結庫

在應用程式目錄中,使用下列命令安裝相依性,一次執行一行:

npm install @azure/ms-rest-js
npm install @azure/cognitiveservices-luis-authoring
npm install @azure/cognitiveservices-luis-runtime

您的 package.json 看起來應該像這樣:

{
  "name": "quickstart-sdk",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@azure/cognitiveservices-luis-authoring": "^4.0.0-preview.3",
    "@azure/cognitiveservices-luis-runtime": "^5.0.0",
    "@azure/ms-rest-js": "^2.0.8"
  }
}

撰寫物件模型

Language Understanding (LUIS) 撰寫用戶端是 LUISAuthoringClient 物件,可向 Azure 進行驗證,其中包含您的撰寫密鑰。

撰寫的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

預測物件模型

Language Understanding (LUIS) 撰寫用戶端是 LUISAuthoringClient 物件,可向 Azure 進行驗證,其中包含您的撰寫密鑰。

預測運行時間的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

程式碼範例

這些代碼段示範如何使用適用於 Python 的 Language Understanding (LUIS) 用戶端連結庫來執行下列動作:

新增相依性

index.js 慣用的編輯器或 IDE 中開啟檔案,然後新增下列相依性。

const msRest = require("@azure/ms-rest-js");
const LUIS_Authoring = require("@azure/cognitiveservices-luis-authoring");
const LUIS_Prediction = require("@azure/cognitiveservices-luis-runtime");

新增未定案程序代碼

  1. quickstart新增 方法及其呼叫。 此方法會保存其餘大部分的程序代碼。 這個方法會在檔案結尾呼叫。

    const quickstart = async () => {
    
        // add calls here
    
    
    }
    quickstart()
        .then(result => console.log("Done"))
        .catch(err => {
            console.log(`Error: ${err}`)
            })
    
  2. 除非另有指定,否則請在快速入門方法中新增其餘程序代碼。

建立應用程式的變數

建立兩組變數:您變更的第一組變數,第二組會在程式代碼範例中出現時保留。

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  1. 建立變數來保存撰寫金鑰和資源名稱。

    const authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE';
    
    const authoringEndpoint = "PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE";
    const predictionEndpoint = "PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE";
    
  2. 建立變數來保存您的端點、應用程式名稱、版本和意圖名稱。

    const appName = "Contoso Pizza Company";
    const versionId = "0.1";
    const intentName = "OrderPizzaIntent";
    

驗證用戶端

使用您的密鑰建立 CognitiveServicesCredentials 物件,並將其與您的端點搭配使用,以建立 LUISAuthoringClient 物件。

const luisAuthoringCredentials = new msRest.ApiKeyCredentials({
    inHeader: { "Ocp-Apim-Subscription-Key": authoringKey }
});
const client = new LUIS_Authoring.LUISAuthoringClient(
    luisAuthoringCredentials,
    authoringEndpoint
);

建立 LUIS 應用程式

LUIS 應用程式包含自然語言處理 (NLP) 模型,包括意圖、實體和範例語句。

建立 AppsOperation 物件的 add 方法,以建立應用程式。 名稱和語言文化特性是必要屬性。

const create_app_payload = {
    name: appName,
    initialVersionId: versionId,
    culture: "en-us"
};

const createAppResult = await client.apps.add(
    create_app_payload
);

const appId = createAppResult.body

建立應用程式的意圖

LUIS 應用程式模型中的主要對像是意圖。 意圖會與用戶語句 意圖的群組對齊。 使用者可能會提出問題,或提出語句,尋找來自 Bot 的特定 預期 回應(或其他用戶端應用程式)。 意圖的範例包括預訂航班、詢問目的地城市中的天氣,以及詢問客戶服務的連絡資訊。

使用具有唯一意圖名稱的 model.add_intent 方法,然後傳遞應用程式識別碼、版本標識碼和新意圖名稱。

intentName 會硬式編碼為 OrderPizzaIntent ,做為應用程式區段中的 [建立變數] 區段中的變數 一部分。

await client.model.addIntent(
    appId,
    versionId,
    { name: intentName }
);

建立應用程式的實體

雖然不需要實體,但在大部分的應用程式中都會找到這些實體。 實體會從用戶語句中擷取資訊,以完整定義使用者的意圖。 有數種類型的 預先建置 和自定義實體,每個實體都有自己的數據轉換物件 (DTO) 模型。 要新增至應用程式的常見預先建置實體包括 number、datetimeV2、geographyV2序數。

請務必知道實體未標示意圖。 它們通常適用於許多意圖。 只有範例用戶語句會標示為特定單一意圖。

實體的建立方法是 Model 類別的一部分。 每個實體類型都有自己的數據轉換物件 (DTO) 模型。

實體建立程式代碼會建立機器學習實體,其子實體和功能會套用至 Quantity 子實體。

入口網站的部分螢幕快照,其中顯示已建立的實體、具有子實體的機器學習實體,以及套用至 'Quantity' 子實體的功能。

// Add Prebuilt entity
await client.model.addPrebuilt(appId, versionId, ["number"]);

// Define ml entity with children and grandchildren
const mlEntityDefinition = {
    name: "Pizza order",
    children: [
        {
            name: "Pizza",
            children: [
                { name: "Quantity" },
                { name: "Type" },
                { name: "Size" }
            ]
        },
        {
            name: "Toppings",
            children: [
                { name: "Type" },
                { name: "Quantity" }
            ]
        }
    ]
};

// Add ML entity 
const response = await client.model.addEntity(appId, versionId, mlEntityDefinition);
const mlEntityId = response.body;

// Add phraselist feature
const phraselistResponse = await client.features.addPhraseList(appId, versionId, {
    enabledForAllModels: false,
    isExchangeable: true,
    name: "QuantityPhraselist",
    phrases: "few,more,extra"
});
const phraseListId = phraselistResponse.body;

// Get entity and subentities
const model = await client.model.getEntity(appId, versionId, mlEntityId);
const toppingQuantityId = getModelGrandchild(model, "Toppings", "Quantity");
const pizzaQuantityId = getModelGrandchild(model, "Pizza", "Quantity");

// add model as feature to subentity model
await client.features.addEntityFeature(appId, versionId, pizzaQuantityId, { modelName: "number", isRequired: true });
await client.features.addEntityFeature(appId, versionId, toppingQuantityId, { modelName: "number" });

// add phrase list as feature to subentity model
await client.features.addEntityFeature(appId, versionId, toppingQuantityId, { featureName: "QuantityPhraselist" });

將下列方法放在 方法上方 quickstart ,以尋找 Quantity 子實體的標識碼,以便將特徵指派給該子實體。

const getModelGrandchild = (model, childName, grandchildName) => {

    return model.children.find(c => c.name == childName).children.find(c => c.name == grandchildName).id

}

將範例語句新增至意圖

為了判斷語句的意圖並擷取實體,應用程式需要語句的範例。 這些範例需要以特定單一意圖為目標,而且應該標示所有自定義實體。 預先建置的實體不需要標示。

藉由建立 ExampleLabelObject 物件清單來新增範例語句,每個範例語句各有一個物件。 每個範例都應該使用實體名稱和實體值的名稱/值組字典來標記所有實體。 實體值應該與範例語句的文字中出現的完全相同。

部分螢幕快照,顯示入口網站中標示的範例語句。

使用 應用程式標識碼、版本標識碼和範例呼叫 examples.add

// Define labeled example
const labeledExampleUtteranceWithMLEntity =
{
    text: "I want two small seafood pizzas with extra cheese.",
    intentName: intentName,
    entityLabels: [
        {
            startCharIndex: 7,
            endCharIndex: 48,
            entityName: "Pizza order",
            children: [
                {
                    startCharIndex: 7,
                    endCharIndex: 30,
                    entityName: "Pizza",
                    children: [
                        {
                            startCharIndex: 7,
                            endCharIndex: 9,
                            entityName: "Quantity"
                        },
                        {
                            startCharIndex: 11,
                            endCharIndex: 15,
                            entityName: "Size"
                        },
                        {
                            startCharIndex: 17,
                            endCharIndex: 23,
                            entityName: "Type"
                        }]
                },
                {
                    startCharIndex: 37,
                    endCharIndex: 48,
                    entityName: "Toppings",
                    children: [
                        {
                            startCharIndex: 37,
                            endCharIndex: 41,
                            entityName: "Quantity"
                        },
                        {
                            startCharIndex: 43,
                            endCharIndex: 48,
                            entityName: "Type"
                        }]
                }
            ]
        }
    ]
};

console.log("Labeled Example Utterance:", JSON.stringify(labeledExampleUtteranceWithMLEntity, null, 4 ));

// Add an example for the entity.
// Enable nested children to allow using multiple models with the same name.
// The quantity subentity and the phraselist could have the same exact name if this is set to True
await client.examples.add(appId, versionId, labeledExampleUtteranceWithMLEntity, { enableNestedChildren: true });

進行應用程式定型

建立模型之後,必須針對此版本的模型定型 LUIS 應用程式。 定型的模型可用於 容器中,或 發佈 至預備或產品位置。

train.trainVersion 方法需要應用程式標識碼和版本標識碼。

非常小型的模型,例如本快速入門示範,將會非常快速地定型。 針對生產層級應用程式,定型應用程式應該包含對get_status方法的輪詢呼叫,以判斷定型何時或是否成功。 回應是一份 ModelTrainingInfo 物件清單,每個物件都有個別的狀態。 所有物件都必須成功,才能將定型視為完成。

await client.train.trainVersion(appId, versionId);
while (true) {
    const status = await client.train.getStatus(appId, versionId);
    if (status.every(m => m.details.status == "Success")) {
        // Assumes that we never fail, and that eventually we'll always succeed.
        break;
    }
}

將應用程式發佈至生產位置

使用 app.publish 方法發佈 LUIS 應用程式。 這會將目前定型的版本發佈至端點的指定位置。 用戶端應用程式會使用此端點傳送用戶語句,以預測意圖和實體擷取。

await client.apps.publish(appId, { versionId: versionId, isStaging: false });

驗證預測運行時間用戶端

搭配密鑰使用 msRest.ApiKeyCredentials 物件,並將它與您的端點搭配使用,以建立 LUIS。LUISRuntimeClient 物件。

警告

本快速入門會使用撰寫密鑰作為運行時間認證的一部分。 撰寫金鑰允許使用一些查詢來查詢運行時間。 針對預備和生產層級程式代碼,請將撰寫金鑰取代為預測運行時間密鑰。

const luisPredictionClient = new LUIS_Prediction.LUISRuntimeClient(
    luisAuthoringCredentials,
    predictionEndpoint
);

從運行時間取得預測

新增下列程序代碼,以建立預測運行時間的要求。 用戶語句是 predictionRequest 物件的一部分。

luisRuntimeClient.prediction.getSlotPrediction 方法需要數個參數,例如應用程式標識符、位置名稱和預測要求物件,才能滿足要求。 其他選項,例如詳細資訊、顯示所有意圖,以及記錄都是選擇性的。

// Production == slot name
const request = { query: "I want two small pepperoni pizzas with more salsa" };
const response = await luisPredictionClient.prediction.getSlotPrediction(appId, "Production", request);
console.log(JSON.stringify(response.prediction, null, 4 ));

預測回應是 JSON 物件,包括意圖和找到的任何實體。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

執行應用程式

node index.js 快速入門檔案上使用 命令執行應用程式。

node index.js

使用適用於 Python 的 Language Understanding (LUIS) 用戶端連結庫來:

  • 建立應用程式
  • 使用範例語句新增意圖、機器學習實體
  • 定型和發佈應用程式
  • 查詢預測運行時間

參考檔案 | 撰寫預測 連結庫原始碼 | 套件 (Pypi) | 範例

必要條件

  • Python 3.x目前版本。
  • Azure 訂用帳戶 - 建立免費帳戶
  • 擁有 Azure 訂用帳戶之後,請在 Azure 入口網站 中建立 Language Understanding 撰寫資源,以取得您的密鑰和端點。 等候部署,然後按兩下 [移至資源 ] 按鈕。
    • 您需要從您 建立 的資源取得密鑰和端點,才能將應用程式連線到 Language Understanding 撰寫。 您稍後會在快速入門中將金鑰和端點貼到下列程式代碼中。 您可以使用免費定價層 (F0) 來試用服務。

設定

建立新的 Python 應用程式

  1. 在主控台視窗中,為您的應用程式建立新的目錄,並移至該目錄。

    mkdir quickstart-sdk && cd quickstart-sdk
    
  2. 為您的 Python 程式代碼建立名為 authoring_and_predict.py 的檔案。

    touch authoring_and_predict.py
    

使用 Pip 安裝客戶端連結庫

在應用程式目錄中,使用下列命令安裝適用於 Python 的 Language Understanding (LUIS) 用戶端連結庫:

pip install azure-cognitiveservices-language-luis

撰寫物件模型

Language Understanding (LUIS) 撰寫用戶端是 LUISAuthoringClient 物件,可向 Azure 進行驗證,其中包含您的撰寫密鑰。

撰寫的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

預測物件模型

Language Understanding (LUIS) 預測運行時間用戶端是 LUISRuntimeClient 物件,可向 Azure 進行驗證,其中包含您的資源密鑰。

預測運行時間的程式代碼範例

建立客戶端之後,請使用此用戶端來存取功能,包括:

程式碼範例

這些代碼段示範如何使用適用於 Python 的 Language Understanding (LUIS) 用戶端連結庫來執行下列動作:

新增相依性

將客戶端連結庫新增至 Python 檔案。

from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from azure.cognitiveservices.language.luis.authoring.models import ApplicationCreateObject
from azure.cognitiveservices.language.luis.runtime import LUISRuntimeClient
from msrest.authentication import CognitiveServicesCredentials
from functools import reduce

import json, time, uuid

新增未定案程序代碼

  1. quickstart新增 方法及其呼叫。 此方法會保存其餘大部分的程序代碼。 這個方法會在檔案結尾呼叫。

    def quickstart():
    
        # add calls here, remember to indent properly
    
    quickstart()
    
  2. 除非另有指定,否則請在快速入門方法中新增其餘程序代碼。

建立應用程式的變數

建立兩組變數:您變更的第一組變數,第二組會在程式代碼範例中出現時保留。

重要

完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  1. 建立變數來保存撰寫金鑰和資源名稱。

    authoringKey = 'PASTE_YOUR_LUIS_AUTHORING_SUBSCRIPTION_KEY_HERE'
    authoringEndpoint = 'PASTE_YOUR_LUIS_AUTHORING_ENDPOINT_HERE'
    predictionKey = 'PASTE_YOUR_LUIS_PREDICTION_SUBSCRIPTION_KEY_HERE'
    predictionEndpoint = 'PASTE_YOUR_LUIS_PREDICTION_ENDPOINT_HERE'
    
  2. 建立變數來保存您的端點、應用程式名稱、版本和意圖名稱。

    # We use a UUID to avoid name collisions.
    appName = "Contoso Pizza Company " + str(uuid.uuid4())
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    

驗證用戶端

使用您的密鑰建立 CognitiveServicesCredentials 物件,並將其與您的端點搭配使用,以建立 LUISAuthoringClient 物件。

client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))

建立 LUIS 應用程式

LUIS 應用程式包含自然語言處理 (NLP) 模型,包括意圖、實體和範例語句。

建立 AppsOperation 物件的 add 方法,以建立應用程式。 名稱和語言文化特性是必要屬性。

# define app basics
appDefinition = ApplicationCreateObject (name=appName, initial_version_id=versionId, culture='en-us')

# create app
app_id = client.apps.add(appDefinition)

# get app id - necessary for all other changes
print("Created LUIS app with ID {}".format(app_id))

建立應用程式的意圖

LUIS 應用程式模型中的主要對像是意圖。 意圖會與用戶語句 意圖的群組對齊。 使用者可能會提出問題,或提出語句,尋找來自 Bot 的特定 預期 回應(或其他用戶端應用程式)。 意圖的範例包括預訂航班、詢問目的地城市中的天氣,以及詢問客戶服務的連絡資訊。

使用具有唯一意圖名稱的 model.add_intent 方法,然後傳遞應用程式識別碼、版本標識碼和新意圖名稱。

intentName 會硬式編碼為 OrderPizzaIntent ,做為應用程式區段中的 [建立變數] 區段中的變數 一部分。

client.model.add_intent(app_id, versionId, intentName)

建立應用程式的實體

雖然不需要實體,但在大部分的應用程式中都會找到這些實體。 實體會從用戶語句中擷取資訊,以完整定義使用者的意圖。 有數種類型的 預先建置 和自定義實體,每個實體都有自己的數據轉換物件 (DTO) 模型。 要新增至應用程式的常見預先建置實體包括 number、datetimeV2、geographyV2序數。

請務必知道實體未標示意圖。 它們通常適用於許多意圖。 只有範例用戶語句會標示為特定單一意圖。

實體的建立方法是 ModelOperations 類別的一部分。 每個實體類型都有自己的數據轉換物件 (DTO) 模型。

實體建立程式代碼會建立機器學習實體,其子實體和功能會套用至 Quantity 子實體。

入口網站的部分螢幕快照,其中顯示已建立的實體、具有子實體的機器學習實體,以及套用至 'Quantity' 子實體的功能。

# Add Prebuilt entity
client.model.add_prebuilt(app_id, versionId, prebuilt_extractor_names=["number"])

# define machine-learned entity
mlEntityDefinition = [
{
    "name": "Pizza",
    "children": [
        { "name": "Quantity" },
        { "name": "Type" },
        { "name": "Size" }
    ]
},
{
    "name": "Toppings",
    "children": [
        { "name": "Type" },
        { "name": "Quantity" }
    ]
}]

# add entity to app
modelId = client.model.add_entity(app_id, versionId, name="Pizza order", children=mlEntityDefinition)

# define phraselist - add phrases as significant vocabulary to app
phraseList = {
    "enabledForAllModels": False,
    "isExchangeable": True,
    "name": "QuantityPhraselist",
    "phrases": "few,more,extra"
}

# add phrase list to app
phraseListId = client.features.add_phrase_list(app_id, versionId, phraseList)

# Get entity and subentities
modelObject = client.model.get_entity(app_id, versionId, modelId)
toppingQuantityId = get_grandchild_id(modelObject, "Toppings", "Quantity")
pizzaQuantityId = get_grandchild_id(modelObject, "Pizza", "Quantity")

# add model as feature to subentity model
prebuiltFeatureRequiredDefinition = { "model_name": "number", "is_required": True }
client.features.add_entity_feature(app_id, versionId, pizzaQuantityId, prebuiltFeatureRequiredDefinition)

# add model as feature to subentity model
prebuiltFeatureNotRequiredDefinition = { "model_name": "number" }
client.features.add_entity_feature(app_id, versionId, toppingQuantityId, prebuiltFeatureNotRequiredDefinition)

# add phrase list as feature to subentity model
phraseListFeatureDefinition = { "feature_name": "QuantityPhraselist", "model_name": None }
client.features.add_entity_feature(app_id, versionId, toppingQuantityId, phraseListFeatureDefinition)

將下列方法放在 方法上方 quickstart ,以尋找 Quantity 子實體的標識碼,以便將特徵指派給該子實體。

def get_grandchild_id(model, childName, grandChildName):
    
    theseChildren = next(filter((lambda child: child.name == childName), model.children))
    theseGrandchildren = next(filter((lambda child: child.name == grandChildName), theseChildren.children))
    
    grandChildId = theseGrandchildren.id
    
    return grandChildId

將範例語句新增至意圖

為了判斷語句的意圖並擷取實體,應用程式需要語句的範例。 這些範例需要以特定單一意圖為目標,而且應該標示所有自定義實體。 預先建置的實體不需要標示。

藉由建立 ExampleLabelObject 物件清單來新增範例語句,每個範例語句各有一個物件。 每個範例都應該使用實體名稱和實體值的名稱/值組字典來標記所有實體。 實體值應該與範例語句的文字中出現的完全相同。

部分螢幕快照,顯示入口網站中標示的範例語句。

使用 應用程式標識碼、版本標識碼和範例呼叫 examples.add

# Define labeled example
labeledExampleUtteranceWithMLEntity = {
    "text": "I want two small seafood pizzas with extra cheese.",
    "intentName": intentName,
    "entityLabels": [
        {
            "startCharIndex": 7,
            "endCharIndex": 48,
            "entityName": "Pizza order",
            "children": [
                {
                    "startCharIndex": 7,
                    "endCharIndex": 30,
                    "entityName": "Pizza",
                    "children": [
                        {
                            "startCharIndex": 7,
                            "endCharIndex": 9,
                            "entityName": "Quantity"
                        },
                        {
                            "startCharIndex": 11,
                            "endCharIndex": 15,
                            "entityName": "Size"
                        },
                        {
                            "startCharIndex": 17,
                            "endCharIndex": 23,
                            "entityName": "Type"
                        }]
                },
                {
                    "startCharIndex": 37,
                    "endCharIndex": 48,
                    "entityName": "Toppings",
                    "children": [
                        {
                            "startCharIndex": 37,
                            "endCharIndex": 41,
                            "entityName": "Quantity"
                        },
                        {
                            "startCharIndex": 43,
                            "endCharIndex": 48,
                            "entityName": "Type"
                        }]
                }
            ]
        }
    ]
}

print("Labeled Example Utterance:", labeledExampleUtteranceWithMLEntity)

# Add an example for the entity.
# Enable nested children to allow using multiple models with the same name.
# The quantity subentity and the phraselist could have the same exact name if this is set to True
client.examples.add(app_id, versionId, labeledExampleUtteranceWithMLEntity, { "enableNestedChildren": True })

進行應用程式定型

建立模型之後,必須針對此版本的模型定型 LUIS 應用程式。 定型的模型可用於 容器中,或 發佈 至預備或產品位置。

train.train_version方法需要應用程式識別碼和版本標識碼。

非常小型的模型,例如本快速入門示範,將會非常快速地定型。 針對生產層級應用程式,定型應用程式應該包含對get_status方法的輪詢呼叫,以判斷定型何時或是否成功。 回應是一份 ModelTrainingInfo 物件清單,每個物件都有個別的狀態。 所有物件都必須成功,才能將定型視為完成。

client.train.train_version(app_id, versionId)
waiting = True
while waiting:
    info = client.train.get_status(app_id, versionId)

    # get_status returns a list of training statuses, one for each model. Loop through them and make sure all are done.
    waiting = any(map(lambda x: 'Queued' == x.details.status or 'InProgress' == x.details.status, info))
    if waiting:
        print ("Waiting 10 seconds for training to complete...")
        time.sleep(10)
    else: 
        print ("trained")
        waiting = False

將應用程式發佈至生產位置

使用 app.publish 方法發佈 LUIS 應用程式。 這會將目前定型的版本發佈至端點的指定位置。 用戶端應用程式會使用此端點傳送用戶語句,以預測意圖和實體擷取。

# Mark the app as public so we can query it using any prediction endpoint.
# Note: For production scenarios, you should instead assign the app to your own LUIS prediction endpoint. See:
# https://docs.microsoft.com/en-gb/azure/cognitive-services/luis/luis-how-to-azure-subscription#assign-a-resource-to-an-app
client.apps.update_settings(app_id, is_public=True)

responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)

驗證預測運行時間用戶端

使用認證物件搭配您的金鑰,並將它與您的端點搭配使用,以建立 LUISRuntimeClientConfiguration 物件。

警告

本快速入門會使用撰寫密鑰作為運行時間認證的一部分。 撰寫金鑰允許使用一些查詢來查詢運行時間。 針對預備和生產層級程式代碼,請將撰寫金鑰取代為預測運行時間密鑰。

runtimeCredentials = CognitiveServicesCredentials(predictionKey)
clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)

從運行時間取得預測

新增下列程序代碼,以建立預測運行時間的要求。

使用者語句是prediction_request 物件的一部分

get_slot_prediction方法需要數個參數,例如應用程式識別碼、位置名稱和預測要求物件,才能滿足要求。 其他選項,例如詳細資訊、顯示所有意圖,以及記錄都是選擇性的。 要求會傳 回 PredictionResponse 物件。

# Production == slot name
predictionRequest = { "query" : "I want two small pepperoni pizzas with more salsa" }

predictionResponse = clientRuntime.prediction.get_slot_prediction(app_id, "Production", predictionRequest)
print("Top intent: {}".format(predictionResponse.prediction.top_intent))
print("Sentiment: {}".format (predictionResponse.prediction.sentiment))
print("Intents: ")

for intent in predictionResponse.prediction.intents:
    print("\t{}".format (json.dumps (intent)))
print("Entities: {}".format (predictionResponse.prediction.entities))

預測回應是 JSON 物件,包括意圖和找到的任何實體。

{
    "query": "I want two small pepperoni pizzas with more salsa",
    "prediction": {
        "topIntent": "OrderPizzaIntent",
        "intents": {
            "OrderPizzaIntent": {
                "score": 0.753606856
            },
            "None": {
                "score": 0.119097039
            }
        },
        "entities": {
            "Pizza order": [
                {
                    "Pizza": [
                        {
                            "Quantity": [
                                2
                            ],
                            "Type": [
                                "pepperoni"
                            ],
                            "Size": [
                                "small"
                            ],
                            "$instance": {
                                "Quantity": [
                                    {
                                        "type": "builtin.number",
                                        "text": "two",
                                        "startIndex": 7,
                                        "length": 3,
                                        "score": 0.968156934,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "pepperoni",
                                        "startIndex": 17,
                                        "length": 9,
                                        "score": 0.9345611,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Size": [
                                    {
                                        "type": "Size",
                                        "text": "small",
                                        "startIndex": 11,
                                        "length": 5,
                                        "score": 0.9592077,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "Toppings": [
                        {
                            "Type": [
                                "salsa"
                            ],
                            "Quantity": [
                                "more"
                            ],
                            "$instance": {
                                "Type": [
                                    {
                                        "type": "Type",
                                        "text": "salsa",
                                        "startIndex": 44,
                                        "length": 5,
                                        "score": 0.7292897,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ],
                                "Quantity": [
                                    {
                                        "type": "Quantity",
                                        "text": "more",
                                        "startIndex": 39,
                                        "length": 4,
                                        "score": 0.9320932,
                                        "modelTypeId": 1,
                                        "modelType": "Entity Extractor",
                                        "recognitionSources": [
                                            "model"
                                        ]
                                    }
                                ]
                            }
                        }
                    ],
                    "$instance": {
                        "Pizza": [
                            {
                                "type": "Pizza",
                                "text": "two small pepperoni pizzas",
                                "startIndex": 7,
                                "length": 26,
                                "score": 0.812199831,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ],
                        "Toppings": [
                            {
                                "type": "Toppings",
                                "text": "more salsa",
                                "startIndex": 39,
                                "length": 10,
                                "score": 0.7250252,
                                "modelTypeId": 1,
                                "modelType": "Entity Extractor",
                                "recognitionSources": [
                                    "model"
                                ]
                            }
                        ]
                    }
                }
            ],
            "$instance": {
                "Pizza order": [
                    {
                        "type": "Pizza order",
                        "text": "two small pepperoni pizzas with more salsa",
                        "startIndex": 7,
                        "length": 42,
                        "score": 0.769223332,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                            "model"
                        ]
                    }
                ]
            }
        }
    }
}

執行應用程式

python 快速入門檔案上使用 命令執行應用程式。

python authoring_and_predict.py

遵循本快速入門,您將依序執行三個 REST 呼叫。

參考文件

必要條件

  • 免費 LUIS 帳戶。

  • Visual Studio Code 之類的文本編輯器。

  • 命令行程式 cURL。 cURL 程式已安裝在macOS、大部分Linux發行版和Windows 10組建1803和更新版本上。

    如果您需要安裝 cURL,您可以從 cURL 下載頁面下載 cURL

建立披薩應用程式

建立 Pizza 應用程式。

  1. 選取 pizza-app-for-luis-v6.json 以顯示 pizza-app-for-luis.json 檔案的 GitHub 頁面。
  2. 以滑鼠右鍵按一下或長點選 [原始] 按鈕,然後選取 [另存連結]pizza-app-for-luis.json 儲存到您的電腦。
  3. 登入 LUIS 入口網站
  4. 選取我的應用程式
  5. 在 [我的應用程式] 頁面中,選取 [+ 新增對話應用程式]
  6. 選取 [匯入為 JSON]
  7. 在 [匯入新的應用程式] 對話方塊中,選取 [選擇檔案] 按鈕。
  8. 選取您下載的 pizza-app-for-luis.json 檔案,然後選取 [開啟]
  9. 在 [匯入新的應用程式] 對話方塊的 [名稱] 欄位中,輸入您 Pizza 應用程式的名稱,然後選取 [完成] 按鈕。

應用程式將會匯入。

如果您看到 [如何建立有效的 LUIS 應用程式] 對話方塊,請關閉對話方塊。

將 Pizza 應用程式定型並發佈

您應該會看到 [意圖] 頁面,其中包含 Pizza 應用程式中的意圖清單。

  1. 在 LUIS 網站的右上方,選取 [定型] 按鈕。

    訓練按鈕

  2. [定型] 按鈕停用時,定型即完成。

若要在聊天機器人或其他用戶端應用程式中收到 LUIS 預測,則須將應用程式發佈到預測端點。

  1. 選取右上方導覽列中的 [發佈]

    發佈至端點之按鈕的螢幕快照。

  2. 選取 [生產位置],然後選取 [完成]

    LUIS 發佈至端點的螢幕快照。

  3. 選取通知中的 [存取您的端點 URL],以移至 [Azure 資源] 頁面。 只有在具有與應用程式相關聯的預測資源時,您才能夠看到 URL。 您也可以按一下 [管理] 以尋找 [Azure 資源] 頁面。

    顯示應用程式已發佈之訊息的螢幕快照。

將撰寫資源新增至 Pizza 應用程式

  1. 選取 [管理]
  2. 選取 [Azure 資源]
  3. 選取 [製作資源]
  4. 選取 [變更製作資源]

如果您有撰寫資源,請輸入租用戶名稱訂用帳戶名稱,以及您撰寫資源的 LUIS 資源名稱

如果您沒有撰寫資源:

  1. 選取 [建立新的資源]
  2. 輸入租用戶名稱資源名稱訂用帳戶名稱Azure 資源群組名稱

您的 Pizza 應用程式現在已準備好可以使用。

針對您的 Pizza 應用程式記錄存取值

若要使用您新的 Pizza 應用程式,將需要 Pizza 應用程式的應用程式識別碼、撰寫金鑰和撰寫端點。 若要取得預測,您需要個別的預測端點和預測金鑰。

若要尋找這些值:

  1. 從 [意圖] 頁面上,選取 [管理]
  2. 從 [應用程式設定] 頁面上,記錄 [應用程式識別碼]
  3. 選取 [Azure 資源]
  4. 選取 [製作資源]
  5. 從 [撰寫資源] 和 [預測資源] 索引標籤中,記下主要金鑰。 此值是您的撰寫金鑰。
  6. 記錄 [端點 URL]。 此值是您的撰寫端點。

建立 JSON 檔案來定型披薩應用程式

若要建立具有三個範例語句的 JSON 檔案,請將下列 JSON 數據儲存至名為 ExampleUtterances.JSON的檔案:

[
  {
    "text": "order a pizza",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 6,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "order a large pepperoni pizza",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 6,
        "endCharIndex": 28
      },
      {
        "entityName": "FullPizzaWithModifiers",
        "startCharIndex": 6,
        "endCharIndex": 28
      },
      {
        "entityName": "PizzaType",
        "startCharIndex": 14,
        "endCharIndex": 28
      },
      {
        "entityName": "Size",
        "startCharIndex": 8,
        "endCharIndex": 12
      }
    ]
  },
  {
    "text": "I want two large pepperoni pizzas on thin crust",
    "intentName": "ModifyOrder",
    "entityLabels": [
      {
        "entityName": "Order",
        "startCharIndex": 7,
        "endCharIndex": 46
      },
      {
        "entityName": "FullPizzaWithModifiers",
        "startCharIndex": 7,
        "endCharIndex": 46
      },
      {
        "entityName": "PizzaType",
        "startCharIndex": 17,
        "endCharIndex": 32
      },
      {
        "entityName": "Size",
        "startCharIndex": 11,
        "endCharIndex": 15
      },
      {
        "entityName": "Quantity",
        "startCharIndex": 7,
        "endCharIndex": 9
      },
      {
        "entityName": "Crust",
        "startCharIndex": 37,
        "endCharIndex": 46
      }
    ]
  }
]`

範例語句 JSON 遵循特定格式。

text 欄位包含範例語句的文字。 intentName 欄位必須對應到 LUIS 應用程式中的現有意圖名稱。 entityLabels 是必填欄位。 如果您不想要標示任何實體,請提供空白陣列。

如果 entityLabels 陣列不是空的,startCharIndexendCharIndex 必須標示 entityName 欄位中參考的實體。 索引以零為起始。 如果您在文字中的某個空格開始或結束標籤,新增語句的 API 呼叫將會失敗。

新增範例語句

  1. 若要上傳範例語句的批次,請將此命令複製到文字編輯器中:

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/examples?verbose=true&show-all-intents=true" ^
          --request POST ^
          --header "Content-Type:application/json" ^
          --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***" ^
          --data "@ExampleUtterances.JSON"
    
  2. 使用您自己的值取代以 ***YOUR- 開頭的值。

    資訊 目的
    ***YOUR-AUTHORING-ENDPOINT*** 您的撰寫 URL 端點。 例如:「https://REPLACE-WITH-YOUR-RESOURCE-NAME.api.cognitive.microsoft.com/"。 您已在建立資源時設定資源名稱。
    ***YOUR-APP-ID*** 您的 LUIS 應用程式識別碼。
    ***YOUR-APP-VERSION*** 您的 LUIS 應用程式版本。 針對 Pizza 應用程式,版本號碼為 “0.1”,不含引號。
    ***YOUR-AUTHORING-KEY*** 您的 32 字元撰寫金鑰。

    在 LUIS 入口網站中,您可以在 [Azure 資源] 頁面上的 [管理] 區段中看到指派的金鑰和端點。 在相同的 [管理] 區段中,您可以在 [應用程式設定] 頁面上取得應用程式識別碼。

    重要

    完成時,請記得從程式碼中移除金鑰,且不要公開張貼金鑰。 在生產環境中,請使用安全的方式來儲存和存取您的認證,例如 Azure Key Vault。 如需詳細資訊,請參閱 Azure AI 服務安全性一文。

  3. 啟動命令提示字元 (Windows) 或終端機 (macOS 和 Linux),並將目錄變更為您儲存盤案 ExampleUtterances.JSON 的相同目錄。

  4. 從編輯器複製 cURL 命令,並將其貼到命令提示字元 (Windows) 或終端機 (macOS 和 Linux) 中。 按 Enter 以執行命令。

    您應該會看到下列回應:

    [{"value":{"ExampleId":1255129706,"UtteranceText":"order a pizza"},"hasError":false},{"value":{"ExampleId":1255129707,"UtteranceText":"order a large pepperoni pizza"},"hasError":false},{"value":{"ExampleId":1255129708,"UtteranceText":"i want two large pepperoni pizzas on thin crust"},"hasError":false}]
    

    以下是針對可讀性格式化的輸出:

    [
      {
        "value": {
          "ExampleId": 1255129706,
          "UtteranceText": "order a pizza"
        },
        "hasError": false
      },
      {
        "value": {
          "ExampleId": 1255129707,
          "UtteranceText": "order a large pepperoni pizza"
        },
        "hasError": false
      },
      {
        "value": {
          "ExampleId": 1255129708,
          "UtteranceText": "i want two large pepperoni pizzas on thin crust"
        },
        "hasError": false
      }
    ]
    

定型披薩應用程式模型

  1. 若要開始披薩應用程式的訓練課程,請將此命令複製到文字編輯器中:

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/train?verbose=true&show-all-intents=true" ^
          --data "" ^
          --request POST ^
          --header "Content-Type:application/json" ^
          --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***"
    
  2. 如同您先前所做的,請將開頭 ***YOUR- 的值取代為您自己的值。

  3. 從編輯器複製 cURL 命令,並將其貼到命令提示字元 (Windows) 或終端機 (macOS 和 Linux) 中。 按 Enter 以執行命令。

    您應該會看到下列回應:

    {"statusId":2,"status":"UpToDate"}
    

    以下是針對可讀性格式化的輸出:

    {
      "statusId": 2,
      "status": "UpToDate"
    }
    

取得訓練狀態

  1. 若要取得定型工作階段的定型狀態,請將此命令複製到文字編輯器中:

    curl "***YOUR-AUTHORING-ENDPOINT***/luis/authoring/v3.0-preview/apps/***YOUR-APP-ID***/versions/***YOUR-APP-VERSION***/train?verbose=true&show-all-intents=true" ^
            --request GET ^
            --header "Content-Type:application/json" ^
            --header "Ocp-Apim-Subscription-Key: ***YOUR-AUTHORING-KEY***"
    
  2. 如同您先前所做的,請將開頭 ***YOUR- 的值取代為您自己的值。

  3. 從編輯器複製 cURL 命令,並將其貼到命令提示字元 (Windows) 或終端機 (macOS 和 Linux) 中。 按 Enter 以執行命令。

    您應該會看到下列回應:

    [{"modelId":"8eb7ad8f-5db5-4c28-819b-ca3905fffd80","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6f53bc92-ae54-44ce-bc4e-010d1f8cfda0","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6cb17888-ad6e-464c-82c0-d37fd1f2c4f8","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"a16fc4fd-1949-4e77-9de3-30369f16c3a5","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"6bacdb75-1889-4f93-8971-8c8995ff8960","details":{"statusId":2,"status":"UpToDate","exampleCount":171}},{"modelId":"be963f4c-4898-48d7-9eba-3c6af0867b9d","details":{"statusId":2,"status":"UpToDate","exampleCount":171}}]
    

    以下是針對可讀性格式化的輸出:

    [
      {
        "modelId": "8eb7ad8f-5db5-4c28-819b-ca3905fffd80",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6f53bc92-ae54-44ce-bc4e-010d1f8cfda0",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6cb17888-ad6e-464c-82c0-d37fd1f2c4f8",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "a16fc4fd-1949-4e77-9de3-30369f16c3a5",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "6bacdb75-1889-4f93-8971-8c8995ff8960",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      },
      {
        "modelId": "be963f4c-4898-48d7-9eba-3c6af0867b9d",
        "details": {
          "statusId": 2,
          "status": "UpToDate",
          "exampleCount": 171
        }
      }
    ]
    

從預測端點取得意圖

使用 cURL 查詢 預測端點 並取得預測結果。

注意

此命令會使用您的預測端點。

  1. 將此指令複製到文字編輯器:

    curl "https://***YOUR-PREDICTION-ENDPOINT***/luis/prediction/v3.0/apps/***YOUR-APP-ID***/slots/production/predict" ^
          --request GET ^
          --get ^
          --data "subscription-key=***YOUR-PREDICTION-KEY***" ^
          --data "verbose=true" ^
          --data "show-all-intents=true" ^
          --data-urlencode "query=I want two large pepperoni pizzas on thin crust please"
    
  2. 使用您自己的值取代以 ***YOUR- 開頭的值。

    資訊 目的
    ***YOUR-PREDICTION-ENDPOINT*** 您的預測 URL 端點。 位於 LUIS 入口網站的 Azure 資源頁面,適用於您的應用程式。
    例如: https://westus.api.cognitive.microsoft.com/
    ***YOUR-APP-ID*** 您的應用程式識別碼。 位於 LUIS 入口網站的 [應用程式 設定] 頁面。
    ***YOUR-PREDICTION-KEY*** 您的 32 個字元預測索引鍵。 位於 LUIS 入口網站的 Azure 資源頁面,適用於您的應用程式。
  3. 將文字複製到主控台視窗,然後按 Enter 以執行命令:

  4. 檢閱預測回應,這會以 JSON 形式傳回:

    {"query":"I want two large pepperoni pizzas on thin crust please","prediction":{"topIntent":"ModifyOrder","intents":{"ModifyOrder":{"score":1.0},"None":{"score":8.55E-09},"Greetings":{"score":1.82222226E-09},"CancelOrder":{"score":1.47272727E-09},"Confirmation":{"score":9.8125E-10}},"entities":{"Order":[{"FullPizzaWithModifiers":[{"PizzaType":["pepperoni pizzas"],"Size":[["Large"]],"Quantity":[2],"Crust":[["Thin"]],"$instance":{"PizzaType":[{"type":"PizzaType","text":"pepperoni pizzas","startIndex":17,"length":16,"score":0.9978157,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Size":[{"type":"SizeList","text":"large","startIndex":11,"length":5,"score":0.9984481,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Quantity":[{"type":"builtin.number","text":"two","startIndex":7,"length":3,"score":0.999770939,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"Crust":[{"type":"CrustList","text":"thin crust","startIndex":37,"length":10,"score":0.933985531,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}]}}],"$instance":{"FullPizzaWithModifiers":[{"type":"FullPizzaWithModifiers","text":"two large pepperoni pizzas on thin crust","startIndex":7,"length":40,"score":0.90681237,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}]}}],"ToppingList":[["Pepperoni"]],"$instance":{"Order":[{"type":"Order","text":"two large pepperoni pizzas on thin crust","startIndex":7,"length":40,"score":0.9047088,"modelTypeId":1,"modelType":"Entity Extractor","recognitionSources":["model"]}],"ToppingList":[{"type":"ToppingList","text":"pepperoni","startIndex":17,"length":9,"modelTypeId":5,"modelType":"List Entity Extractor","recognitionSources":["model"]}]}}}}
    

    格式化為可讀性的 JSON 回應:

    {
      "query": "I want two large pepperoni pizzas on thin crust please",
      "prediction": {
        "topIntent": "ModifyOrder",
        "intents": {
          "ModifyOrder": {
            "score": 1.0
          },
          "None": {
            "score": 8.55e-9
          },
          "Greetings": {
            "score": 1.82222226e-9
          },
          "CancelOrder": {
            "score": 1.47272727e-9
          },
          "Confirmation": {
            "score": 9.8125e-10
          }
        },
        "entities": {
          "Order": [
            {
              "FullPizzaWithModifiers": [
                {
                  "PizzaType": [
                    "pepperoni pizzas"
                  ],
                  "Size": [
                    [
                      "Large"
                    ]
                  ],
                  "Quantity": [
                    2
                  ],
                  "Crust": [
                    [
                      "Thin"
                    ]
                  ],
                  "$instance": {
                    "PizzaType": [
                      {
                        "type": "PizzaType",
                        "text": "pepperoni pizzas",
                        "startIndex": 17,
                        "length": 16,
                        "score": 0.9978157,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Size": [
                      {
                        "type": "SizeList",
                        "text": "large",
                        "startIndex": 11,
                        "length": 5,
                        "score": 0.9984481,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Quantity": [
                      {
                        "type": "builtin.number",
                        "text": "two",
                        "startIndex": 7,
                        "length": 3,
                        "score": 0.999770939,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ],
                    "Crust": [
                      {
                        "type": "CrustList",
                        "text": "thin crust",
                        "startIndex": 37,
                        "length": 10,
                        "score": 0.933985531,
                        "modelTypeId": 1,
                        "modelType": "Entity Extractor",
                        "recognitionSources": [
                          "model"
                        ]
                      }
                    ]
                  }
                }
              ],
              "$instance": {
                "FullPizzaWithModifiers": [
                  {
                    "type": "FullPizzaWithModifiers",
                    "text": "two large pepperoni pizzas on thin crust",
                    "startIndex": 7,
                    "length": 40,
                    "score": 0.90681237,
                    "modelTypeId": 1,
                    "modelType": "Entity Extractor",
                    "recognitionSources": [
                      "model"
                    ]
                  }
                ]
              }
            }
          ],
          "ToppingList": [
            [
              "Pepperoni"
            ]
          ],
          "$instance": {
            "Order": [
              {
                "type": "Order",
                "text": "two large pepperoni pizzas on thin crust",
                "startIndex": 7,
                "length": 40,
                "score": 0.9047088,
                "modelTypeId": 1,
                "modelType": "Entity Extractor",
                "recognitionSources": [
                  "model"
                ]
              }
            ],
            "ToppingList": [
              {
                "type": "ToppingList",
                "text": "pepperoni",
                "startIndex": 17,
                "length": 9,
                "modelTypeId": 5,
                "modelType": "List Entity Extractor",
                "recognitionSources": [
                  "model"
                ]
              }
            ]
          }
        }
      }
    }
    

清除資源

您可以從 LUIS 入口網站刪除應用程式,並從 Azure 入口網站 刪除 Azure 資源

如果您使用 REST API,請在完成快速入門時,從檔案系統刪除 ExampleUtterances.JSON 檔案。

疑難排解

  • 向客戶端連結庫進行驗證 - 驗證錯誤通常表示使用了錯誤的金鑰和端點。 本快速入門會針對預測運行時間使用撰寫密鑰和端點作為便利性,但只有在您尚未使用每月配額時才能運作。 如果您無法使用撰寫金鑰和端點,您必須在存取預測運行時間 SDK 用戶端連結庫時使用預測執行時間金鑰和端點。
  • 建立實體 - 如果您在建立本教學課程中使用的巢狀機器學習實體時發生錯誤,請確定您已複製程式代碼,且未變更程式代碼以建立不同的實體。
  • 建立範例語句 - 如果您在建立本教學課程中使用的已加上標籤的範例語句時收到錯誤,請確定您已複製程式代碼,且未變更程式代碼以建立不同的標記範例。
  • 定型 - 如果您收到定型錯誤,這通常表示空的應用程式(沒有含範例語句的意圖),或意圖或實體格式不正確的應用程式。
  • 其他錯誤 - 因為程式代碼會使用文字和 JSON 物件呼叫用戶端連結庫,因此請確定您尚未變更程式代碼。

其他錯誤 - 如果您收到上述清單中未涵蓋的錯誤,請在此頁面上提供意見反應,讓我們知道。 包含您安裝之用戶端連結庫的程式設計語言和版本。

下一步