זיהוי כוונות באמצעות ניתוח סנטימנטים

ניתוח סנטימנטים בודק את הקלט של המשתמש ומזהה את הדעה הסובייקטיבית הרווחת כדי לקבוע את הגישה של המשתמש כחיובית, שלילית או ניטרלית. כששולחים בקשה לזיהוי כוונות, אפשר להפעיל ניתוח סנטימנטים, והתשובה תכיל ערכים של ניתוח סנטימנטים.

‫Dialogflow משתמש ב-Natural Language API כדי לבצע את הניתוח הזה. מידע נוסף על ממשק ה-API ומסמכים על פירוש תוצאות ניתוח הסנטימנט של Dialogflow זמין במקורות הבאים:

שפות נתמכות

רשימת השפות הנתמכות מופיעה בעמודה סנטימנט בדף שפות. אם תבקשו ניתוח סנטימנט בשפה שלא נתמכת, בקשת זיהוי הכוונה לא תיכשל, אבל השדה QueryResult.diagnostic_info יכיל מידע על השגיאה.

לפני שמתחילים

התכונה הזו רלוונטית רק כשמשתמשים ב-API עבור אינטראקציות עם משתמשי קצה. אם אתם משתמשים בשילוב, אתם יכולים לדלג על המדריך הזה.

לפני שמתחילים, צריך לבצע את השלבים הבאים:

יצירת סוכן

  1. עוברים אל מסוף Dialogflow ES.
  2. נכנסים למסוף אם מוצגת בקשה לכך. מידע נוסף זמין בסקירה הכללית על מסוף Dialogflow.
  3. בתפריט שבסרגל הצד, מרחיבים את האפשרות סוכני טעינה.
  4. לוחצים על יצירת סוכן חדש.
  5. מזינים את שם הסוכן, שפת ברירת המחדל ואזור הזמן שמוגדר כברירת מחדל.
  6. מזינים פרויקט קיים. כדי לאפשר למסוף Dialogflow ליצור פרויקט, בוחרים באפשרות Create a new Google project (יצירת פרויקט חדש ב-Google).
  7. לוחצים על יצירה.

הגדרות הסוכן לניתוח סנטימנטים

אתם יכולים להפעיל ניתוח סנטימנט לכל בקשה לזיהוי כוונות, או להגדיר את הסוכן כך שתמיד יחזיר תוצאות של ניתוח סנטימנט.

כדי להפעיל ניתוח סנטימנט לכל השאילתות:

  1. עוברים אל מסוף Dialogflow ES.
  2. בוחרים נציג תמיכה.
  3. לוחצים על סמל ההגדרות לצד שם הסוכן.
  4. בוחרים בכרטיסייה מתקדם.
  5. מפעילים את האפשרות הפעלת ניתוח סנטימנט לשאילתה הנוכחית.

שימוש בסימולטור של Dialogflow

אתם יכולים ליצור אינטראקציה עם הסוכן ולקבל תוצאות של ניתוח סנטימנט באמצעות הסימולטור של Dialogflow:

  1. מזינים את ההנחיה "תודה שעזרת לי".
  2. בתחתית הסימולטור, מעיינים בקטע SENTIMENT (סנטימנט). הוא מציג ציון חיובי של סנטימנט.
  3. מזינים בסימולטור את הערך 'It didn't work at all' (הוא לא פעל בכלל).
  4. בתחתית הסימולטור, מעיינים בקטע SENTIMENT (סנטימנט). הציון של הסנטימנט שלילי.

זיהוי כוונות

כדי לזהות כוונות, מבצעים קריאה ל-method‏ detectIntent בסוג Sessions.

REST

מבצעים קריאה ל-detectIntent ומזינים את השדה sentimentAnalysisRequestConfig.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב-Google Cloud
  • SESSION_ID: מזהה סשן

ה-method של ה-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 מכיל את הערכים score ו-magnitude.

Java

כדי לבצע אימות ב-Dialogflow CX, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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