Detecting Intent from Text

Here is an example of detecting intent by sending text to a Dialogflow agent.

Set up your GCP project and authentication

Create an agent

Import the example intents and entities

Detect intent

Protocol

After you have imported the sample agent, you can pass user input to the detectIntent endpoint to determine what the user has requested and which action to take.

Follow these steps to determine the intent when the user input is "reserve a meeting room for six people".

  1. Use the following curl command to access the detectIntent endpoint and specify user input of "reserve a meeting room for six people". Replace project-name with the name of your Google Cloud project. The command uses the gcloud command-line interface from the Google Cloud SDK to get an authorization token for the command. For instructions on setting up authorization, see Quickstart.

    curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
         -H "Content-Type: application/json; charset=utf-8" --data "{
      'query_input': {
        'text': {
          'text': 'reserve a meeting room for six people',
          'language_code': 'en-US'
        }
      }
    }" "https://dialogflow.googleapis.com/v2/projects/project-name/agent/sessions/123456789:detectIntent"
      

    You should see a response similar to the following. Notice that the action is room.reservation, guests is 6, and fulfillmentText asks the user for more information.

    {
      "responseId": "50fcfcec-a315-4415-9075-5e0391e1f952",
      "queryResult": {
        "queryText": "reserve a meeting room for six people",
        "action": "room.reservation",
        "parameters": {
          "time": "",
          "date": "",
          "guests": 6,
          "duration": "",
          "location": ""
        },
        "fulfillmentText": "I can help with that. Where would you like to reserve a room?",
        "fulfillmentMessages": [
          {
            "text": {
              "text": [
                "I can help with that. Where would you like to reserve a room?"
              ]
            },
            "platform": "FACEBOOK"
          },
          {
            "text": {
              "text": [
                "I can help with that. Where would you like to reserve a room?"
              ]
            }
          }
        ],
        "outputContexts": [
          {
            "name": "projects/project-name/agent/sessions/123456789/contexts/e8f6a63e-73da-4a1a-8bfc-857183f71228_id_dialog_context",
            "lifespanCount": 2,
            "parameters": {
              "time.original": "",
              "time": "",
              "duration.original": "",
              "date": "",
              "guests": 6,
              "duration": "",
              "location.original": "",
              "guests.original": "six",
              "location": "",
              "date.original": ""
            }
          },
          {
            "name": "projects/project-name/agent/sessions/123456789/contexts/room_reservation_dialog_params_location",
            "lifespanCount": 1,
            "parameters": {
              "time.original": "",
              "time": "",
              "duration.original": "",
              "date": "",
              "guests": 6,
              "duration": "",
              "location.original": "",
              "guests.original": "six",
              "location": "",
              "date.original": ""
            }
          },
          {
            "name": "projects/project-name/agent/sessions/123456789/contexts/room_reservation_dialog_context",
            "lifespanCount": 2,
            "parameters": {
              "date.original": "",
              "time.original": "",
              "time": "",
              "duration.original": "",
              "date": "",
              "guests": 6,
              "duration": "",
              "location.original": "",
              "guests.original": "six",
              "location": ""
            }
          }
        ],
        "intent": {
          "name": "projects/project-name/agent/intents/e8f6a63e-73da-4a1a-8bfc-857183f71228",
          "displayName": "room.reservation"
        },
        "intentDetectionConfidence": 1,
        "diagnosticInfo": {},
        "languageCode": "en-us"
      }
    }
      

C#

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

        public static int DetectIntentFromTexts(string projectId,
                                                string sessionId,
                                                string[] texts,
                                                string languageCode = "en-US")
        {
            var client = SessionsClient.Create();

            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: new SessionName(projectId, sessionId),
                    queryInput: new QueryInput()
                    {
                        Text = new TextInput()
                        {
                            Text = text,
                            LanguageCode = languageCode
                        }
                    }
                );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
            }

            return 0;
        }

Go

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
	ctx := context.Background()

	sessionClient, err := dialogflow.NewSessionsClient(ctx)
	if err != nil {
		return "", err
	}
	defer sessionClient.Close()

	if projectID == "" || sessionID == "" {
		return "", errors.New(fmt.Sprintf("Received empty project (%s) or session (%s)", projectID, sessionID))
	}

	sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
	textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
	queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
	queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
	request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

	response, err := sessionClient.DetectIntent(ctx, &request)
	if err != nil {
		return "", err
	}

	queryResult := response.GetQueryResult()
	fulfillmentText := queryResult.GetFulfillmentText()
	return fulfillmentText, nil
}

Java

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

/**
 * Returns the result of detect intent with texts as inputs.
 *
 * Using the same `session_id` between requests allows continuation of the conversation.
 * @param projectId Project/Agent Id.
 * @param texts The text intents to be detected based on what a user says.
 * @param sessionId Identifier of the DetectIntent session.
 * @param languageCode Language code of the query.
 */
