Beispiel #1
0
    async def construct(  # type: ignore
            self,
            _global_config: GlobalConfig,
            endpoint: str,
            authoring_key: str,
            *args,
            runtime_key: Optional[str] = None,
            **kwargs) -> None:
        """
        Args:
            _global_config: Global configuration for the whole test framework.
            endpoint: The endpoint to use to access LUIS, e.g.
                `https://westeurope.api.cognitive.microsoft.com/`.
            authoring_key: The access key for the LUIS authoring API.
            runtime_key: The access key for the LUIS runtime API. Defaults to the authoring key if
                omitted or set to :obj:`None`.
        """

        await super().construct(*args, **kwargs)

        self.__authoring_client = LUISAuthoringClient(
            endpoint, CognitiveServicesCredentials(authoring_key))

        self.__runtime_client = LUISRuntimeClient(
            endpoint,
            CognitiveServicesCredentials(
                authoring_key if runtime_key is None else runtime_key))
Beispiel #2
0
def predict():
    authoringKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    authoringEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    predictionKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    predictionEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    
    appName = "Luis Demo v20"
    versionId = "0.1"
    client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))
    app_id = '5eab7501-e61b-4b51-8831-d9f7657ee00f'
    
    responseEndpointInfo = client.apps.publish(app_id, versionId, is_staging=False)
    
    runtimeCredentials = CognitiveServicesCredentials(predictionKey)
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)

	#Alternative Usage of Saved Model
	# joblib.dump(clf, 'NB_spam_model.pkl')
	# NB_spam_model = open('NB_spam_model.pkl','rb')
	# clf = joblib.load(NB_spam_model)

    if request.method == 'POST':
        message = request.form['message']
        my_prediction = clientRuntime.prediction.get_slot_prediction(app_id, "Production", {"query":message}).prediction.top_intent
        my_prediction = my_prediction.replace("_"," ")
        my_prediction = my_prediction.capitalize()
    return render_template('result.html',prediction = my_prediction)
Beispiel #3
0
def getLuisAuthoringClient(authoringEndpoint, authoringKey):
    try:
        client = LUISAuthoringClient(
            authoringEndpoint, CognitiveServicesCredentials(authoringKey))
        return True, client
    except Exception as err:
        print("Error getting LUIS Authoring Client. {}".format(err))
    return False
Beispiel #4
0
 def __init__(self, config):
     super(LUISNLU, self).__init__(config)
     self.base_url = config['luis_base_url']
     self.subkey = config['luis_subkey']
     self.app_id = config['luis_app_id']
     self.app_version = config['luis_app_version']
     self.runtime_client = LUISRuntimeClient(self.base_url, CognitiveServicesCredentials(self.subkey))
     self.authoring_client = LUISAuthoringClient(self.base_url, CognitiveServicesCredentials(self.subkey))
Beispiel #5
0
 def publish(self):
     endpoint = f'https://{ self.credential.app_region }.api.cognitive.microsoft.com'
     client = LUISAuthoringClient(
         endpoint, CognitiveServicesCredentials(self.credential.app_key))
     client.train.train_version(self.credential.app_id,
                                self.credential.app_version)
     client.apps.publish(self.credential.app_id,
                         self.credential.app_version,
                         is_staging=True)
    def set_luis(self):
        self.owner = self.uobject.get_owner()
        self.authoringKey = self.owner.get_property('AuthoringKey')
        self.authoringEndpoint = self.owner.get_property('AuthoringEndpoint')
        self.predictionKey = self.owner.get_property('PredictionKey')
        self.predictionEndpoint = self.owner.get_property('PredictionEndpoint')
        self.app_id = self.owner.get_property('AppId')

        enumLanguage = self.owner.get_property('TargetLanguage')
        self.target_language = self.owner.call_function('GetStringEnumLanguage', enumLanguage)

        self.client = LUISAuthoringClient(self.authoringEndpoint, CognitiveServicesCredentials(self.authoringKey))
Beispiel #7
0
    def update(self):
        endpoint = f'https://{ self.credential.app_region }.api.cognitive.microsoft.com'
        client = LUISAuthoringClient(
            endpoint, CognitiveServicesCredentials(self.credential.app_key))
        utterance = None

        if self.labels is not None and self.values is not None:
            utterance = self.create_utterance(self.create_labels())
        else:
            labels = ()
            utterance = self.create_utterance(labels)

        client.examples.batch(self.credential.app_id,
                              self.credential.app_version, [utterance])
        time.sleep(5)
