/* */

Detect sentiment with your Bot using Text Analytics

One of the things you can do with the Text Analytics API, is the ability to recognise sentiment. This simply means that this API is able to detect if a piece of text has a positive or a negative feeling. Since our bot mainly gets it’s input from text, we can use the Text API to validate if the user is happy or not. Just like with the other Cognitive Services, it’s really simple to tap into this form of AI!

The goal


We’ll expand on our mfRestaurantBot and check if the user is satisfied about the food. I’ve added an Intent to LUIS that asks the user to rate it by asking what they thought. Based on their sentiment, we’ll determine if the user is happy or not. When we have that information, we can take further actions or not.

Requirements

To achieve our goal, we’ll need to get a couple of things first:

Once you’re sure you got all these requirements, we’re ready to proceed to the next step.

API Key

We’ll need to create the Text Analytics API and get the API key in order to use it. Head over to the Azure Portal and Create a new Service. Search the Marketplace for Text Analytics API and create the service. Fill in all the required fields and create the service.

Now that we have our service, we’ll need to search for our API Key. Simply open it up and find your API Key under Show access keys. Copy it and store it for later.

The TextAnalyticsService

I added a class to the project called TextAnalyticsService that wraps around the functionality from the SentimentClient from Cognitive Services and only returns what we currently need.


public static class TextAnalyticsService
{
    private static string TEXT_ANALYTICS_KEY
        = "<TEXT_ANALYTICS_KEY>";

    private static SentimentClient _client
        = new SentimentClient(TEXT_ANALYTICS_KEY);
        
    public static async Task<float> DetermineSentimentAsync(string sentence)
    {
        var request = new SentimentRequest();
        request.Documents.Add(new SentimentDocument()
        {
            Id = Guid.NewGuid().ToString(), // Random Identifier
            Text = sentence,
            Language = "en"
        });

        var result = await _client.GetSentimentAsync(request);

        // Since we only send one document, we expect only one document back
        return result.Documents.First().Score;
    }
}

Take note of the <TEXT_ANALYTICS_KEY> and change that accordingly to the API Key we got in our previous step. As you can see, we need to create a SentimentDocument which will hold the Text. It’s Language is set to English, but there are many other languages supported. The service returns a float between 0 (negative sentiment) and 1 (positive sentiment).

Calling the service

Now that we’re able to call the Text Analytics API to detect sentiment, we’ll integrate this in our bot. Simply use PromptDialog to ask the user for input and detect their sentiment.


[LuisIntent("RateFood")]
public async Task RateFood(IDialogContext context, LuisResult result)
{
    PromptDialog.Text(context, ResumeAfterRateFoodClarification, "What did you think of our food?");
}

private async Task ResumeAfterRateFoodClarification(IDialogContext context, IAwaitable<string> result)
{
    var sentence = await result;
    var sentiment = await TextAnalyticsService.DetermineSentimentAsync(sentence);
    await context.PostAsync($"You rated our food: {Math.Round(sentiment * 10, 1)}/10");

    if(sentiment < 0.5)
    {
        PromptDialog.Confirm(context, ResumeAfterFeedbackClarification,
            "I see it wasn't perfect, can we contact you about this?");
    }
}

private async Task ResumeAfterFeedbackClarification(IDialogContext context, IAwaitable<bool> result)
{
    var confirmation = await result;
    await context.PostAsync(confirmation ? "We'll call you!" : "We won't contact you.");
}

Here you see we check if the sentiment has a score lower than 0.5. If so, we assume the user isn’t happy about the food and we request if we can contact them about it.

Result

Let’s see that in action! When we run this bot, let’s see if it’s actually doing what we expect it to do with different sentences.

Positive sentiment

Medium sentiment

Negative sentiment

Conclusion

We managed to realise our goal and get a bot to recognise sentiment. This is a really simple yet powerful form to see how the user feels and react to that. Think about a chat take-over by a human when the sentiment is really low to make sure the bot doesn’t make wrong decisions on it’s own. I hope this sample inspires to get you started! Take not that the Text Analytics API is still in beta but it’s powerful enough to use. Let me know what you think in the comments below or on Twitter.

2 comments On Detect sentiment with your Bot using Text Analytics

Leave a reply:

Your email address will not be published.

Site Footer