빠른 시작: LUIS(Language Understanding) 클라이언트 라이브러리 및 REST API

Important

LUIS는 2025년 10월 1일에 사용 중지되며 2023년 4월 1일부터 새 LUIS 리소스를 만들 수 없습니다. 지속적인 제품 지원 및 다국어 기능을 활용하려면 LUIS 애플리케이션대화 언어 이해로 마이그레이션하는 것이 좋습니다.

C#, Python 또는 JavaScript를 통해 이 빠른 시작을 사용하여 LUIS SDK 클라이언트 라이브러리로 Azure LUIS AI(인공 지능) 앱을 만들고 쿼리합니다. 또한 cURL을 사용하여 REST API를 통해 요청을 보낼 수 있습니다.

LUIS(Language Understanding)를 사용하면 사용자의 대화형 자연어 텍스트에 NLP(자연어 처리)를 적용하여 전반적인 의미를 예측하고 관련된 세부 정보를 끌어올 수 있습니다.

  • 작성 클라이언트 라이브러리 및 REST API를 사용하면 LUIS 앱을 생성, 편집, 학습 및 게시할 수 있습니다.
  • 예측 런타임 클라이언트 라이브러리 및 REST API를 사용하면 게시된 앱을 쿼리할 수 있습니다.

.NET용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 앱 만들기
  • 예제 발화를 사용하여 기계 학습된 엔터티인 의도 추가
  • 앱 학습 및 게시
  • 예측 런타임 쿼리

참조 설명서 | 작성예측 라이브러리 소스 코드 | 작성예측 NuGet | C# 샘플

필수 조건

  • 최신 버전의 .NET Core.NET Core CLI.
  • Azure 구독 - 체험 구독 만들기
  • Azure 구독을 보유한 후에는 Azure Portal에서 언어 이해 작성 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포될 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 언어 이해 작성에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다. 무료 가격 책정 계층(F0)을 사용하여 서비스를 시도할 수 있습니다.

설정

새 C# 애플리케이션 만들기

선호하는 편집기 또는 IDE에서 .NET Core 애플리케이션을 새로 만듭니다.

  1. 콘솔 창(예: cmd, PowerShell 또는 Bash)에서 dotnet new 명령을 사용하여 language-understanding-quickstart라는 새 콘솔 앱을 만듭니다. 이 명령은 Program.cs라는 단일 소스 파일을 사용하여 간단한 "Hello World" C# 프로젝트를 만듭니다.

    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용 LUIS(Language Understanding) 클라이언트 라이브러리를 설치합니다.

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

개체 모델 제작

LUIS(Language Understanding) 작성 클라이언트는 Azure를 인증하는 LUISAuthoringClient 개체이며, 이 개체에는 작성 키가 포함되어 있습니다.

작성에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

예측 개체 모델

LUIS(Language Understanding) 예측 런타임 클라이언트는 Azure를 인증하는 LUISRuntimeClient 개체이며, 리소스 키를 포함합니다.

예측 런타임에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

코드 예제

이러한 코드 조각은 Python용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행하는 방법을 보여줍니다.

종속성 추가

선호하는 편집기 또는 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. 달리 지정하지 않는 한 Program 클래스의 Main 메서드에 나머지 코드를 추가합니다.

앱에 대한 변수 만들기

두 개의 변수 세트를 만듭니다. 첫 번째 집합은 변경하고 두 번째 집합은 코드 샘플에 표시된 그대로 둡니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 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 메서드를 호출합니다. 응답은 앱 ID입니다.

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

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

앱용 의도 만들기

LUIS 앱 모델의 기본 개체는 의도입니다. 의도는 사용자 발화 의도의 그룹화를 통해 정렬됩니다. 사용자는 봇(또는 다른 클라이언트 애플리케이션)에서 의도된 특정 응답을 찾는 질문을 하거나 명령문을 만들 수 있습니다. 의도의 예로 항공편 예약, 목적지 도시의 날씨 요청 및 고객 서비스에 대한 연락처 정보 요청이 있습니다.

