Quickstart: Add utterances to app using PHP

In this quickstart, write a program to add an utterance to an intent using the Authoring APIs in PHP.

For more information, refer to the technical documentation for the add utterance, train, and training status APIs.

For this article, you need a free LUIS account in order to author your LUIS application.

Prerequisites

  • Latest PHP.
  • Make sure openssl is available as a dependency for PHP.
  • Your LUIS authoring key. You can find this key under Account Settings in the LUIS website.
  • Your existing LUIS application ID. The application ID is shown in the application dashboard. The LUIS application with the intents and entities used in the utterances.json file must exist prior to running the code in add-utterances.php. The code in this article does not create the intents and entities. It only adds the utterances for existing intents and entities.
  • The version ID within the application that receives the utterances. The default ID is "0.1"
  • Create a new file named add-utterances.php project in VSCode.

Note

The complete add-utterances.cs file and an example utterances.json file are available from the LUIS-Samples Github repository.

Write the PHP code

Add the dependencies to the file.

// NOTE: Replace this example LUIS application ID with the ID of your LUIS application.
$appID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

// NOTE: Replace this example LUIS application version number with the version number of your LUIS application.
$appVersion = "0.1";

// NOTE: Replace this example LUIS authoring key with a valid key.
$key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

$host = "https://westus.api.cognitive.microsoft.com";
$path = "/luis/api/v2.0/apps/" . $appID . "/versions/" . $appVersion . "/";
$uri = $host . $path;

$usage = "Usage:
add-utterances <input file>
add-utterances -train <input file>
add-utterances -status

The contents of <input file> must be in the format described at: https://aka.ms/add-utterance-json-format
";

Add the GET request used for training status.

function SendGet ($uri, $key) {

	echo "GET " . $uri;

	$headers = "Content-type: text/json\r\n" .
		"Ocp-Apim-Subscription-Key: $key\r\n";

	// NOTE: Use the key 'http' even if you are making an HTTPS request. See:
	// http://php.net/manual/en/function.stream-context-create.php
	$options = array (
		'http' => array (
			'header' => $headers,
			'method' => 'GET',
		)
	);
	// Perform the Web request and get the JSON response
	$context  = stream_context_create ($options);
	$result = file_get_contents ($uri, false, $context);
	return $result;
}

Add the POST request used to create utterances or start training.

function SendPost ($uri, $key, $content) {

	echo "POST " . $uri;

	$headers = "Content-type: text/json\r\n" .
		"Ocp-Apim-Subscription-Key: $key\r\n";

	// NOTE: Use the key 'http' even if you are making an HTTPS request. See:
	// http://php.net/manual/en/function.stream-context-create.php
	$options = array (
		'http' => array (
			'header' => $headers,
			'method' => 'POST',
			'content' => $content
		)
	);
	// Perform the Web request and get the JSON response
	$context  = stream_context_create ($options);
	$result = file_get_contents ($uri, false, $context);
	return $result;
}

Add the AddUtterances function.

function AddUtterances($uri, $key, $input_file) {
	$content = file_get_contents ($input_file);
	echo "Added utterances.\n";
	$result = SendPost ($uri . "examples", $key, $content);
    echo json_encode (json_decode ($result), JSON_PRETTY_PRINT);
}

Add the Train function.

function Train($uri, $key, $input_file) {
	$content = file_get_contents ($input_file);
	echo "Sent training request.\n";
	$result = SendPost ($uri . "train", $key, $content);
    echo json_encode (json_decode ($result), JSON_PRETTY_PRINT);
	echo "\n";
	Status($uri, $key);
}

Add the Status function.

function Status($uri, $key) {
	echo "Requested training status.\n";
	$result = SendGet ($uri . "train", $key);
    echo json_encode (json_decode ($result), JSON_PRETTY_PRINT);
}

To manage the command line arguments, add the main code block.

if ($argc < 2)
{
	echo $usage;
}
else
{
	if (0 === strcasecmp($argv[1], "-train")) {
		if ($argc > 2)
		{
			Train($uri, $key, $argv[2]);
		}
		else
		{
			echo $usage;
		}
	}
	else if (0 === strcasecmp($argv[1], "-status"))
	{
		Status($uri, $key);
	}
	else
	{
		AddUtterances($uri, $key, $argv[1]);
	}
}

Specify utterances to add

Create and edit the file utterances.json to specify the array of utterances you want to add to the LUIS app. The intent and entities must already be in the LUIS app.

Note

The LUIS application with the intents and entities used in the utterances.json file must exist prior to running the code in add-utterances.php. The code in this article does not create the intents and entities. It only adds the utterances for existing intents and entities.

The text field contains the text of the utterance. The intentName field must correspond to the name of an intent in the LUIS app. The entityLabels field is required. If you don't want to label any entities, provide an empty list as shown in the following example:

If the entityLabels list is not empty, the startCharIndex and endCharIndex need to mark the entity referred to in the entityName field. Both indexes are zero-based counts meaning 6 in the top example refers to the "S" of Seattle and not the space before the capital S.

[
    {
        "text": "go to Seattle",
        "intentName": "BookFlight",
        "entityLabels": [
            {
                "entityName": "Location::LocationTo",
                "startCharIndex": 6,
                "endCharIndex": 12
            }
        ]
    },
    {
        "text": "book a flight",
        "intentName": "BookFlight",
        "entityLabels": []
    }
]

Add an utterance from the command line

Run the application from a command line with PHP.

Calling add-utterances.php with only the utterance.json as an argument adds but does not train LUIS on the new utterances.

> php add-utterances.php ./utterances.json

The following JSON is returned from the add utterances API call. The response field is in this format for utterances that was added. The hasError is false, indicating the utterance was added.

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

Add an utterance and train from the command line

Call add-utterance.php with the -train argument to send a request to train.

> php add-utterances.php ./utterances.json -train

Note

Duplicate utterances aren't added again, but don't cause an error. The response contains the ID of the original utterance.

The following shows the result of a successful request to train:

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

After the request to train is queued, it can take a moment to complete training.

Get training status from the command line

Call the app with the -status argument to check the training status and display status details.

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

Next steps