감정 분석과 함께 인텐트 인식

감정 분석은 사용자 입력을 검사하고 전반적인 주관적 의견을 파악하여 특히 사용자의 태도가 긍정적인지, 부정적인지, 중립적인지를 판단합니다. 인텐트 감지 요청을 할 때 감정 분석을 수행하도록 지정하면 응답에 감정 분석 값이 포함됩니다.

Dialogflow에서 감정 분석을 수행하는 데 Natural Language API를 사용합니다. Natural Language API 및 Dialogflow 감정 분석 결과 해석 문서에 대한 자세한 내용은 다음을 참조하세요.

지원 언어

지원되는 언어 목록은 언어 페이지에서 감정 열을 참조하세요. 지원되지 않는 언어에 대한 감정 분석을 요청할 경우 인텐트 감지 요청은 실패하지 않지만 QueryResult.diagnostic_info 필드에 오류 정보가 포함됩니다.

시작하기 전에

이 기능은 최종 사용자 상호작용에 API를 사용할 때만 적용됩니다. 통합을 사용 중인 경우 이 가이드를 건너뛸 수 있습니다.

이 가이드를 읽기 전에 다음을 수행해야 합니다.

  1. Dialogflow 기본사항 읽기
  2. 설정 단계 수행

에이전트 만들기

아직 에이전트를 만들지 않은 경우 지금 만듭니다.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 로그인 메시지가 표시되면 Dialogflow 콘솔에 로그인합니다. 자세한 내용은 Dialogflow 콘솔 개요를 참조하세요.
  3. 왼쪽 사이드바 메뉴에서 에이전트 만들기를 클릭합니다. 이미 다른 에이전트가 있는 경우 에이전트 이름을 클릭하고 아래로 스크롤하여 새 에이전트 만들기를 클릭합니다.
  4. 에이전트 이름, 기본 언어, 기본 시간대를 입력합니다.
  5. 프로젝트를 이미 만든 경우 해당 프로젝트를 입력합니다. Dialogflow 콘솔이 프로젝트를 만들 수 있게 하려면 새 Google 프로젝트 만들기를 선택하세요.
  6. 만들기 버튼을 클릭합니다.

에이전트로 예시 파일 가져오기

이 가이드의 단계에서는 에이전트가 있다고 가정하므로 이 가이드를 위해 준비된 에이전트를 가져와야 합니다. 이 단계에서는 가져올 때 모든 에이전트 설정, 인텐트, 항목을 덮어쓰는 restore 옵션을 사용합니다.

파일을 가져오려면 다음 단계를 따르세요.

  1. room-booking-agent.zip 파일을 다운로드합니다.
  2. Dialogflow ES 콘솔로 이동합니다.
  3. 에이전트를 선택합니다.
  4. 에이전트 이름 옆에 있는 설정 버튼을 클릭합니다.
  5. 내보내기 및 가져오기 탭을 선택합니다.
  6. ZIP 파일에서 복원을 선택하고 안내에 따라 다운로드한 ZIP 파일을 복원합니다.

감정 분석용 에이전트 설정

인텐트 감지 요청당 감정 분석을 트리거하거나 항상 감정 분석 결과를 반환하도록 에이전트를 구성할 수 있습니다.

모든 쿼리에 감정 분석을 사용 설정하려면 다음 안내를 따르세요.

  1. Dialogflow ES 콘솔로 이동합니다.
  2. 에이전트를 선택합니다.
  3. 에이전트 이름 옆에 있는 설정 버튼을 클릭합니다.
  4. 고급 탭을 선택합니다.
  5. 현재 쿼리에 감정 분석 사용 설정을 사용으로 전환합니다.

Dialogflow 시뮬레이터 사용

Dialogflow 시뮬레이터를 사용하면 에이전트와 상호작용하고 감정 분석 결과를 제공받을 수 있습니다.

  1. 'Thank you for helping me.'라고 입력합니다.

  2. 시뮬레이터 하단의 감정 섹션을 확인합니다. 긍정적인 감정 점수가 표시되어야 합니다.

  3. 다음으로, 시뮬레이터에 'It didn't work at all.'을 입력합니다.

  4. 시뮬레이터 하단의 감정 섹션을 확인합니다. 부정적인 감정 점수가 표시되어야 합니다.

인텐트 감지

인텐트를 감지하려면 Sessions 유형에서 detectIntent 메서드를 호출합니다.

REST

detectIntent 메서드를 호출하고 sentimentAnalysisRequestConfig 필드를 확인합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID
  • SESSION_ID: 세션 ID

HTTP 메서드 및 URL:

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

CTS에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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