고유한 의도 이름을 사용하여 ModelCreateObject를 만든 다음, 앱 ID, 버전 ID 및 ModelCreateObject를 Model.AddIntentAsync 메서드에 전달합니다. 응답은 의도 ID입니다.

intentName 값은 앱에 대한 변수 만들기 섹션에 있는 변수의 일부로 OrderPizzaIntent에 하드 코딩됩니다.

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

앱용 엔터티 만들기

엔터티는 필수는 아니지만 대부분의 앱에서 찾을 수 있습니다. 엔터티는 사용자의 의도를 채우는 데 필요한 정보를 사용자 발화에서 추출합니다. 미리 작성된 엔터티 및 사용자 지정 엔터티의 여러 형식이 있으며, 각 엔터티는 고유한 DTO(데이터 변환 개체) 모델을 사용합니다. 앱에 추가할 수 있는 일반적인 미리 작성된 엔터티에는 number, datetimeV2, geographyV2, ordinal이 있습니다.

엔터티는 의도에 표시되지 않는다는 것을 알고 있어야 합니다. 대부분의 의도에 적용할 수 있고 일반적으로 적용하고 있습니다. 사용자 발화 예제만 특정 단일 의도에 대해 표시됩니다.

엔터티를 만드는 메서드는 Model 클래스의 일부입니다. 각 엔터티 형식에는 자체의 고유한 DTO(데이터 변환 개체) 모델이 있으며, 일반적으로 Models 네임스페이스에서 model 단어가 포함됩니다.

엔터티 생성 코드는 하위 엔터티 및 Quantity 하위 엔터티에 적용되는 기능을 사용하여 기계 학습 엔터티를 만듭니다.

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

// 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 하위 엔터티의 ID를 찾습니다.

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 개체의 목록을 만들어 발화 예제를 추가합니다. 각 예제는 엔터티 이름과 엔터티 값의 이름/값 쌍으로 구성된 사전을 통해 모든 엔터티를 표시해야 합니다. 엔터티 값은 발화 예제의 텍스트에 표시된 것과 정확히 일치해야 합니다.

Partial screenshot showing the labeled example utterance in the portal.

앱 ID, 버전 ID 및 예제를 사용하여 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 메서드에는 앱 ID와 버전 ID가 필요합니다.

이 빠른 시작에서 보여 주는 것과 같은 매우 작은 모델은 매우 빠르게 학습됩니다. 프로덕션 수준 애플리케이션의 경우 앱을 학습시키려면 학습이 성공했는지 여부를 확인하기 위해 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 메서드는 요청을 처리할 여러 매개 변수(예: app ID, slot name, prediction request 개체)가 필요합니다. verbose, show all intents, log와 같은 다른 옵션은 선택 사항입니다.

// 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

Node.js용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 앱 만들기
  • 예제 발화를 사용하여 기계 학습된 엔터티인 의도 추가
  • 앱 학습 및 게시
  • 예측 런타임 쿼리

참조 설명서 | 작성예측 NPM | 샘플

필수 조건

  • Node.JS
  • Azure 구독 - 체험 구독 만들기
  • Azure 구독을 보유한 후에는 Azure Portal에서 언어 이해 작성 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포될 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 언어 이해 작성에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다. 무료 가격 책정 계층(F0)을 사용하여 서비스를 시도할 수 있습니다.

설정

새 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"
  }
}

개체 모델 제작

LUIS(Language Understanding) 작성 클라이언트는 Azure를 인증하는 LUISAuthoringClient 개체이며, 이 개체에는 작성 키가 포함되어 있습니다.

작성에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

예측 개체 모델

LUIS(Language Understanding) 작성 클라이언트는 Azure를 인증하는 LUISAuthoringClient 개체이며, 이 개체에는 작성 키가 포함되어 있습니다.

예측 런타임에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

코드 예제

이러한 코드 조각은 Python용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행하는 방법을 보여줍니다.

종속성 추가

원하는 편집기 또는 IDE에서 index.js 파일을 열고 다음 종속성을 추가합니다.

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. 별도로 지정하지 않는 한 나머지 코드를 빠른 시작 메서드에 추가합니다.

앱에 대한 변수 만들기