Beispiel #8
0
def initiateConnection():
    """
    This Function reads the ConfigurationInput.Ini file to create a connection with the Remote Luis platform.
    To get Details click on the NameInitials on the right top corner of the screen and
    :return: Client ID
    """
    configurationInput = "ConfigurationInput.ini"
    if not os.path.exists(configurationInput):
        exit("The {} file is missing which holds the Login details".format(
            configurationInput))
        pass
    config = configparser.ConfigParser()
    config.read(configurationInput)
    if 'Luis Bot' not in config.sections():
        exit("The config file does not have a 'Luis Bot' section")
        pass
    endpoint = config.get('Luis Bot', 'Endpoint_URL')
    authoring_key = config.get('Luis Bot', 'Primary_Key')
    return LUISAuthoringClient(endpoint,
                               CognitiveServicesCredentials(authoring_key))
def quickstart():

    authoringKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    authoringEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'
    predictionKey = '20dc03f3f35e418b9c38bb1553ad8b24'
    predictionEndpoint = 'https://jemdemo5.cognitiveservices.azure.com/'

    appName = "Luis Demo v"
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    intentName2 = "OrderTaxiIntent"

    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))

    # define app basics
    appDefinition = {
        "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))

    # read training data
    with open('Intentsubset1.csv', 'r') as fd:
        reader = csv.DictReader(fd)
        labeledExampleUtteranceWithMLEntity = list(reader)


# Get unique intents
    all_intents = []
    for x in labeledExampleUtteranceWithMLEntity:
        all_intents.append(x['intentName'])
    unique_intents = list(set(all_intents))

    for x in unique_intents:
        client.model.add_intent(app_id, versionId, x)

    # Define labeled example

    print("Labeled Example Utterance:",
          labeledExampleUtteranceWithMLEntity[2:4])
    print(len(labeledExampleUtteranceWithMLEntity))
    df = pd.DataFrame(labeledExampleUtteranceWithMLEntity)
    X = df['text']
    Y = df['intentName']
    X_train, X_test, Y_train, Y_test = train_test_split(X,
                                                        Y,
                                                        test_size=0.3,
                                                        random_state=42,
                                                        stratify=Y)
    print('finished split')
    # 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
    chunks = (len(X_train) - 1) // 50 + 1
    Train_df = pd.concat([X_train, Y_train], axis=1, join="inner")
    Train_dict = Train_df.to_dict('records')
    print(len(Train_df))
    for i in range(chunks):
        client.examples.batch(app_id, versionId,
                              Train_dict[i * 50:(i + 1) * 50],
                              {"enableNestedChildren": True})

    print('added examples')
    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

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

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

    # Production == slot name
    predictionRequest = {"query": "I forgot my password"}

    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))
def quickstart(): 

	# <VariablesYouChange>
	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'
	# </VariablesYouChange>

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

	# <AuthoringCreateClient>
	client = LUISAuthoringClient(authoringEndpoint, CognitiveServicesCredentials(authoringKey))
	# </AuthoringCreateClient>

	# Create app
	app_id = create_app(client, appName, versionId)

	# <AddIntent>
	client.model.add_intent(app_id, versionId, intentName)
	# </AddIntent>
	
	# Add Entities
	add_entities(client, app_id, versionId)
	
	# Add labeled examples
	add_labeled_examples(client,app_id, versionId, intentName)

	# <TrainAppVersion>
	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
	# </TrainAppVersion>
	
	# <PublishVersion>
	# 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)
	# </PublishVersion>
	
	# <PredictionCreateClient>
	runtimeCredentials = CognitiveServicesCredentials(predictionKey)
	clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint, credentials=runtimeCredentials)
	# </PredictionCreateClient>

    # <QueryPredictionEndpoint>
    # 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))
    # </QueryPredictionEndpoint>

	# Clean up resources.
	print ("Deleting app...")
	client.apps.delete(app_id)
	print ("App deleted.")
Beispiel #11
0
# <Dependencies>
from azure.cognitiveservices.language.luis.authoring import LUISAuthoringClient
from msrest.authentication import CognitiveServicesCredentials

import datetime, json, os, time
# </Dependencies>

# <AuthorizationVariables>
authoring_key = 'REPLACE-WITH-YOUR-ASSIGNED-AUTHORING-KEY'

