快速入門:使用 Java 取得意圖Quickstart: Get intent using Java

在本快速入門中,會將將語句傳遞至 LUIS 端點,並取回意圖和實體。In this quickstart, pass utterances to a LUIS endpoint and get intent and entities back.

在本快速入門中,使用可用的公用 LUIS 應用程式,從交談文字判斷使用者的意圖。In this quickstart, use an available public LUIS app to determine a user's intention from conversational text. 以文字形式將使用者的用意傳送至公用應用程式的 HTTP 預測端點。Send the user's intention as text to the public app's HTTP prediction endpoint. 在端點,LUIS 會套用公用應用程式的模型來分析自然語言文字的意義、判斷整體意圖,並擷取與應用程式主體網域相關的資料。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.

本快速入門會使用端點 REST API。This quickstart uses the endpoint REST API. 如需詳細資訊,請參閱端點 API 文件For more information, see the endpoint API documentation.

在本文中,您需要免費 LUIS 帳戶。For this article, you need a free LUIS account.

必要條件Prerequisites

  • JDK SE (英文) (Java 開發套件,標準版)JDK SE (Java Development Kit, Standard Edition)
  • Visual Studio Code 或您最愛的 IDEVisual Studio Code or your favorite IDE
  • 公用應用程式識別碼:df67dcdb-c37d-46af-88e1-8b97951ca1c2Public app ID: df67dcdb-c37d-46af-88e1-8b97951ca1c2

注意

完整解決方案可從 cognitive-services-language-understanding GitHub 存放庫中取得。The complete solution is available from the cognitive-services-language-understanding GitHub repository.

取得 LUIS 金鑰Get LUIS key

預測端點的存取權會與端點金鑰一起提供。Access to the prediction endpoint is provided with an endpoint key. 基於本快速入門的目的,請使用與您的 LUIS 帳戶相關聯的免費入門金鑰。For the purposes of this quickstart, use the free starter key associated with your LUIS account.

  1. 使用您的 LUIS 帳戶登入。Sign in using your LUIS account.

    Language Understanding (LUIS) 應用程式清單的螢幕擷取畫面Screenshot of Language Understanding (LUIS) app list

  2. 在右上功能表中選取您的名稱,然後選取 [設定]。Select your name in the top right menu, then select Settings.

    LUIS 使用者設定功能表存取

  3. 複製 [撰寫金鑰] 的值。Copy the value of the Authoring key. 您稍後會在快速入門中使用此值。You will use it later in the quickstart.

    Language Understanding (LUIS) 使用者設定的螢幕擷取畫面Screenshot of Language Understanding (LUIS) user settings

    撰寫金鑰允許對撰寫 API 提出無限制的免費要求,而且每個月可對所有 LUIS 應用程式的預測端點 API 進行多達 1000 次查詢。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 with browser

若要了解 LUIS 預測端點所傳回的內容,請在網頁瀏覽器中檢視預測結果。To understand what a LUIS prediction endpoint returns, view a prediction result in a web browser. 若要查詢公用應用程式,您需要自己的金鑰和應用程式識別碼。In order to query a public app, you need your own key and the app ID. 公用 IoT 應用程式識別碼 (df67dcdb-c37d-46af-88e1-8b97951ca1c2) 會提供為第一個步驟中 URL 的一部分。The public IoT app ID, df67dcdb-c37d-46af-88e1-8b97951ca1c2, is provided as part of the URL in step one.

GET 端點要求的 URL 格式為:The format of the URL for a GET endpoint request is:

https://<region>.api.cognitive.microsoft.com/luis/v2.0/apps/<appID>?subscription-key=<YOUR-KEY>&q=<user-utterance>
  1. 公用 IoT 應用程式的端點採用以下格式:https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/df67dcdb-c37d-46af-88e1-8b97951ca1c2?subscription-key=<YOUR_KEY>&q=turn on the bedroom lightThe endpoint of the public IoT app is in this format: https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/df67dcdb-c37d-46af-88e1-8b97951ca1c2?subscription-key=<YOUR_KEY>&q=turn on the bedroom light

    複製此 URL,並以您的金鑰取代 <YOUR_KEY> 值。Copy the URL and substitute your key for the value of <YOUR_KEY>.

  2. 將 URL 貼入瀏覽器視窗,然後按 Enter。Paste the URL into a browser window and press Enter. 瀏覽器會顯示 JSON 結果,指出 LUIS 偵測到 HomeAutomation.TurnOn 意圖 (最高意圖) 和 HomeAutomation.Room 實體 (值為 bedroom)。The browser displays a JSON result that indicates that LUIS detects the HomeAutomation.TurnOn intent as the top intent and the HomeAutomation.Room entity with the value bedroom.

    {
      "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
        }
      ]
    }
    
  3. 將 URL 中的 q= 參數值變更為 turn off the living room light,然後按 Enter。Change the value of the q= parameter in the URL to turn off the living room light, and press Enter. 結果現在指出 LUIS 偵測到 HomeAutomation.TurnOff 意圖 (最高意圖) 和 HomeAutomation.Room 實體 (值為 living room)。The result now indicates that LUIS detected the HomeAutomation.TurnOff intent as the top intent and the HomeAutomation.Room entity with value living room.

    {
      "query": "turn off the living room light",
      "topScoringIntent": {
        "intent": "HomeAutomation.TurnOff",
        "score": 0.984057844
      },
      "entities": [
        {
          "entity": "living room",
          "type": "HomeAutomation.Room",
          "startIndex": 13,
          "endIndex": 23,
          "score": 0.9619945
        }
      ]
    }
    

以程式設計方式取得意圖Get intent programmatically

您可以使用 Java 來存取您在上一個步驟的瀏覽器視窗中看到的相同結果。You can use Java to access the same results you saw in the browser window in the previous step. 務必將 Apache 程式庫新增至您的專案。Be sure to add the Apache libraries to your project.

  1. 複製下列程式碼,以在名為 LuisGetRequest.java 的檔案中建立類別: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. 以您的 LUIS 金鑰取代 YOUR-KEY 變數的值。Replace the value of the YOUR-KEY variable with your LUIS key.

  3. 取代為您的檔案路徑,並從命令列編譯 Java 程式:javac -cp .;<FILE_PATH>\* LuisGetRequest.javaReplace with your file path and compile the java program from a command line: javac -cp .;<FILE_PATH>\* LuisGetRequest.java.

  4. 取代為您的檔案路徑,並從命令列執行應用程式:java -cp .;<FILE_PATH>\* LuisGetRequest.javaReplace with your file path and run the application from a command line: java -cp .;<FILE_PATH>\* LuisGetRequest.java. 它會顯示您稍早在瀏覽器視窗中看到的相同 JSON。It displays the same JSON that you saw earlier in the browser window.

    主控台視窗會顯示來自 LUIS 的 JSON 結果

LUIS 金鑰LUIS keys

為了方便起見,本快速入門會使用撰寫金鑰。This quickstart uses the authoring key for convenience. 此金鑰主要用於撰寫模型,但允許數目 (1000) 較小的端點要求。The key is primarily for authoring the model but does allow a small number (1000) of endpoint requests. 當您準備好在測試、預備或生產環境中使用更多端點要求時,請在 Azure 入口網站中建立 Language Understanding 資源,並將它指派給 LUIS 入口網站中的 LUIS 應用程式。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

刪除 Java 檔案/專案資料夾。Delete the Java file/project folder.

後續步驟Next steps