두 개의 변수 세트를 만듭니다. 첫 번째 집합은 변경하고 두 번째 집합은 코드 샘플에 표시된 그대로 둡니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 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 앱 모델의 기본 개체는 의도입니다. 의도는 사용자 발화 의도의 그룹화를 통해 정렬됩니다. 사용자는 봇(또는 다른 클라이언트 애플리케이션)에서 의도된 특정 응답을 찾는 질문을 하거나 명령문을 만들 수 있습니다. 의도의 예로 항공편 예약, 목적지 도시의 날씨 요청 및 고객 서비스에 대한 연락처 정보 요청이 있습니다.

고유한 의도의 이름과 함께 model.add_intent 메서드를 사용한 다음, 앱 ID, 버전 ID 및 새 의도 이름을 전달합니다.

intentName 값은 앱에 대한 변수 만들기 섹션에 있는 변수의 일부로 OrderPizzaIntent에 하드 코딩됩니다.

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

앱용 엔터티 만들기

엔터티는 필수는 아니지만 대부분의 앱에서 찾을 수 있습니다. 엔터티는 사용자의 의도를 채우는 데 필요한 정보를 사용자 발화에서 추출합니다. 미리 작성된 엔터티 및 사용자 지정 엔터티의 여러 형식이 있으며, 각 엔터티는 고유한 DTO(데이터 변환 개체) 모델을 사용합니다. 앱에 추가할 수 있는 일반적인 미리 작성된 엔터티에는 number, datetimeV2, geographyV2, ordinal이 있습니다.

엔터티는 의도에 표시되지 않는다는 것을 알고 있어야 합니다. 대부분의 의도에 적용할 수 있고 일반적으로 적용하고 있습니다. 사용자 발화 예제만 특정 단일 의도에 대해 표시됩니다.

엔터티를 만드는 메서드는 Model 클래스의 일부입니다. 각 엔터티 형식마다 자체적인 DTO(데이터 변환 개체) 모델이 있습니다.

엔터티 생성 코드는 하위 엔터티 및 Quantity 하위 엔터티에 적용되는 기능을 사용하여 기계 학습 엔터티를 만듭니다.

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

// 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 하위 엔터티의 ID를 찾습니다.

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

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

}

의도에 발화 예제 추가

발화의 의도를 파악하고 엔터티를 추출하기 위해 앱에는 발화 예제가 필요합니다. 이러한 예제는 특정 단일 의도를 대상으로 해야 하며, 모든 사용자 지정 엔터티를 표시해야 합니다. 미리 작성된 엔터티는 표시할 필요가 없습니다.

각 발화 예제에 대한 하나의 개체인 ExampleLabelObject 개체의 목록을 만들어 발화 예제를 추가합니다. 각 예제는 엔터티 이름과 엔터티 값의 이름/값 쌍으로 구성된 사전을 통해 모든 엔터티를 표시해야 합니다. 엔터티 값은 발화 예제의 텍스트에 표시된 것과 정확히 일치해야 합니다.

Partial screenshot showing the labeled example utterance in the portal.

앱 ID, 버전 ID 및 예제를 사용하여 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 메서드에는 앱 ID와 버전 ID가 필요합니다.

이 빠른 시작에서 보여 주는 것과 같은 매우 작은 모델은 매우 빠르게 학습됩니다. 프로덕션 수준 애플리케이션의 경우 앱을 학습시키려면 학습이 성공했는지 여부와 성공한 시기를 확인하는 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 메서드는 요청을 처리할 여러 매개 변수(예: 앱 ID, 슬롯 이름 및 예측 요청 개체)가 필요합니다. verbose, show all intents, log와 같은 다른 옵션은 선택 사항입니다.

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

애플리케이션 실행

quickstart 파일의 node index.js 명령을 사용하여 애플리케이션을 실행합니다.

node index.js

Python용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 앱 만들기
  • 예제 발화를 사용하여 기계 학습된 엔터티인 의도 추가
  • 앱 학습 및 게시
  • 예측 런타임 쿼리

참조 설명서 | 작성예측 라이브러리 소스 코드 | 패키지(Pypi) | 샘플