authoring_endpoint = "https://REPLACE-WITH-RESOURCE-NAME.cognitiveservices.azure.com/"
# </AuthorizationVariables>

# <Client>
# Instantiate a LUIS client
client = LUISAuthoringClient(authoring_endpoint,
                             CognitiveServicesCredentials(authoring_key))

# </Client>


# <createApp>
def create_app():
    # Create a new LUIS app
    app_name = "Contoso {}".format(datetime.datetime.now())
    app_desc = "Flight booking app built with LUIS Python SDK."
    app_version = "0.1"
    app_locale = "en-us"

    app_id = client.apps.add(
        dict(name=app_name,
             initial_version_id=app_version,
def quickstart():

    # <VariablesYouChange>
    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'
    # </VariablesYouChange>

    # <VariablesYouDontNeedToChangeChange>
    appName = "Contoso Pizza Company"
    versionId = "0.1"
    intentName = "OrderPizzaIntent"
    # </VariablesYouDontNeedToChangeChange>

    # <AuthoringCreateClient>
    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))
    # </AuthoringCreateClient>

    # Create app
    app_id = create_app(client, appName, versionId)

    # <AddIntent>
    client.model.add_intent(app_id, versionId, intentName)
    # </AddIntent>

    # Add Entities
    add_entities(client, app_id, versionId)

    # Add labeled examples
    add_labeled_examples(client, app_id, versionId, intentName)

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

    # <PublishVersion>
    responseEndpointInfo = client.apps.publish(app_id,
                                               versionId,
                                               is_staging=False)
    # </PublishVersion>

    # <PredictionCreateClient>
    runtimeCredentials = CognitiveServicesCredentials(predictionKey)
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                      credentials=runtimeCredentials)
    # </PredictionCreateClient>

    # <QueryPredictionEndpoint>
    # 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))
def management(subscription_key):
    """Managing

    This will show how to manage your LUIS applications.
    """
    client = LUISAuthoringClient(
        'https://westus.api.cognitive.microsoft.com',
        CognitiveServicesCredentials(subscription_key),
    )

    try:
        # Create a LUIS app
        default_app_name = "Contoso-{}".format(datetime.datetime.now())
        version_id = "0.1"

        print("Creating App {}, version {}".format(default_app_name,
                                                   version_id))

        app_id = client.apps.add({
            'name': default_app_name,
            'initial_version_id': version_id,
            'description': "New App created with LUIS Python sample",
            'culture': 'en-us',
        })
        print("Created app {}".format(app_id))

        # Listing app
        print("\nList all apps")
        for app in client.apps.list():
            print("\t->App: '{}'".format(app.name))

        # Cloning a version
        print("\nCloning version 0.1 into 0.2")
        client.versions.clone(
            app_id,
            "0.1",  # Source
            "0.2"  # New version name
        )
        print("Your app version has been cloned.")

        # Export the version
        print("\nExport version 0.2 as JSON")
        luis_app = client.versions.export(app_id, "0.2")
        luis_app_as_json = json.dumps(luis_app.serialize())
        # You can now save this JSON string as a file

        # Import the version
        print("\nImport previously exported version as 0.3")
        luis_app
        client.versions.import_method(app_id, json.loads(luis_app_as_json),
                                      "0.3")

        # Listing versions
        print("\nList all versions in this app")
        for version in client.versions.list(app_id):
            print("\t->Version: '{}', training status: {}".format(
                version.version, version.training_status))

        # Print app details
        print("\nPrint app '{}' details".format(default_app_name))
        details = client.apps.get(app_id)
        # as_dict "dictify" the object, by default it's attribute based. e.g. details.name
        pprint(details.as_dict())

        # Print version details
        print("\nPrint version '{}' details".format(version_id))
        details = client.versions.get(app_id, version_id)
        # as_dict "dictify" the object, by default it's attribute based. e.g. details.name
        pprint(details.as_dict())

        # Delete an app
        print("\nDelete app '{}'".format(default_app_name))
        client.apps.delete(app_id)
        print("App deleted!")

    except Exception as err:
        print("Encountered exception. {}".format(err))
