Dialogflow Client Libraries

This page shows how to get started with the new Cloud Client Libraries for the Dialogflow V2 API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

Java

If you are using Maven, add this to your pom.xml file:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-dialogflow</artifactId>
    <version>0.29.0-alpha</version>
</dependency>

Node.js

npm install --save dialogflow@0.1.0

Python

For more on setting up your Python development environment, refer to Python Development Environment Setup Guide.
pip install --upgrade dialogflow==0.1.0

Using the client library

To run the client library, you must first set up authentication.

The following example shows how to use the client library.

Java

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());
    }
  }
}
Read more in the Java API Reference Documentation for the Dialogflow V2 API Client Library.

Node.js

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);
  });
Read more in the Node.js API Reference Documentation for the Dialogflow V2 API Client Library.

Python

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))
Read more in the Python API Reference Documentation for the Dialogflow V2 API Client Library.

Additional Resources

Send feedback about...

Google Dialogflow Enterprise Edition