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

Note

The complete solution is available from the cognitive-services-language-understanding GitHub repository.

Get LUIS key

Access to the prediction endpoint is provided with an endpoint key. For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. Sign in using your LUIS account.

    Screenshot of Language Understanding (LUIS) app list

  2. Select your name in the top right menu, then select Settings.

    LUIS user settings menu access

  3. Copy the value of the Authoring key. You will use it later in the quickstart.

    Screenshot of Language Understanding (LUIS) user settings

    The authoring key allows free unlimited 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 same results as you saw in the browser window in the previous section.

  1. Create a new console application in Visual Studio.

    Create a new console application in Visual Studio

  2. In the Visual Studio project, in the Solutions Explorer, select Add reference, then select System.Web from the Assemblies tab.

    select Add reference, then select System.Web from the Assemblies tab

  3. Overwrite Program.cs with the following code:

    using System;
    using System.Net.Http;
    using System.Web;
    
    /*
    
        You can use the authoring key instead of the endpoint key. 
        The authoring key allows 1000 endpoint queries a month.
    
    */
    
    namespace ConsoleLuisEndpointSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                MakeRequest();
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
    
            static async void MakeRequest()
            {
                var client = new HttpClient();
                var queryString = HttpUtility.ParseQueryString(string.Empty);
    
                // This app ID is for a public sample app that recognizes requests to turn on and turn off lights
                var luisAppId = "df67dcdb-c37d-46af-88e1-8b97951ca1c2";
                var endpointKey = "YOUR_KEY";
    
                // The request header contains your subscription key
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", endpointKey);
    
                // The "q" parameter contains the utterance to send to LUIS
                queryString["q"] = "turn on the left light";
    
                // These optional request parameters are set to their default values
                queryString["timezoneOffset"] = "0";
                queryString["verbose"] = "false";
                queryString["spellCheck"] = "false";
                queryString["staging"] = "false";
    
                var endpointUri = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + luisAppId + "?" + 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 value of YOUR_KEY with your LUIS key.

  5. Build and run the console application. It displays the same JSON that you saw earlier in the browser window.

    Console window displays JSON result from LUIS

LUIS keys

This quickstart uses the authoring 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, close the Visual Studio project and remove the project directory 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

Note

The complete solution is available from the cognitive-services-language-understanding GitHub repository.

Get LUIS key

Access to the prediction endpoint is provided with an endpoint key. For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. Sign in using your LUIS account.

    Screenshot of Language Understanding (LUIS) app list

  2. Select your name in the top right menu, then select Settings.

    LUIS user settings menu access

  3. Copy the value of the Authoring key. You will use it later in the quickstart.

    Screenshot of Language Understanding (LUIS) user settings

    The authoring key allows free unlimited 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

You can use Java to access the same results you saw in the browser window in the previous step. Be sure to add the Apache libraries to your project.

  1. Copy the following code to create a class in a file named LuisGetRequest.java:

    // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/downloads.cgi)
    
    // You need to add the following Apache HTTP client libraries to your project:
    // httpclient-4.5.3.jar
    // httpcore-4.4.11.jar
    // commons-logging-4.0.6.jar
    
    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 LuisGetRequest {
    
        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 
                // You can use the authoring key instead of the endpoint key. 
                // The authoring key allows 1000 endpoint queries a month.
                String EndpointKey = "YOUR-KEY";
    
                // Begin endpoint URL string building
                URIBuilder endpointURLbuilder = new URIBuilder("https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + AppId + "?");
    
                // query text
                endpointURLbuilder.setParameter("q", "turn on the left light");
    
                // create URL from string
                URI endpointURL = endpointURLbuilder.build();
    
                // create HTTP object from URL
                HttpGet request = new HttpGet(endpointURL);
    
                // set key to access LUIS endpoint
                request.setHeader("Ocp-Apim-Subscription-Key", EndpointKey);
    
                // 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());
            }
        }
    }
    
  2. Replace the value of the YOUR-KEY variable with your LUIS key.

  3. Replace with your file path and compile the java program from a command line: javac -cp .;<FILE_PATH>\* LuisGetRequest.java.

  4. Replace with your file path and run the application from a command line: java -cp .;<FILE_PATH>\* LuisGetRequest.java. It displays the same JSON that you saw earlier in the browser window.

    Console window displays JSON result from LUIS

