Sentiments Analysis using Salesforce Einstein API

Sentiments Analysis using Salesforce Einstein API

In continuation of the series of Salesforce Einstein posts, this post will explain the basic steps and prerequisites required to leverage salesforce Language API to describe the Sentiments of the text.

The Einstein Sentiments API helps the user to decide if the summary of the body of the text is positive or negative without going through the text.

Pre Requisite :

1) Sign Up for Einstein Platform Services Account:
 Copy and paste this link to create an Einstein Platform services account

Click on Sign Up using Salesforce.

log in using your Salesforce credentials

Click on allow and then click download to save the einstein_platform.pem file.

2) Upload the key to Salesforce Files.

Navigate to files tab in sales application and then click upload. select the file downloaded in step 1 and click on done.

3) Create a remote site setting:

Log in to Salesforce.
From Setup, enter Remote Site in the Quick Find box, then select Remote Site Settings.
Click New Remote Site.
Enter a name for the remote site.
In the Remote Site URL field, enter
Click Save.

similarly, create one more remote site setting with as the site url

4) Create Apex Classes:

Clone two apex classes (JWT.apex and JWTBearer.apex) from the repository

In Salesforce, from Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Click New.
To create the JWT Apex class, copy all the code from JWT.apex into the Apex Class tab and click Save.
To create the JWTBearerFlow Apex class, go back to to the Apex Classes page, and click New.
Copy all the code from JWTBearer.apex to the Apex Class tab and click Save.

This completes the prerequisites for sentiment analysis.
Now let us begin and create a Visualforce page and controller which could be used to predict the sentiments.

copy and paste the code to create two classes as mentioned below:

global class SentimentAnalysisResponse {
    webservice List<Probabilities> probabilities    { get; set; } 
    global class Probabilities {
        webservice String label                     { get; set; } 
        webservice Double probability               { get; set; }

Controller :
public class EinsteinAPI {
public string TextToPredict {get;set;}
public SentimentAnalysisResponse resp{get;set;}    
    public EinsteinAPI (){
    public void checkSentiments() {
        resp = findSentiment(TextToPredict );
    public String getAccessToken() {
        ContentVersion base64Content = [
            SELECT  Title
            FROM    ContentVersion
            WHERE   Title = 'einstein_platform'
            OR      Title = 'predictive_services'
            ORDER BY Title
            LIMIT 1
        String keyContents  = base64Content.VersionData.tostring();
        keyContents         = keyContents.replace( '-----BEGIN RSA PRIVATE KEY-----', '' );
        keyContents         = keyContents.replace( '-----END RSA PRIVATE KEY-----', '' );
        keyContents         = keyContents.replace( '\n', '' );

        JWT jwt             = new JWT( 'RS256' );
        jwt.pkcs8           = keyContents; 
        jwt.iss             = '';
        jwt.sub             = 'Saurabh.dua@XXX.XXX'; // Update with your own email ID
        jwt.aud             = '';
        jwt.exp             = String.valueOf(3600);
        String access_token = JWTBearerFlow.getAccessToken( '', jwt );
        return access_token;
     * This method is created to make call
     * to the Sentiment Endpoint and get 
     * the Sentiment of the block of text.
     * @param       text                        Block of text whose Sentiment has to be analysed
     * @return      SentimentAnalysisResponse   Returns an instance of SentimentAnalysisResponse class
    public SentimentAnalysisResponse findSentiment( String text ) {
        String key = getAccessToken();
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod( 'POST' );
        req.setEndpoint( '');
        req.setHeader( 'Authorization', 'Bearer ' + key );
        req.setHeader( 'Content-type', 'application/json' );
        String body = '{\"modelId\":\"CommunitySentiment\",\"document\":\"' + text + '\"}';
        req.setBody( body );
        HTTPResponse res = http.send( req );
        SentimentAnalysisResponse resp = ( SentimentAnalysisResponse ) JSON.deserialize( res.getBody(), SentimentAnalysisResponse.class );
        return resp;


Visualforce page code :

<apex:page controller="EinsteinAPI">
<apex:form >
    <b>Enter the Text for analysis</b><br/>
    <apex:inputTextarea value="{!TextToPredict}"/><br/>
    <apex:commandButton value="Check Sentiments" action="{!checkSentiments}" reRender="ResponsePanel"/>
    <apex:outputPanel id="ResponsePanel">
        <table width="100%">
        <apex:repeat value="{!resp.probabilities}" var="r">

Preview the Visualforce page and check the sentiments of the text.

Live demo Below , Start by entering text and click on check sentiments to see the results

About Saurabh Dua


  1. Hi Saurabh everything got saved without any error but is not giving any results.

  2. will sentiment analysis return sentiment based on user locale?


Note: only a member of this blog may post a comment.

Powered by Blogger.