Detect intent with sentiment analysis

Sentiment analysis inspects user input and identifies the prevailing subjective opinion, especially to determine a user's attitude as positive, negative, or neutral. When making a detect intent request, you can specify that sentiment analysis be performed, and the response will contain sentiment analysis values.

The Natural Language API is used by Dialogflow to perform this analysis. For more information on that API and documentation on interpreting Dialogflow sentiment analysis results:

Supported languages

For a list of supported languages, see the sentiment column on the languages page. If you request sentiment analysis for an unsupported language, your detect intent request does not fail, but the QueryResult.diagnostic_info field contains error information.

Before you begin

This feature is only applicable when using the API for end-user interactions. If you are using an integration, you can skip this guide.

You should do the following before reading this guide:

  1. Read Dialogflow basics.
  2. Perform setup steps.

Create an agent

If you have not already created an agent, create one now:

  1. Go to the Dialogflow ES 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

The steps in this guide make assumptions about your agent, so you need to import an agent prepared for this guide. When importing, these steps use the restore option, which overwrites all agent settings, intents, and entities.

To import the file, follow these steps:

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

Agent settings for sentiment analysis

You can trigger sentiment analysis per detect intent request, or you can configure your agent to always return sentiment analysis results.

To enable sentiment analysis for all queries:

  1. Go to the Dialogflow ES Console.
  2. Select an agent.
  3. Click the settings button next to the agent name.
  4. Select the Advanced tab.
  5. Toggle Enable sentiment analysis for the current query on.

Use the Dialogflow simulator

You can interact with the agent and receive sentiment analysis results via the Dialogflow simulator:

  1. Type "Thank you for helping me."

  2. See the SENTIMENT section at the bottom of the simulator. It should show a positive sentiment score.

  3. Next, type "It didn't work at all." in the simulator.

  4. See the SENTIMENT section at the bottom of the simulator. It should show a negative sentiment score.

Detect intent

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


Call the detectIntent method and provide the sentimentAnalysisRequestConfig field.

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:


Request JSON body:

  "queryParams": {
    "sentimentAnalysisRequestConfig": {
      "analyzeQueryTextSentiment": true
  "queryInput": {
    "text": {
      "text": "please reserve an amazing meeting room for six people",
      "languageCode": "en-US"

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

  "responseId": "747ee176-acc5-46be-8d9a-b7ef9c2b9199",
  "queryResult": {
    "queryText": "please reserve an amazing meeting room for six people",
    "action": "room.reservation",
    "parameters": {
      "date": "",
      "duration": "",
      "guests": 6,
      "location": "",
      "time": ""
    "fulfillmentText": "I can help with that. Where would you like to reserve a room?",
    "sentimentAnalysisResult": {
      "queryTextSentiment": {
        "score": 0.8,
        "magnitude": 0.8

Notice that the sentimentAnalysisResult field contains score and magnitude values.


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

import java.util.List;
import java.util.Map;

public class DetectIntentWithSentimentAnalysis {

  public static Map<String, QueryResult> detectIntentSentimentAnalysis(
      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 =

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

        SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig =

        QueryParameters queryParameters =
        DetectIntentRequest detectIntentRequest =

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(detectIntentRequest);

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

        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
            "Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
            "Fulfillment Text: '%s'\n",
            queryResult.getFulfillmentMessagesCount() > 0
                ? queryResult.getFulfillmentMessages(0).getText()
                : "Triggered Default Fallback Intent");
            "Sentiment Score: '%s'\n",

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


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

// Imports the Dialogflow client library
const dialogflow = require('@google-cloud/dialogflow').v2;

// Instantiate a DialogFlow client.
const sessionClient = new dialogflow.SessionsClient();

 * TODO(developer): Uncomment the following lines before running the sample.
// const projectId = 'ID of GCP project associated with your Dialogflow agent';
// const sessionId = `user specific ID of session, e.g. 12345`;
// const query = `phrase(s) to pass to detect, e.g. I'd like to reserve a room for six people`;
// const languageCode = 'BCP-47 language code, e.g. en-US';

// Define session path
const sessionPath = sessionClient.projectAgentSessionPath(

async function detectIntentandSentiment() {
  // The text query request.
  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: query,
        languageCode: languageCode,
    queryParams: {
      sentimentAnalysisRequestConfig: {
        analyzeQueryTextSentiment: true,

  // Send request and log result
  const responses = await sessionClient.detectIntent(request);
  console.log('Detected intent');
  const result = responses[0].queryResult;
  console.log(`  Query: ${result.queryText}`);
  console.log(`  Response: ${result.fulfillmentText}`);
  if (result.intent) {
    console.log(`  Intent: ${result.intent.displayName}`);
  } else {
    console.log('  No intent matched.');
  if (result.sentimentAnalysisResult) {
    console.log('Detected sentiment');
      `  Score: ${result.sentimentAnalysisResult.queryTextSentiment.score}`
      `  Magnitude: ${result.sentimentAnalysisResult.queryTextSentiment.magnitude}`
  } else {
    console.log('No sentiment Analysis Found');


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

def detect_intent_with_sentiment_analysis(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs and analyzes the
    sentiment of the query text.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    from import dialogflow

    session_client = dialogflow.SessionsClient()

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

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

        query_input = dialogflow.QueryInput(text=text_input)

        # Enable sentiment analysis
        sentiment_config = dialogflow.SentimentAnalysisRequestConfig(

        # Set the query parameters with sentiment analysis
        query_params = dialogflow.QueryParameters(

        response = session_client.detect_intent(
                "session": session_path,
                "query_input": query_input,
                "query_params": query_params,

        print("=" * 20)
        print("Query text: {}".format(response.query_result.query_text))
            "Detected intent: {} (confidence: {})\n".format(
        print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
        # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
            "Query Text Sentiment Score: {}\n".format(
            "Query Text Sentiment Magnitude: {}\n".format(