Quickstart: Interactions with the API

If you are not using an integration, you must write code to interact with end-users. For each conversational turn, your code calls the Dialogflow API to query your agent. This guide 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. Perform steps in the Build an agent quickstart guide. Steps below continue working on the agent you started in that guide. If you no longer have that agent, you can download build-agent-quickstart.zip and import the file.

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 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 "I know french".
  • Language code: The language code for the end-user expression. Use "en-US" for this example agent.

REST

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

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

  • PROJECT_ID: your Google Cloud 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": "I know french",
      "language_code": "en-US"
    }
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "responseId": "856510ca-f617-4e25-b0bb-a26c0a59e030-19db3199",
  "queryResult": {
    "queryText": "I know french",
    "parameters": {
      "language": "French",
      "language-programming": ""
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Wow! I didn't know you knew French. How long have you known French?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Wow! I didn't know you knew French. How long have you known French?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/PROJECT_ID/agent/sessions/123456789/contexts/set-language-followup",
        "lifespanCount": 2,
        "parameters": {
          "language": "French",
          "language.original": "french",
          "language-programming": "",
          "language-programming.original": ""
        }
      }
    ],
    "intent": {
      "name": "projects/PROJECT_ID/agent/intents/fe45022f-e58a-484f-96e8-1cbd6628f648",
      "displayName": "set-language"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  }
}

Note the following about the response:

  • The queryResult.intent field contains the matched intent.
  • The value of the queryResult.fulfillmentMessages field contains the intent response. This is the response that your system should forward to the end-user.
  • The value of the queryResult.parameters field contains the parameters extracted from the end-user expression.
  • The queryResult.outputContext field contains the active context.

Go

To authenticate to Dialogflow, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To authenticate to Dialogflow, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntentTexts {

  // DialogFlow API Detect Intent sample with text inputs.
  public static Map<String, QueryResult> detectIntentTexts(
      String projectId, List<String> texts, String sessionId, String languageCode)
      throws IOException, ApiException {
    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
        TextInput.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.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");

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

Node.js

To authenticate to Dialogflow, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


/**
 * 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: String representing a 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
// ]
// languageCode: Indicates the language Dialogflow agent should use to detect intents
// const languageCode = 'en';

// Imports the Dialogflow library
const dialogflow = require('@google-cloud/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.projectAgentSessionPath(
    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);

Python

To authenticate to Dialogflow, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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."""
    from google.cloud import 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.TextInput(text=text, language_code=language_code)

        query_input = dialogflow.QueryInput(text=text_input)

        response = session_client.detect_intent(
            request={"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))

Additional languages

C#: Please follow the C# setup instructions on the client libraries page and then visit the Dialogflow reference documentation for .NET.

PHP: Please follow the PHP setup instructions on the client libraries page and then visit the Dialogflow reference documentation for PHP.

Ruby: Please follow the Ruby setup instructions on the client libraries page and then visit the Dialogflow reference documentation for Ruby.

Productionization

Before running your agent in production, be sure to implement the productionization best practices.