public static void detectIntentTexts(String projectId, List<String> texts, String sessionId,
    String languageCode) throws Exception {
  // Instantiates a client
  try (SessionsClient sessionsClient = SessionsClient.create()) {
    // Set the session name using the sessionId (UUID) and projectID (my-project-id)
    SessionName session = SessionName.of(projectId, sessionId);
    System.out.println("Session Path: " + session.toString());

    // Detect intents for each text input
    for (String text : texts) {
      // Set the text (hello) and language code (en-US) for the query
      Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

      // Build the query with the TextInput
      QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

      // Performs the detect intent request
      DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

      // Display the query result
      QueryResult queryResult = response.getQueryResult();

      System.out.println("====================");
      System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
      System.out.format("Detected Intent: %s (confidence: %f)\n",
          queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
      System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
    }
  }
}

Node.js

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

// Imports the Dialogflow library
const dialogflow = require('dialogflow');

// Instantiates a sessison client
const sessionClient = new dialogflow.SessionsClient();

if (!queries || !queries.length) {
  return;
}

// The path to identify the agent that owns the created intent.
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

let promise;

// Detects the intent of the queries.
for (const query of queries) {
  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (!promise) {
    // First query.
    console.log(`Sending query "${query}"`);
    promise = sessionClient.detectIntent(request);
  } else {
    promise = promise.then(responses => {
      console.log('Detected intent');
      const response = responses[0];
      logQueryResult(sessionClient, response.queryResult);

      // Use output contexts as input contexts for the next query.
      response.queryResult.outputContexts.forEach(context => {
        // There is a bug in gRPC that the returned google.protobuf.Struct
        // value contains fields with value of null, which causes error
        // when encoding it back. Converting to JSON and back to proto
        // removes those values.
        context.parameters = structjson.jsonToStructProto(
          structjson.structProtoToJson(context.parameters)
        );
      });
      request.queryParams = {
        contexts: response.queryResult.outputContexts,
      };

      console.log(`Sending query "${query}"`);
      return sessionClient.detectIntent(request);
    });
  }
}

promise
  .then(responses => {
    console.log('Detected intent');
    logQueryResult(sessionClient, responses[0].queryResult);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

namespace Google\Cloud\Samples\Dialogflow;

use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;

/**
 * Returns the result of detect intent with texts as inputs.
 * Using the same `session_id` between requests allows continuation
 * of the conversation.
 */
function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US')
{
    // new session
    $sessionsClient = new SessionsClient();
    $session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
    printf('Session path: %s' . PHP_EOL, $session);

    // query for each string in array
    foreach ($texts as $text) {
        // create text input
        $textInput = new TextInput();
        $textInput->setText($text);
        $textInput->setLanguageCode($languageCode);

        // create query input
        $queryInput = new QueryInput();
        $queryInput->setText($textInput);

        // get response and relevant info
        $response = $sessionsClient->detectIntent($session, $queryInput);
        $queryResult = $response->getQueryResult();
        $queryText = $queryResult->getQueryText();
        $intent = $queryResult->getIntent();
        $displayName = $intent->getDisplayName();
        $confidence = $queryResult->getIntentDetectionConfidence();
        $fulfilmentText = $queryResult->getFulfillmentText();

        // output relevant info
        print(str_repeat("=", 20) . PHP_EOL);
        printf('Query text: %s' . PHP_EOL, $queryText);
        printf('Detected intent: %s (confidence: %f)' . PHP_EOL, $displayName,
            $confidence);
        print(PHP_EOL);
        printf('Fulfilment text: %s' . PHP_EOL, $fulfilmentText);
    }

    $sessionsClient->close();
}

Python

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversaion."""
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(
            session=session, query_input=query_input)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))

Ruby

For more on installing and creating a Dialogflow client, refer to Dialogflow Client Libraries.

# project_id = "Your Google Cloud project ID"
# session_id = "mysession"
# texts = "hello", "book a meeting room"]
# language_code = "en-US"

require "google/cloud/dialogflow"

session_client = Google::Cloud::Dialogflow::Sessions.new
session = session_client.class.session_path project_id, session_id
puts "Session path: #{session}"

texts.each do |text|
  query_input = { text: { text: text, language_code: language_code } }
  response = session_client.detect_intent session, query_input
  query_result = response.query_result

  puts "Query text:        #{query_result.query_text}"
  puts "Intent detected:   #{query_result.intent.display_name}"
  puts "Intent confidence: #{query_result.intent_detection_confidence}"
  puts "Fulfillment text:  #{query_result.fulfillment_text}\n"
end

Was this page helpful? Let us know how we did:

Send feedback about...

Dialogflow Enterprise Edition Documentation