从情感分析结果中检测意图

情感分析功能会检查用户输入的内容,并确定其中主导性的主观意见,以确定用户的态度是肯定、否定还是中立的。在发出检测意图请求时,您可以启用情感分析,然后响应就会包含情感分析值。

Dialogflow 使用 Natural Language API 来执行此分析任务。如需详细了解该 API 并阅读关于如何解读 Dialogflow 情感分析结果的文章,请参阅以下内容:

支持的语言

如需查看受支持语言的列表,请参阅语言页面上的情感列。如果您针对不受支持的语言请求情感分析,则检测意图请求不会失败,但 QueryResult.diagnostic_info 字段会包含错误信息。

准备工作

此功能仅适用于使用 API 与最终用户互动的情况。如果您使用的是集成服务,则可以跳过本指南。

在开始之前,请完成以下步骤:

创建代理

  1. 前往 Dialogflow ES 控制台
  2. 如果系统提示,请登录控制台。如需了解详情,请参阅 Dialogflow 控制台概览
  3. 在边栏菜单中,展开加载代理
  4. 点击创建新代理
  5. 输入代理名称、默认语言和默认时区。
  6. 输入现有项目。如需让 Dialogflow 控制台创建项目,请选择创建新 Google 项目
  7. 点击创建

用于情感分析的代理设置

您可以针对每个检测意图请求触发情感分析,也可以将代理配置为始终返回情感分析结果。

要为所有查询启用情感分析,请执行以下操作:

  1. 前往 Dialogflow ES 控制台
  2. 选择一个代理。
  3. 选择代理名称旁边的设置 图标。
  4. 选择高级标签。
  5. 开启针对当前查询启用情感分析

使用 Dialogflow 模拟器

您可以通过 Dialogflow 模拟器与代理进行交互并接收情感分析结果:

  1. 输入“Thank you for helping me”。
  2. 查看模拟器底部的情感 (SENTIMENT) 部分。它显示的是积极的情感得分。
  3. 在模拟器中输入“It didn't work at all”。
  4. 查看模拟器底部的情感 (SENTIMENT) 部分。它显示的是负面情感得分。

检测意图

如需检测意图,请对 Sessions 类型调用 detectIntent 方法。

REST

调用 detectIntent 方法并提供 sentimentAnalysisRequestConfig 字段。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID
  • SESSION_ID:会话 ID。

HTTP 方法和网址:

POST https://dialogflow.googleapis.com/v2/projects/PROJECT_ID/agent/sessions/SESSION_ID:detectIntent

请求 JSON 正文:

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

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

{
  "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
      }
    }
  }
}

请注意,sentimentAnalysisResult 字段包含 scoremagnitude 值。

Java

如需向 Dialogflow CX 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryParameters;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SentimentAnalysisRequestConfig;
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 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 =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

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

        //
        SentimentAnalysisRequestConfig sentimentAnalysisRequestConfig =
            SentimentAnalysisRequestConfig.newBuilder().setAnalyzeQueryTextSentiment(true).build();

        QueryParameters queryParameters =
            QueryParameters.newBuilder()
                .setSentimentAnalysisRequestConfig(sentimentAnalysisRequestConfig)
                .build();
        DetectIntentRequest detectIntentRequest =
            DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build();

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

        // 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");
        System.out.format(
            "Sentiment Score: '%s'\n",
            queryResult.getSentimentAnalysisResult().getQueryTextSentiment().getScore());

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

Node.js

如需向 Dialogflow CX 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

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');
    console.log(
      `  Score: ${result.sentimentAnalysisResult.queryTextSentiment.score}`
    );
    console.log(
      `  Magnitude: ${result.sentimentAnalysisResult.queryTextSentiment.magnitude}`
    );
  } else {
    console.log('No sentiment Analysis Found');
  }

Python

如需向 Dialogflow CX 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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 google.cloud 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(
            analyze_query_text_sentiment=True
        )

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

        response = session_client.detect_intent(
            request={
                "session": session_path,
                "query_input": query_input,
                "query_params": query_params,
            }
        )

        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))
        # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
        print(
            "Query Text Sentiment Score: {}\n".format(
                response.query_result.sentiment_analysis_result.query_text_sentiment.score
            )
        )
        print(
            "Query Text Sentiment Magnitude: {}\n".format(
                response.query_result.sentiment_analysis_result.query_text_sentiment.magnitude
            )
        )