LUIS keys

This quickstart uses the authoring 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, close the Visual Studio project and remove the project directory from the file system.

Next steps

Prerequisites

Note

The complete solution is available from the cognitive-services-language-understanding GitHub repository.

Get LUIS key

Access to the prediction endpoint is provided with an endpoint key. For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. Sign in using your LUIS account.

    Screenshot of Language Understanding (LUIS) app list

  2. Select your name in the top right menu, then select Settings.

    LUIS user settings menu access

  3. Copy the value of the Authoring key. You will use it later in the quickstart.

    Screenshot of Language Understanding (LUIS) user settings

    The authoring key allows free unlimited 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

You can use Python to access the same results you saw in the browser window in the previous step.

  1. Copy one of the following code snippets to a file called quickstart-call-endpoint.py:

    ########### Python 2.7 #############
    import httplib, urllib, base64
    
    headers = {
        # Request headers includes endpoint key
        # You can use the authoring key instead of the endpoint key.
        # The authoring key allows 1000 endpoint queries a month.
        'Ocp-Apim-Subscription-Key': 'YOUR-KEY',
    }
    
    params = urllib.urlencode({
        # Text to analyze
        'q': 'turn on the left light',
        # Optional request parameters, set to default values
        'verbose': 'false',
    })
    
    # HTTP Request
    try:
        # LUIS endpoint HOST for westus region
        conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
    
        # LUIS endpoint path
        # includes public app ID
        conn.request("GET", "/luis/v2.0/apps/df67dcdb-c37d-46af-88e1-8b97951ca1c2?%s" % params, "{body}", headers)
    
        response = conn.getresponse()
        data = response.read()
    
        # print HTTP response to screen
        print(data)
        conn.close()
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))
    
    ####################################
    
  2. Replace the value of the Ocp-Apim-Subscription-Key field with your LUIS endpoint key.

  3. Install dependencies with pip install requests.

  4. Run the script with python ./quickstart-call-endpoint.py. It displays the same JSON that you saw earlier in the browser window.

LUIS keys

This quickstart uses the authoring 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, close the Visual Studio project and remove the project directory from the file system.

Next steps

Prerequisites

Note

The complete Node.js solution is available from the Azure-Samples GitHub repository.

Get LUIS key

Access to the prediction endpoint is provided with an endpoint key. For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. Sign in using your LUIS account.

    Screenshot of Language Understanding (LUIS) app list

  2. Select your name in the top right menu, then select Settings.

    LUIS user settings menu access

  3. Copy the value of the Authoring key. You will use it later in the quickstart.

    Screenshot of Language Understanding (LUIS) user settings

    The authoring key allows free unlimited 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

You can use Node.js to access the same results you saw in the browser window in the previous step.

  1. Copy the following code snippet:

    require('dotenv').config();
    
    var request = require('request');
    var querystring = require('querystring');
    
    // Analyze text
    //
    // utterance = user's text
    //
    function getLuisIntent(utterance) {
    
        // endpoint URL
        var endpoint =
            "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/";
    
        // Set the LUIS_APP_ID environment variable 
        // to df67dcdb-c37d-46af-88e1-8b97951ca1c2, which is the ID
        // of a public sample application.    
        var luisAppId = process.env.LUIS_APP_ID;
    
        // Read LUIS key from environment file ".env"
        // You can use the authoring key instead of the endpoint key. 
        // The authoring key allows 1000 endpoint queries a month.
        var endpointKey = process.env.LUIS_ENDPOINT_KEY;
    
        // Create query string 
        var queryParams = {
            "verbose":  true,
            "q": utterance,
            "subscription-key": endpointKey
        }
    
        // append query string to endpoint URL
        var luisRequest =
            endpoint + luisAppId +
            '?' + querystring.stringify(queryParams);
    
        // HTTP Request
        request(luisRequest,
            function (err,
                response, body) {
    
                // HTTP Response
                if (err)
                    console.log(err);
                else {
                    var data = JSON.parse(body);
    
                    console.log(`Query: ${data.query}`);
                    console.log(`Top Intent: ${data.topScoringIntent.intent}`);
                    console.log('Intents:');
                    console.log(JSON.stringify(data.intents));
                }
            });
    }
    
    // Pass an utterance to the sample LUIS app
    getLuisIntent('turn on the left light');
    
    
    
  2. Create .env file with the following text or set these variables in the system environment:

    LUIS_APP_ID=df67dcdb-c37d-46af-88e1-8b97951ca1c2
    LUIS_ENDPOINT_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
  3. Set the LUIS_ENDPOINT_KEY environment variable to your key.

  4. Install dependencies by running the following command at the command-line: npm install.

  5. Run the code with npm start. It displays the same values that you saw earlier in the browser window.

