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

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

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

支持的语言

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

准备工作

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

在阅读本指南之前,请先完成以下事项:

  1. 阅读 Dialogflow 基础知识
  2. 执行设置步骤

创建代理

如果尚未创建代理,请立即创建一个:

  1. 转到 Dialogflow ES 控制台
  2. 如果系统要求登录 Dialogflow 控制台,请登录。如需了解详情,请参阅 Dialogflow 控制台概览
  3. 点击左侧边栏菜单中的创建代理 (Create Agent)。如果您已有其他代理,请点击代理名称,滚动到底部,然后点击创建新代理 (Create new agent)。
  4. 输入您的代理名称、默认语言和默认时区。
  5. 如果您已经创建了项目,请输入该项目。如果要允许 Dialogflow 控制台创建项目,请选择创建新 Google 项目 (Create a new Google project)。
  6. 点击创建 (Create) 按钮。

将示例文件导入代理

本指南中的步骤对您的代理进行了假设,因此您需要import为本指南准备的代理。 导入时,这些步骤使用“恢复”(restore) 选项,该选项会覆盖所有代理设置、意图和实体。

如需导入文件,请按以下步骤操作:

  1. 下载 room-booking-agent.zip 文件。
  2. 转到 Dialogflow ES 控制台
  3. 选择您的代理。
  4. 点击代理名称旁边的设置 按钮。
  5. 选择导出和导入标签页。
  6. 选择从 ZIP 文件恢复 (Restore from ZIP),然后按照说明恢复下载的 zip 文件。

用于情感分析的代理设置

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

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

  1. 转到 Dialogflow ES 控制台
  2. 选择一个代理。
  3. 点击代理名称旁边的设置 按钮。
  4. 选择高级 (Advanced) 标签页。
  5. 打开针对当前查询启用情感分析 (Enable sentiment analysis for the current query)。

使用 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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// 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 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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
            )
        )