Quickstart: Get intent with REST APIs

In this quickstart, use an available public LUIS app to determine a user's intention from conversational text. Send the user's intention as text to the public app's HTTP prediction endpoint. At the endpoint, LUIS applies the public app's model to analyze the natural language text for meaning, determining overall intent and extracting data relevant to the app's subject domain.

This quickstart uses the endpoint REST API. For more information, see the endpoint API documentation.

For this article, you need a free LUIS account.

Prerequisites

Get LUIS key

Access to the keys and endpoints is provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. Sign in to the LUIS portal.

  2. Select your app from the apps list.

  3. Select Manage then select Azure Resources.

  4. Copy the values for the key and endpoint for the Starter resource.

    The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

Get intent programmatically

Use C# to query the prediction endpoint GET API to get the prediction result.

  1. Create a new console application targeting the C# language, with a project and folder name of predict-with-rest.

    dotnet new console -lang C# -n predict-with-rest
    
  2. Install required dependencies with the following dotnet CLI commands.

    dotnet add package System.Net.Http
    
  3. Overwrite Program.cs with the following code:

     using System;
     using System.Net.Http;
     using System.Web;
    
     namespace predict_with_rest
     {
         class Program
         {
             static void Main(string[] args)
             {
                 // YOUR-KEY: for example, the starter key
                 var key = "YOUR-KEY";
    
                 // YOUR-ENDPOINT: example is westus2.api.cognitive.microsoft.com
                 var endpoint = "YOUR-ENDPOINT";
    
                 // //public sample app
                 var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"; 
    
                 var utterance = "turn on all lights";
    
                 MakeRequest(key, endpoint, appId, utterance);
    
                 Console.WriteLine("Hit ENTER to exit...");
                 Console.ReadLine();
             }
             static async void MakeRequest(string key, string endpoint, string appId, string utterance)
             {
                 var client = new HttpClient();
                 var queryString = HttpUtility.ParseQueryString(string.Empty);
    
                 // The request header contains your subscription key
                 client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
    
                 // The "q" parameter contains the utterance to send to LUIS
                 queryString["query"] = utterance;
    
                 // These optional request parameters are set to their default values
                 queryString["verbose"] = "true";
                 queryString["show-all-intents"] = "true";
                 queryString["staging"] = "false";
                 queryString["timezoneOffset"] = "0";
    
                 var endpointUri = String.Format("https://{0}/luis/prediction/v3.0/apps/{1}/slots/production/predict?query={2}", endpoint, appId, queryString);
    
                 var response = await client.GetAsync(endpointUri);
    
                 var strResponseContent = await response.Content.ReadAsStringAsync();
    
                 // Display the JSON result from LUIS
                 Console.WriteLine(strResponseContent.ToString());
             }
         }
     }
    
    
  4. Replace the following values:

    • YOUR-KEY with your starter key
    • YOUR-ENDPOINT with your endpoint, for example, westus2.api.cognitive.microsoft.com
  5. Build the console application.

    dotnet build
    
  6. Run the console application. The console output displays the same JSON that you saw earlier in the browser window.

    dotnet run
    
  7. Review prediction response in JSON format:

    Hit ENTER to exit...
    {'query': 'turn on all lights', 'prediction': {'topIntent': 'HomeAutomation.TurnOn', 'intents': {'HomeAutomation.TurnOn': {'score': 0.5375382}, 'None': {'score': 0.08687421}, 'HomeAutomation.TurnOff': {'score': 0.0207554}}, 'entities': {'HomeAutomation.Operation': ['on'], '$instance': {'HomeAutomation.Operation': [{'type': 'HomeAutomation.Operation', 'text': 'on', 'startIndex': 5, 'length': 2, 'score': 0.724984169, 'modelTypeId': -1, 'modelType': 'Unknown', 'recognitionSources': ['model']}]}}}}
    

    The JSON response formatted for readability:

    {
        "query": "turn on all lights",
        "prediction": {
            "topIntent": "HomeAutomation.TurnOn",
            "intents": {
                "HomeAutomation.TurnOn": {
                    "score": 0.5375382
                },
                "None": {
                    "score": 0.08687421
                },
                "HomeAutomation.TurnOff": {
                    "score": 0.0207554
                }
            },
            "entities": {
                "HomeAutomation.Operation": [
                    "on"
                ],
                "$instance": {
                    "HomeAutomation.Operation": [
                        {
                            "type": "HomeAutomation.Operation",
                            "text": "on",
                            "startIndex": 5,
                            "length": 2,
                            "score": 0.724984169,
                            "modelTypeId": -1,
                            "modelType": "Unknown",
                            "recognitionSources": [
                                "model"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS keys

This quickstart uses the starter key for convenience. The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

Clean up resources

When you are finished with this quickstart, delete the file from the file system.

Next steps

Prerequisites

  • JDK SE (Java Development Kit, Standard Edition)
  • Visual Studio Code or your favorite IDE
  • Public app ID: df67dcdb-c37d-46af-88e1-8b97951ca1c2

Get LUIS key

Access to the keys and endpoints is provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. Sign in to the LUIS portal.

  2. Select your app from the apps list.

  3. Select Manage then select Azure Resources.

  4. Copy the values for the key and endpoint for the Starter resource.

    The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

Get intent programmatically

Use Java to query the prediction endpoint GET API to get the prediction result.

  1. Make a subdirectory named lib and copy in the following java libs:

  2. Copy the following code to create a class in a file named Predict.java:

    import java.io.*;
    import java.net.URI;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    public class Predict {
    
        public static void main(String[] args) 
        {
            HttpClient httpclient = HttpClients.createDefault();
    
            try
            {
    
                // The ID of a public sample LUIS app that recognizes intents for turning on and off lights
                String AppId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";
    
                // Add your endpoint key 
                String Key = "YOUR-KEY";
    
                // Add your endpoint, example is westus.api.cognitive.microsoft.com
                String Endpoint = "YOUR-ENDPOINT";
    
                String Utterance = "turn on all lights";
    
                // Begin endpoint URL string building
                URIBuilder endpointURLbuilder = new URIBuilder("https://" + Endpoint + "/luis/prediction/v3.0/apps/" + AppId + "/slots/production/predict?");
    
                // query string params
                endpointURLbuilder.setParameter("query", Utterance);
                endpointURLbuilder.setParameter("subscription-key", Key);
                endpointURLbuilder.setParameter("show-all-intents", "true");
                endpointURLbuilder.setParameter("verbose", "true");
    
                // create URL from string
                URI endpointURL = endpointURLbuilder.build();
    
                // create HTTP object from URL
                HttpGet request = new HttpGet(endpointURL);
    
                // access LUIS endpoint - analyze text
                HttpResponse response = httpclient.execute(request);
    
                // get response
                HttpEntity entity = response.getEntity();
    
    
                if (entity != null) 
                {
                    System.out.println(EntityUtils.toString(entity));
                }
            }
    
            catch (Exception e)
            {
                System.out.println(e.getMessage());
            }
        }   
    }    
    
  3. Replace the following values:

    • YOUR-KEY with your starter key
    • YOUR-ENDPOINT with your endpoint, for example, westus2.api.cognitive.microsoft.com
  4. Compile the java program from a command line:

    javac -cp ":lib/*" Predict.java
    
  5. Run the java program from the command line:

    java -cp ":lib/*" Predict
    
  6. Review prediction response in JSON format:

    {'query': 'turn on all lights', 'prediction': {'topIntent': 'HomeAutomation.TurnOn', 'intents': {'HomeAutomation.TurnOn': {'score': 0.5375382}, 'None': {'score': 0.08687421}, 'HomeAutomation.TurnOff': {'score': 0.0207554}}, 'entities': {'HomeAutomation.Operation': ['on'], '$instance': {'HomeAutomation.Operation': [{'type': 'HomeAutomation.Operation', 'text': 'on', 'startIndex': 5, 'length': 2, 'score': 0.724984169, 'modelTypeId': -1, 'modelType': 'Unknown', 'recognitionSources': ['model']}]}}}}
    

    The JSON response formatted for readability:

    {
        "query": "turn on all lights",
        "prediction": {
            "topIntent": "HomeAutomation.TurnOn",
            "intents": {
                "HomeAutomation.TurnOn": {
                    "score": 0.5375382
                },
                "None": {
                    "score": 0.08687421
                },
                "HomeAutomation.TurnOff": {
                    "score": 0.0207554
                }
            },
            "entities": {
                "HomeAutomation.Operation": [
                    "on"
                ],
                "$instance": {
                    "HomeAutomation.Operation": [
                        {
                            "type": "HomeAutomation.Operation",
                            "text": "on",
                            "startIndex": 5,
                            "length": 2,
                            "score": 0.724984169,
                            "modelTypeId": -1,
                            "modelType": "Unknown",
                            "recognitionSources": [
                                "model"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS keys

This quickstart uses the starter key for convenience. The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

Clean up resources

When you are finished with this quickstart, delete the file from the file system.

Next steps

Prerequisites

Get LUIS key

Access to the keys and endpoints is provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. Sign in to the LUIS portal.

  2. Select your app from the apps list.

  3. Select Manage then select Azure Resources.

  4. Copy the values for the key and endpoint for the Starter resource.

    The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

Get intent programmatically

Use Python to query the prediction endpoint GET API to get the prediction result.

  1. Copy one of the following code snippets to a file called predict.py:

    ########### Python 3.6 #############
    import requests
    
    try:
    
        key = 'YOUR-KEY'
        endpoint = 'YOUR-ENDPOINT' # such as 'westus2.api.cognitive.microsoft.com' 
        appId = 'df67dcdb-c37d-46af-88e1-8b97951ca1c2'
        utterance = 'turn on all lights'
    
        headers = {
        }
    
        params ={
            'query': utterance,
            'timezoneOffset': '0',
            'verbose': 'true',
            'show-all-intents': 'true',
            'spellCheck': 'false',
            'staging': 'false',
            'subscription-key': key
        }
    
        r = requests.get(f'https://{endpoint}/luis/prediction/v3.0/apps/{appId}/slots/production/predict',headers=headers, params=params)
        print(r.json())
    
    except Exception as e:
        print(f'{e}')
    
  2. Replace the following values:

    • YOUR-KEY with your starter key
    • YOUR-ENDPOINT with your endpoint, for example, westus2.api.cognitive.microsoft.com
  3. Install dependencies with the following console command:

    pip install requests
    
  4. Run the script with the following console command:

    python predict.py
    
  5. Review prediction response in JSON format:

    {'query': 'turn on all lights', 'prediction': {'topIntent': 'HomeAutomation.TurnOn', 'intents': {'HomeAutomation.TurnOn': {'score': 0.5375382}, 'None': {'score': 0.08687421}, 'HomeAutomation.TurnOff': {'score': 0.0207554}}, 'entities': {'HomeAutomation.Operation': ['on'], '$instance': {'HomeAutomation.Operation': [{'type': 'HomeAutomation.Operation', 'text': 'on', 'startIndex': 5, 'length': 2, 'score': 0.724984169, 'modelTypeId': -1, 'modelType': 'Unknown', 'recognitionSources': ['model']}]}}}}
    

    The JSON response formatted for readability:

    {
        "query": "turn on all lights",
        "prediction": {
            "topIntent": "HomeAutomation.TurnOn",
            "intents": {
                "HomeAutomation.TurnOn": {
                    "score": 0.5375382
                },
                "None": {
                    "score": 0.08687421
                },
                "HomeAutomation.TurnOff": {
                    "score": 0.0207554
                }
            },
            "entities": {
                "HomeAutomation.Operation": [
                    "on"
                ],
                "$instance": {
                    "HomeAutomation.Operation": [
                        {
                            "type": "HomeAutomation.Operation",
                            "text": "on",
                            "startIndex": 5,
                            "length": 2,
                            "score": 0.724984169,
                            "modelTypeId": -1,
                            "modelType": "Unknown",
                            "recognitionSources": [
                                "model"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS keys

This quickstart uses the starter key for convenience. The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

Clean up resources

When you are finished with this quickstart, delete the file from the file system.

Next steps

Prerequisites

Get LUIS key

Access to the keys and endpoints is provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. Sign in to the LUIS portal.

  2. Select your app from the apps list.

  3. Select Manage then select Azure Resources.

  4. Copy the values for the key and endpoint for the Starter resource.

    The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

Get intent programmatically

Use Node.js to query the prediction endpoint GET API to get the prediction result.

  1. Copy the following code snippet to a file named predict.js:

    var request = require('request');
    var requestpromise = require('request-promise');
    var querystring = require('querystring');
    
    // Analyze text
    //
    getPrediction = async () => {
    
        // YOUR-KEY - Language Understanding starter key
        var endpointKey = "YOUR-KEY";
    
        // YOUR-ENDPOINT Language Understanding endpoint URL, an example is westus2.api.cognitive.microsoft.com
        var endpoint = "YOUR-ENDPOINT";
    
        // Set the LUIS_APP_ID environment variable 
        // to df67dcdb-c37d-46af-88e1-8b97951ca1c2, which is the ID
        // of a public sample application.    
        var appId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";
    
        var utterance = "turn on all lights";
    
        // Create query string 
        var queryParams = {
            "show-all-intents": true,
            "verbose":  true,
            "query": utterance,
            "subscription-key": endpointKey
        }
    
        // append query string to endpoint URL
        var URI = `https://${endpoint}/luis/prediction/v3.0/apps/${appId}/slots/production/predict?${querystring.stringify(queryParams)}`
    
        // HTTP Request
        const response = await requestpromise(URI);
    
        // HTTP Response
        console.log(response);
    
    }
    
    // Pass an utterance to the sample LUIS app
    getPrediction().then(()=>console.log("done")).catch((err)=>console.log(err));
    
  2. Set the following values:

    • YOUR-KEY to your starter key
    • YOUR-ENDPOINT to your endpoint URL
  3. Install dependencies by running the following command at the command-line:

    npm install request request-promise querystring
    
  4. Run the code with the following command:

    node predict.js
    
  5. Review prediction response in JSON format:

    {"query":"turn on all lights","prediction":{"topIntent":"HomeAutomation.TurnOn","intents":{"HomeAutomation.TurnOn":{"score":0.5375382},"None":{"score":0.08687421},"HomeAutomation.TurnOff":{"score":0.0207554}},"entities":{"HomeAutomation.Operation":["on"],"$instance":{"HomeAutomation.Operation":[{"type":"HomeAutomation.Operation","text":"on","startIndex":5,"length":2,"score":0.724984169,"modelTypeId":-1,"modelType":"Unknown","recognitionSources":["model"]}]}}}}
    

    The JSON response formatted for readability:

    {
        "query": "turn on all lights",
        "prediction": {
            "topIntent": "HomeAutomation.TurnOn",
            "intents": {
                "HomeAutomation.TurnOn": {
                    "score": 0.5375382
                },
                "None": {
                    "score": 0.08687421
                },
                "HomeAutomation.TurnOff": {
                    "score": 0.0207554
                }
            },
            "entities": {
                "HomeAutomation.Operation": [
                    "on"
                ],
                "$instance": {
                    "HomeAutomation.Operation": [
                        {
                            "type": "HomeAutomation.Operation",
                            "text": "on",
                            "startIndex": 5,
                            "length": 2,
                            "score": 0.724984169,
                            "modelTypeId": -1,
                            "modelType": "Unknown",
                            "recognitionSources": [
                                "model"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS keys

This quickstart uses the starter key for convenience. The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

Clean up resources

When you are finished with this quickstart, delete the file from the file system.

Next steps

Prerequisites

Get LUIS key

Access to the keys and endpoints is provided in the LUIS portal in the Manage Section on the Azure Resources page.

  1. Sign in to the LUIS portal.

  2. Select your app from the apps list.

  3. Select Manage then select Azure Resources.

  4. Copy the values for the key and endpoint for the Starter resource.

    The Starter key allows free requests to the authoring API and up to 1000 queries to the prediction endpoint API per month for all your LUIS apps.

Get intent programmatically

Use Go to query the prediction endpoint GET API to get the prediction result.

  1. Create a new file named predict.go. Add the following code:

    package main
    
    /* Do dependencies */
    import (
        "fmt"
        "net/http"
        "net/url"
        "io/ioutil"
        "log"
    )
    func main() {
    
    	// public app
        var appID = "df67dcdb-c37d-46af-88e1-8b97951ca1c2"
    
    	// utterance for public app
    	var utterance = "turn on all lights"
    
    	// YOUR-KEY - your starter or prediction key
    	var endpointKey = "YOUR-KEY"
    
    	// YOUR-ENDPOINT - example is westus2.api.cognitive.microsoft.com
        var endpoint = "YOUR-ENDPOINT"
    
    	endpointPrediction(appID, endpointKey, endpoint, utterance)
    }
    func endpointPrediction(appID string, endpointKey string, endpoint string, utterance string) {
    
        var endpointUrl = fmt.Sprintf("https://%s/luis/prediction/v3.0/apps/%s/slots/production/predict?subscription-key=%s&verbose=true&show-all-intents=true&query=%s", endpoint, appID, endpointKey, url.QueryEscape(utterance))
    
        response, err := http.Get(endpointUrl)
    
        if err!=nil {
            // handle error
            fmt.Println("error from Get")
            log.Fatal(err)
        }
    
        response2, err2 := ioutil.ReadAll(response.Body)
    
        if err2!=nil {
            // handle error
            fmt.Println("error from ReadAll")
            log.Fatal(err2)
        }
    
        fmt.Println("response")
        fmt.Println(string(response2))
    }
    
  2. Replace the following values:

    • YOUR-KEY with your starter key
    • YOUR-ENDPOINT with your endpoint, for example, westus2.api.cognitive.microsoft.com
  3. With a command prompt in the same directory as where you created the file, enter the following command to compile the Go file:

    go build predict.go
    
  4. Run the Go application from the command line by entering the following text in the command prompt:

    go run predict.go
    

    The command prompt response is:

    appID has value df67dcdb-c37d-46af-88e1-8b97951ca1c2
    endpointKey has value a7b206911f714e71a1ddae36928a61cc
    endpoint has value westus2.api.cognitive.microsoft.com
    utterance has value turn on all lights
    response
    {"query":"turn on all lights","prediction":{"topIntent":"HomeAutomation.TurnOn","intents":{"HomeAutomation.TurnOn":{"score":0.5375382},"None":{"score":0.08687421},"HomeAutomation.TurnOff":{"score":0.0207554}},"entities":{"HomeAutomation.Operation":["on"],"$instance":{"HomeAutomation.Operation":[{"type":"HomeAutomation.Operation","text":"on","startIndex":5,"length":2,"score":0.724984169,"modelTypeId":-1,"modelType":"Unknown","recognitionSources":["model"]}]}}}}
    

    JSON formatted for readability:

    {
        "query": "turn on all lights",
        "prediction": {
            "topIntent": "HomeAutomation.TurnOn",
            "intents": {
                "HomeAutomation.TurnOn": {
                    "score": 0.5375382
                },
                "None": {
                    "score": 0.08687421
                },
                "HomeAutomation.TurnOff": {
                    "score": 0.0207554
                }
            },
            "entities": {
                "HomeAutomation.Operation": [
                    "on"
                ],
                "$instance": {
                    "HomeAutomation.Operation": [
                        {
                            "type": "HomeAutomation.Operation",
                            "text": "on",
                            "startIndex": 5,
                            "length": 2,
                            "score": 0.724984169,
                            "modelTypeId": -1,
                            "modelType": "Unknown",
                            "recognitionSources": [
                                "model"
                            ]
                        }
                    ]
                }
            }
        }
    }
    

LUIS keys

This quickstart uses the starter key for convenience. The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. When you are ready for more endpoint requests in a test, stage or production environment, create a Language Understanding resource in the Azure portal and assign it to the LUIS app in the LUIS portal.

Clean up resources

When you are finished with this quickstart, delete the file from the file system.

Next steps