Adding Sentiment Analysis to Detect Intent Requests

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:

Set up your GCP project and authentication

Create an agent

Import the example intents and entities

Enable beta features

You may need to enable the beta API:

  1. Go to the Dialogflow console.

  2. Select an agent.

  3. Click the gear icon settings next to the agent name.

  4. Scroll down while on the General tab and ensure that BETA FEATURES is enabled.

  5. If you have made changes, click SAVE.

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.

Here are the agent settings for sentiment analysis:

  • Enable sentiment analysis for current query: Sentiment analysis results are triggered for each query.

To access agent settings for sentiment analysis:

  1. Go to the Dialogflow console.

  2. Select an agent.

  3. Click the gear icon settings next to the agent name.

  4. Select the Advanced tab.

Use the Dialogflow simulator

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

  1. Type "please reserve an amazing meeting room for six people" in the simulator.

  2. See the SENTIMENT section at the bottom of the simulator.

Detect intent

curl command

  1. Use the following curl command to call the detectIntent method and provide the sentimentAnalysisRequestConfig field. Replace project-id with your Google Cloud project ID. The command uses the gcloud command-line interface from the Google Cloud SDK to get an authorization token.

    curl -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
         -H "Content-Type: application/json; charset=utf-8" --data "{
      'queryParams': {
        'sentimentAnalysisRequestConfig': {
          'analyzeQueryTextSentiment': true
      'queryInput': {
        'text': {
          'text': 'please reserve an amazing meeting room for six people',
          'languageCode': 'en-US'
    }" ""
  2. You should see a response similar to the following. Notice that the sentimentAnalysisResult field contains score and magnitude values.

      "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


 * Returns the result of detect intent with texts as inputs.
 * <p>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 text in query.
public static Map<String, QueryResult>  detectIntentSentimentAnalysis(
    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();

      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());
      System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
          "Sentiment Score: '%s'\n",

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


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

// 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.sessionPath(projectId, sessionId);

// 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: ${
} else {
  console.log(`No sentiment Analysis Found`);


def detect_intent_with_sentiment_analysis(project_id, session_id, texts,
    """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."""
    import dialogflow_v2beta1 as 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.types.TextInput(
            text=text, language_code=language_code)

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

        # Enable sentiment analysis
        sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig(

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

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

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

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

Send feedback about...

Dialogflow Enterprise Edition Documentation