def booking_app(subscription_kuy):
    """Authoring.

    This will create a LUIS Booking application, train and publish it.
    """
    client = LUISAuthoringClient(
        'https://westus.api.cognitive.microsoft.com',
        CognitiveServicesCredentials(subscription_key),
    )

    try:
        # Create a LUIS app
        default_app_name = "Contoso-{}".format(datetime.datetime.now())
        version_id = "0.1"

        print("Creating App {}, version {}".format(default_app_name,
                                                   version_id))

        app_id = client.apps.add({
            'name': default_app_name,
            'initial_version_id': version_id,
            'description': "New App created with LUIS Python sample",
            'culture': 'en-us',
        })
        print("Created app {}".format(app_id))

        # Add information into the model

        print("\nWe'll create two new entities.")
        print(
            "The \"Destination\" simple entity will hold the flight destination."
        )
        print(
            "The \"Class\" hierarchical entity will accept \"First\", \"Business\" and \"Economy\" values."
        )

        destination_name = "Destination"
        destination_id = client.model.add_entity(app_id, version_id,
                                                 destination_name)
        print("{} simple entity created with id {}".format(
            destination_name, destination_id))

        class_name = "Class"
        class_id = client.model.add_hierarchical_entity(
            app_id,
            version_id,
            name=class_name,
            children=["First", "Business", "Economy"])
        print("{} hierarchical entity created with id {}".format(
            class_name, class_id))

        print(
            "\nWe'll now create the \"Flight\" composite entity including \"Class\" and \"Destination\"."
        )

        flight_name = "Flight"
        flight_id = client.model.add_composite_entity(
            app_id,
            version_id,
            name=flight_name,
            children=[class_name, destination_name])
        print("{} composite entity created with id {}".format(
            flight_name, flight_id))

        find_economy_to_madrid = "find flights in economy to Madrid"
        find_first_to_london = "find flights to London in first class"

        print(
            "\nWe'll create a new \"FindFlights\" intent including the following utterances:"
        )
        print(" - " + find_economy_to_madrid)
        print(" - " + find_first_to_london)

        intent_name = "FindFlights"
        intent_id = client.model.add_intent(app_id, version_id, intent_name)
        print("{} intent created with id {}".format(intent_name, intent_id))

        def get_example_label(utterance, entity_name, value):
            """Build a EntityLabelObject.

            This will find the "value" start/end index in "utterance", and assign it to "entity name"
            """
            utterance = utterance.lower()
            value = value.lower()
            return {
                'entity_name': entity_name,
                'start_char_index': utterance.find(value),
                'end_char_index': utterance.find(value) + len(value)
            }

        utterances = [{
            'text':
            find_economy_to_madrid,
            'intent_name':
            intent_name,
            'entity_labels': [
                get_example_label(find_economy_to_madrid, "Flight",
                                  "economy to madrid"),
                get_example_label(find_economy_to_madrid, "Destination",
                                  "Madrid"),
                get_example_label(find_economy_to_madrid, "Class", "economy"),
            ]
        }, {
            'text':
            find_first_to_london,
            'intent_name':
            intent_name,
            'entity_labels': [
                get_example_label(find_first_to_london, "Flight",
                                  "London in first class"),
                get_example_label(find_first_to_london, "Destination",
                                  "London"),
                get_example_label(find_first_to_london, "Class", "first"),
            ]
        }]
        utterances_result = client.examples.batch(app_id, version_id,
                                                  utterances)

        print("\nUtterances added to the {} intent".format(intent_name))

        # Training the model
        print("\nWe'll start training your app...")

        async_training = client.train.train_version(app_id, version_id)
        is_trained = async_training.status == "UpToDate"

        trained_status = ["UpToDate", "Success"]
        while not is_trained:
            time.sleep(1)
            status = client.train.get_status(app_id, version_id)
            is_trained = all(m.details.status in trained_status
                             for m in status)

        print(
            "Your app is trained. You can now go to the LUIS portal and test it!"
        )

        # Publish the app
        print("\nWe'll start publishing your app...")

        publish_result = client.apps.publish(app_id, {
            'version_id': version_id,
            'is_staging': False,
            'region': 'westus'
        })
        endpoint = publish_result.endpoint_url + \
            "?subscription-key=" + subscription_key + "&q="
        print("Your app is published. You can now go to test it on\n{}".format(
            endpoint))

    except Exception as err:
        print("Encountered exception. {}".format(err))
