Quickstart: Interactions with the API

This quickstart shows you how to interact with an agent by using the REST API at the command line and by using the client libraries.

Before you begin

If you do not plan on using the API, you can skip this quickstart.

You should do the following before reading this guide:

  1. Understand Dialogflow basics.
  2. Perform setup steps.
  3. Learn how to build an agent.

Create an agent

The steps in this guide make assumptions about your agent, so it's best to start with a new agent. You should delete any existing agent for your project before creating a new one. To delete an existing agent:

  1. Go to the Dialogflow Console.
  2. If requested, sign in to the Dialogflow Console. See Dialogflow console overview for more information.
  3. Select the agent you wish to delete.
  4. Click the settings settings button next to the agent's name.
  5. Scroll down to the bottom of the General settings tab.
  6. Click Delete this agent.
  7. Enter DELETE in the text field.
  8. Click Delete.

To create an agent:

  1. Go to the Dialogflow Console.
  2. If requested, sign in to the Dialogflow Console. See Dialogflow console overview for more information.
  3. Click Create Agent in the left sidebar menu. (If you already have other agents, click the agent name, scroll to the bottom and click Create new agent.)
  4. Enter your agent's name, default language, and default time zone.
  5. If you have already created a project, enter that project. If you want to allow the Dialogflow Console to create the project, select Create a new Google project.
  6. Click the Create button.

Import the example file to your agent

Importing will add intents and entities to your agent. If any existing intents or entities have the same name as those in the imported file, they will be replaced.

To import the file, follow these steps:

  1. Download the RoomReservation.zip file
  2. Go to the Dialogflow Console
  3. Select your agent
  4. Click the settings settings button next to the agent name
  5. Select the Export and Import tab
  6. Select Import From Zip and import the zip file that you downloaded

Sessions

A session represents a conversation between a Dialogflow agent and an end-user. You create a session at the beginning of a conversation and use it for each turn of the conversation. Once the conversation has ended, you discontinue using the session.

You should not use the same session for concurrent conversations with different end-users. Dialogflow maintains the currently active contexts for each active session. Session data is stored by Dialogflow for 20 minutes.

Each session is determined unique by a session ID generated by your system. You create a new session by providing a new session ID in a detect intent request. A session ID is a string of at most 36 bytes in size. Your system is responsible for generating unique session IDs. They can be random numbers, hashed end-user identifiers, or any other values that are convenient for you to generate.

Detect intent

When you use the API for interactions, your service interacts directly with the end-user. For each conversational turn, your service sends end-user expressions to Dialogflow by calling the detectIntent or streamingDetectIntent method of the Sessions type. Dialogflow responds with information about the matched intent, the action, the parameters, and the response defined for the intent. Your service performs actions as needed (for example, database queries or external API calls) and sends a message to the end-user. This process continues until the conversation has ended.

The agent imported in steps above is a simple room reservation agent. To examine the intents, visit the Dialogflow Console and select your new agent.

The following samples show how to detect intent. Each sample accepts a subset of the following inputs:

  • Project ID: Use the project ID for the project you created in the setup steps.
  • Session ID: For the purpose of testing an agent, you can use anything. For example, "123456789" is frequently used by samples.
  • Text or texts: This is the single end-user expression or list of end-user expressions. If multiple expressions are supplied, the sample code calls detect intent for each expression. Try using "reserve a meeting room for six people".
  • Language code: The language code for the end-user expression. Use "en-US" for this example agent.

REST & CMD LINE

To detect intent, call the detectIntent method on the Sessions resource.

Before using any of the request data below, make the following replacements:

  • project-id: your GCP project ID
  • session-id: a session ID

HTTP method and URL:

POST https://dialogflow.googleapis.com/v2/projects/project-id/agent/sessions/session-id:detectIntent

Request JSON body:

{
  "query_input": {
    "text": {
      "text": "reserve a meeting room for six people",
      "language_code": "en-US"
    }
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "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?"
          ]
        }
      }
    ],
    "outputContexts": [
      ...
    ],
    "intent": {
      "name": "projects/project-id/agent/intents/e8f6a63e-73da-4a1a-8bfc-857183f71228",
      "displayName": "room.reservation"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": "en-us"
  }
}

Note the following about the response:

  • The value of the queryResult.action field is "room.reservation". This matches the action field for the matched intent.
  • The value of the queryResult.parameters.guests field is 6. This parameter value was extracted from the end-user expression: "reserve a meeting room for six people".
  • The value of the queryResult.fulfillmentMessages[0|1].text.text[0] field asks the user for more information. This is the response that your system should forward to the end-user.

C#

        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}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
            }

            return 0;
        }

Go

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


/**
 * 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.
 * @return The QueryResult for each input text.
 */
public static Map<String, QueryResult> detectIntentTexts(
    String projectId,
    List<String> texts,
    String sessionId,
    String languageCode) throws Exception {
  Map<String, QueryResult> queryResults = Maps.newHashMap();
  // 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());

      queryResults.put(text, queryResult);
    }
  }
  return queryResults;
}

Node.js


/**
 * TODO(developer): UPDATE these variables before running the sample.
 */
// projectId: ID of the GCP project where Dialogflow agent is deployed
// const projectId = 'PROJECT_ID';
// sessionId: Random number or hashed user identifier
// const sessionId = 123456;
// queries: A set of sequential queries to be send to Dialogflow agent for Intent Detection
// const queries = [
//   'Reserve a meeting room in Toronto office, there will be 5 of us',
//   'Next monday at 3pm for 1 hour, please', // Tell the bot when the meeting is taking place
//   'B'  // Rooms are defined on the Dialogflow agent, default options are A, B, or C
// ]
// languaceCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

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

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

async function detectIntent(
  projectId,
  sessionId,
  query,
  contexts,
  languageCode
) {
  // The path to identify the agent that owns the created intent.
  const sessionPath = sessionClient.sessionPath(projectId, sessionId);

  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
      },
    },
  };

  if (contexts && contexts.length > 0) {
    request.queryParams = {
      contexts: contexts,
    };
  }

  const responses = await sessionClient.detectIntent(request);
  return responses[0];
}

async function executeQueries(projectId, sessionId, queries, languageCode) {
  // Keeping the context across queries let's us simulate an ongoing conversation with the bot
  let context;
  let intentResponse;
  for (const query of queries) {
    try {
      console.log(`Sending Query: ${query}`);
      intentResponse = await detectIntent(
        projectId,
        sessionId,
        query,
        context,
        languageCode
      );
      console.log('Detected intent');
      console.log(
        `Fulfillment Text: ${intentResponse.queryResult.fulfillmentText}`
      );
      // Use the context from this response for next queries
      context = intentResponse.queryResult.outputContexts;
    } catch (error) {
      console.log(error);
    }
  }
}
executeQueries(projectId, sessionId, queries, languageCode);

PHP

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

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 conversation."""
    import dialogflow_v2 as dialogflow
    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

# 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 Documentation
Need help? Visit our support page.