필수 조건

  • Python 3.x의 현재 버전입니다.
  • Azure 구독 - 체험 구독 만들기
  • Azure 구독을 보유한 후에는 Azure Portal에서 언어 이해 작성 리소스를 만들어 키와 엔드포인트를 가져옵니다. 배포될 때까지 기다렸다가 리소스로 이동 단추를 클릭합니다.
    • 애플리케이션을 언어 이해 작성에 연결하려면 만든 리소스의 키와 엔드포인트가 필요합니다. 이 빠른 시작의 뒷부분에 나오는 코드에 키와 엔드포인트를 붙여넣습니다. 무료 가격 책정 계층(F0)을 사용하여 서비스를 시도할 수 있습니다.

설정

새 Python 애플리케이션 만들기

  1. 콘솔 창에서 애플리케이션에 대한 새 디렉터리를 만들고 해당 디렉터리로 이동합니다.

    mkdir quickstart-sdk && cd quickstart-sdk
    
  2. Python 코드용으로 authoring_and_predict.py라는 파일을 만듭니다.

    touch authoring_and_predict.py
    

Pip을 사용하여 클라이언트 라이브러리 설치

애플리케이션 디렉터리 내에서 다음 명령을 사용하여 Python용 LUIS(Language Understanding) 클라이언트 라이브러리를 설치합니다.

pip install azure-cognitiveservices-language-luis

개체 모델 제작

LUIS(Language Understanding) 작성 클라이언트는 Azure를 인증하는 LUISAuthoringClient 개체이며, 이 개체에는 작성 키가 포함되어 있습니다.

작성에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

예측 개체 모델

LUIS(Language Understanding) 예측 런타임 클라이언트는 Azure를 인증하는 LUISRuntimeClient 개체이며, 리소스 키를 포함합니다.

예측 런타임에 대한 코드 예제

클라이언트가 만들어지면 이 클라이언트를 사용하여 다음과 같은 기능에 액세스합니다.

코드 예제

이러한 코드 조각은 Python용 LUIS(Language Understanding) 클라이언트 라이브러리를 사용하여 다음을 수행하는 방법을 보여줍니다.

종속성 추가

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. 별도로 지정하지 않는 한 나머지 코드를 빠른 시작 메서드에 추가합니다.

앱에 대한 변수 만들기

두 개의 변수 세트를 만듭니다. 첫 번째 집합은 변경하고 두 번째 집합은 코드 샘플에 표시된 그대로 둡니다.

Important

완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 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 앱 모델의 기본 개체는 의도입니다. 의도는 사용자 발화 의도의 그룹화를 통해 정렬됩니다. 사용자는 봇(또는 다른 클라이언트 애플리케이션)에서 의도된 특정 응답을 찾는 질문을 하거나 명령문을 만들 수 있습니다. 의도의 예로 항공편 예약, 목적지 도시의 날씨 요청 및 고객 서비스에 대한 연락처 정보 요청이 있습니다.

고유한 의도의 이름과 함께 model.add_intent 메서드를 사용한 다음, 앱 ID, 버전 ID 및 새 의도 이름을 전달합니다.

intentName 값은 앱에 대한 변수 만들기 섹션에 있는 변수의 일부로 OrderPizzaIntent에 하드 코딩됩니다.

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

앱용 엔터티 만들기

엔터티는 필수는 아니지만 대부분의 앱에서 찾을 수 있습니다. 엔터티는 사용자의 의도를 채우는 데 필요한 정보를 사용자 발화에서 추출합니다. 미리 작성된 엔터티 및 사용자 지정 엔터티의 여러 형식이 있으며, 각 엔터티는 고유한 DTO(데이터 변환 개체) 모델을 사용합니다. 앱에 추가할 수 있는 일반적인 미리 작성된 엔터티에는 number, datetimeV2, geographyV2, ordinal이 있습니다.

엔터티는 의도에 표시되지 않는다는 것을 알고 있어야 합니다. 대부분의 의도에 적용할 수 있고 일반적으로 적용하고 있습니다. 사용자 발화 예제만 특정 단일 의도에 대해 표시됩니다.