def quickstart():

    # Set variables ----------------------------------------------------

    appName = "BookFlight-Luis-model"
    versionId = "0.1"

    # Authenticate client------------------------------------------------

    client = LUISAuthoringClient(authoringEndpoint,
                                 CognitiveServicesCredentials(authoringKey))

    # Create LUIS application -------------------------------------------

    # define app basics
    appDefinition = {
        "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(f"Created LUIS app with id {app_id}")

    # Create intention(s) ------------------------------------------------

    intentNames = ["BookFlight", "Confirm", "Greetings"]
    for intent in intentNames:
        client.model.add_intent(app_id, versionId, intent)

    # Create entity(ies) -------------------------------------------------

    # Add pre_built entity :
    client.model.add_prebuilt(
        app_id,
        versionId,
        prebuilt_extractor_names=["money", "geographyV2", "datetimeV2"])

    # Create Airport entity :
    airport_entity = {"name": "Airport"}

    # Add ML entity to app
    from_entity = client.model.add_entity(app_id,
                                          versionId,
                                          name="From",
                                          children=[airport_entity])
    to_entity = client.model.add_entity(app_id,
                                        versionId,
                                        name="To",
                                        children=[airport_entity])

    departure_date_id = client.model.add_entity(app_id,
                                                versionId,
                                                name="Departure_date")
    return_date_id = client.model.add_entity(app_id,
                                             versionId,
                                             name="Return_date")
    budget_id = client.model.add_entity(app_id, versionId, name="budget")

    # Get entity and sub-entities for nested entities:
    from_object = client.model.get_entity(app_id, versionId, from_entity)
    to_object = client.model.get_entity(app_id, versionId, to_entity)

    from_airport_id = get_child_id(from_object, "Airport")
    to_airport_id = get_child_id(to_object, "Airport")

    # Add model as feature to subentity model
    prebuiltFeaturedDefinition = {
        "model_name": "geographyV2",
        "is_required": False
    }
    client.features.add_entity_feature(app_id, versionId, from_airport_id,
                                       prebuiltFeaturedDefinition)
    client.features.add_entity_feature(app_id, versionId, to_airport_id,
                                       prebuiltFeaturedDefinition)
    prebuiltFeaturedDefinition = {
        "model_name": "datetimeV2",
        "is_required": False
    }
    client.features.add_entity_feature(app_id, versionId, departure_date_id,
                                       prebuiltFeaturedDefinition)
    client.features.add_entity_feature(app_id, versionId, return_date_id,
                                       prebuiltFeaturedDefinition)
    prebuiltFeaturedDefinition = {"model_name": "money", "is_required": False}
    client.features.add_entity_feature(app_id, versionId, budget_id,
                                       prebuiltFeaturedDefinition)

    # Add utterances examples to intents ----------------------------------------------

    # Define labeled examples :
    BookFlight_json_file = "./data/training_data_50_ex.json"
    BookFlight_utterance = load_json(BookFlight_json_file)
    print("\nBookFlight_utterance : ", BookFlight_utterance)

    other_utterances = [{
        "text": "right",
        "intentName": intentNames[1]
    }, {
        "text": "yes",
        "intentName": intentNames[1]
    }, {
        "text": "OK",
        "intentName": intentNames[1]
    }, {
        "text": "good",
        "intentName": intentNames[1]
    }, {
        "text": "Hello",
        "intentName": intentNames[2]
    }, {
        "text": "Hi",
        "intentName": intentNames[2]
    }, {
        "text": "Hey",
        "intentName": intentNames[2]
    }, {
        "text": "Good morning",
        "intentName": intentNames[2]
    }]

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

    # Train the model ---------------------------------------------------------

    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 "InProgess" == x.
                details.status, info))
        if waiting:
            print("Waiting 10 seconds for training to complete")
            time.sleep(10)
        else:
            print("Trained")
            waiting = False

    # Publish the app ---------------------------------------------------------

    responseEndpointInfo = client.apps.publish(app_id,
                                               versionId,
                                               is_staging=False)
    print("Model published to Production slot")

    # Authenticate prediction runtime client ----------------------------------

    runtimeCredentials = CognitiveServicesCredentials(
        authoringKey)  # for test only. For production, use prediction key
    clientRuntime = LUISRuntimeClient(endpoint=predictionEndpoint,
                                      credentials=runtimeCredentials)

    # Get a prediction from runtime --------------------------------------------

    # Production == slot name
    predictionRequest = {
        "query":
        "Hi. i'd like to fly from New-York to Las-Vegas on August 10, 2021"
    }

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

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