LUIS keys

This quickstart uses the authoring 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, close the Visual Studio project and remove the project directory from the file system.

Next steps

Prerequisites

Note

The complete solution is available from the cognitive-services-language-understanding GitHub repository.

Get LUIS key

Access to the prediction endpoint is provided with an endpoint key. For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. Sign in using your LUIS account.

    Screenshot of Language Understanding (LUIS) app list

  2. Select your name in the top right menu, then select Settings.

    LUIS user settings menu access

  3. Copy the value of the Authoring key. You will use it later in the quickstart.

    Screenshot of Language Understanding (LUIS) user settings

    The authoring key allows free unlimited 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

You can use Go to access the same results you saw in the browser window in the previous step.

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

    package main
    
    /* Do dependencies */
    import (
        "fmt"
        "flag"
        "net/http"
        "net/url"
        "io/ioutil"
        "log"
    )
    
    /* 
        Analyze text
    
        appID = public app ID = be402ffc-57f4-4e1f-9c1d-f0d9fa520aa4
        endpointKey = Azure Language Understanding key, or Authoring key if it still has quota
        region = endpoint region
        utterance = text to analyze
    
    */
    func endpointPrediction(appID string, endpointKey string, region string, utterance string) {
    
        var endpointUrl = fmt.Sprintf("https://%s.api.cognitive.microsoft.com/luis/v2.0/apps/%s?subscription-key=%s&verbose=false&q=%s", region, appID, endpointKey, url.QueryEscape(utterance))
        
        response, err := http.Get(endpointUrl)
    
        // 401 - check value of 'subscription-key' - do not use authoring key!
        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))
    }
    
    func main() {
        
        var appID = flag.String("appID", "df67dcdb-c37d-46af-88e1-8b97951ca1c2", "LUIS appID")
        var endpointKey = flag.String("endpointKey", "", "LUIS endpoint key")
        var region = flag.String("region", "", "LUIS app publish region")
        var utterance = flag.String("utterance", "turn on the bedroom light", "utterance to predict")
    
        flag.Parse()
        
        fmt.Println("appID has value", *appID)
        fmt.Println("endpointKey has value", *endpointKey)
        fmt.Println("region has value", *region)
        fmt.Println("utterance has value", *utterance)
    
        endpointPrediction(*appID, *endpointKey, *region, *utterance)
    
    }
    
  2. With a command prompt in the same directory as where you created the file, enter go build endpoint.go to compile the Go file. The command prompt does not return any information for a successful build.

  3. Run the Go application from the command line by entering the following text in the command prompt:

    go run endpoint.go -appID df67dcdb-c37d-46af-88e1-8b97951ca1c2 -endpointKey <add-your-key> -region westus
    

    Replace <add-your-key> with the value of your key.

    The command prompt response is:

    appID has value df67dcdb-c37d-46af-88e1-8b97951ca1c2
    endpointKey has value xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    region has value westus
    utterance has value turn on the bedroom light
    response
    {
        "query": "turn on the bedroom light",
        "topScoringIntent": {
            "intent": "HomeAutomation.TurnOn",
            "score": 0.809439957
        },
        "entities": [
            {
            "entity": "bedroom",
            "type": "HomeAutomation.Room",
            "startIndex": 12,
            "endIndex": 18,
            "score": 0.8065475
            }
        ]
    }
    

LUIS keys

This quickstart uses the authoring 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, close the Visual Studio project and remove the project directory from the file system.

Next steps