엔터티를 만드는 메서드는 ModelOperations 클래스의 일부입니다. 각 엔터티 형식마다 자체적인 DTO(데이터 변환 개체) 모델이 있습니다.

엔터티 생성 코드는 하위 엔터티 및 Quantity 하위 엔터티에 적용되는 기능을 사용하여 기계 학습 엔터티를 만듭니다.

Partial screenshot from portal showing the entity created, a machine-learning entity with subentities and features applied to the `Quantity` subentities.

# 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 하위 엔터티의 ID를 찾습니다.

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 개체의 목록을 만들어 발화 예제를 추가합니다. 각 예제는 엔터티 이름과 엔터티 값의 이름/값 쌍으로 구성된 사전을 통해 모든 엔터티를 표시해야 합니다. 엔터티 값은 발화 예제의 텍스트에 표시된 것과 정확히 일치해야 합니다.

Partial screenshot showing the labeled example utterance in the portal.

앱 ID, 버전 ID 및 예제를 사용하여 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 메서드에는 앱 ID와 버전 ID가 필요합니다.

이 빠른 시작에서 보여 주는 것과 같은 매우 작은 모델은 매우 빠르게 학습됩니다. 프로덕션 수준 애플리케이션의 경우 앱을 학습시키려면 학습이 성공했는지 여부와 성공한 시기를 확인하는 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 메서드는 요청을 처리할 여러 매개 변수(예: 앱 ID, 슬롯 이름 및 예측 요청 개체)가 필요합니다. verbose, show all intents, log와 같은 다른 옵션은 선택 사항입니다. 요청은 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"
                        ]
                    }
                ]
            }
        }
    }
}

애플리케이션 실행

quickstart 파일의 python 명령을 사용하여 애플리케이션을 실행합니다.

python authoring_and_predict.py

이 빠른 시작에서는 세 개의 REST 호출을 순서대로 수행합니다.

참조 설명서

필수 조건

  • LUIS 체험 계정

  • Visual Studio Code와 같은 텍스트 편집기

  • 명령줄 프로그램 cURL. cURL 프로그램은 macOS, 대부분의 Linux 배포판 및 Windows 10 빌드 1803 이상에 이미 설치되어 있습니다.

    cURL을 설치해야 하는 경우 cURL 다운로드 페이지에서 cURL을 다운로드할 수 있습니다.

Pizza 앱 만들기

Pizza 앱 만들기

  1. pizza-app-for-luis-v6.json을 선택하여 pizza-app-for-luis.json 파일에 대한 GitHub 페이지를 엽니다.
  2. Raw 단추를 마우스 오른쪽 단추로 클릭하거나 길게 누르고 다른 이름으로 링크 저장을 선택하여 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 웹 사이트의 오른쪽 위에서 학습 단추를 선택합니다.

    Train button

  2. 학습 단추가 사용하지 않도록 설정되어 있으면 학습이 완료된 것입니다.

챗봇 또는 다른 클라이언트 애플리케이션에서 LUIS 예측을 받으려면 앱을 예측 엔드포인트에 게시해야 합니다.

  1. 오른쪽 위 탐색에서 게시를 선택합니다.

    A screenshot of the button for publishing to the endpoint.

  2. 프로덕션 슬롯을 선택한 다음, 완료를 선택합니다.

    A screenshot of LUIS publishing to the endpoint.

  3. 알림에서 엔드포인트 URL에 액세스를 선택하여 Azure 리소스 페이지로 이동합니다. 앱과 연결된 예측 리소스가 있는 경우에만 URL을 볼 수 있습니다. 관리를 클릭하여 Azure 리소스 페이지를 찾을 수도 있습니다.

    A screenshot of a message showing the app has been published.

Pizza 앱에 제작 리소스 추가

  1. 관리를 선택합니다.
  2. Azure 리소스를 선택합니다.
  3. 제작 리소스를 선택합니다.
  4. 제작 리소스 변경을 선택합니다.

제작 리소스가 있는 경우 제작 리소스의 테넌트 이름, 구독 이름LUIS 리소스 이름을 입력합니다.

제작 리소스가 없는 경우

  1. 새 리소스 만들기를 선택합니다.
  2. 테넌트 이름, 리소스 이름, 구독 이름Azure 리소스 그룹 이름을 입력합니다.

이제 Pizza 앱을 사용할 준비가 되었습니다.

피자 앱에 대한 액세스 값 기록

새 Pizza 앱을 사용하려면 Pizza 앱의 앱 ID, 제작 키 및 제작 엔드포인트가 필요합니다. 예측을 가져오려면 별도의 예측 엔드포인트와 예측 키가 필요합니다.

이러한 값을 찾으려면 다음을 수행합니다.

  1. 의도 페이지에서 관리를 선택합니다.
  2. 애플리케이션 설정 페이지에서 앱 ID를 기록합니다.
  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 필드에 언급된 엔터티를 표시해야 합니다. 인덱스는 0부터 시작합니다. 텍스트의 공간에서 레이블을 시작하거나 종료하는 경우 발화를 추가하기 위한 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 앱 ID입니다.
    ***YOUR-APP-VERSION*** LUIS 앱 버전입니다. 피자 앱의 경우 버전 번호는 따옴표 없이 "0.1"입니다.
    ***YOUR-AUTHORING-KEY*** 32자 작성 키입니다.

    할당된 키와 리소스는 Azure Resources 페이지의 관리 섹션에 있는 LUIS 포털에 표시됩니다. 앱 ID는 애플리케이션 설정 페이지의 동일한 관리 섹션에서 사용할 수 있습니다.

    Important

    완료되면 코드에서 키를 제거하고 공개적으로 게시하지 마세요. 프로덕션의 경우 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 Resources 설정 페이지에 있습니다.
    예: https://westus.api.cognitive.microsoft.com/.
    ***YOUR-APP-ID*** 앱 ID. LUIS 포털, 앱의 애플리케이션 설정 페이지에 있습니다.
    ***YOUR-PREDICTION-KEY*** 32자 예측 키입니다. LUIS 포털, 앱의 Azure Resources 설정 페이지에 있습니다.
  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 Portal에서 Azure 리소스를 삭제할 수 있습니다.

REST API를 사용 중인 경우 빠른 시작을 완료한 후 파일 시스템에서 ExampleUtterances.JSON 파일을 삭제합니다.

문제 해결

  • 클라이언트 라이브러리에 대한 인증 - 인증 오류는 일반적으로 잘못된 키 및 엔드포인트가 사용되었음을 나타냅니다. 이 빠른 시작은 편의상 예측 런타임에 작성 키와 엔드포인트를 사용하지만 월별 할당량을 아직 사용하지 않은 경우에만 작동합니다. 작성 키와 엔드포인트를 사용할 수 없는 경우 예측 런타임 SDK 클라이언트 라이브러리에 액세스할 때 예측 런타임 키와 엔드포인트를 사용해야 합니다.
  • 엔터티 만들기 - 이 자습서에 사용되는 중첩된 기계 학습 엔터티를 만드는 동안 오류가 발생하면 코드를 복사하고 다른 엔터티를 만들기 위해 코드를 변경하지 않았는지 확인합니다.
  • 예제 발화 만들기 - 이 자습서에 사용되는 레이블이 지정된 예제 발화를 만드는 동안 오류가 발생하면 코드를 복사하고 다른 레이블이 지정된 예제를 만들기 위해 코드를 변경하지 않았는지 확인합니다.
  • 학습 - 학습 오류가 발생하는 경우 이는 일반적으로 빈 앱(예: 예제 발화가 있는 의도 없음) 또는 형식이 잘못된 의도 또는 엔터티가 포함된 앱을 나타냅니다.
  • 기타 오류 - 코드가 텍스트 및 JSON 개체를 사용하여 클라이언트 라이브러리를 호출하므로 코드를 변경하지 않았는지 확인합니다.

기타 오류 - 이전 목록에서 다루지 않은 오류가 발생하면 이 페이지의 하단에 피드백을 제공하여 알려주세요. 설치한 클라이언트 라이브러리의 프로그래밍 언어와 버전을 포함합니다.

다음 단계