Curl Node Java Python

Tone Analyzer

API Reference

Introduction

The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional, social, and language tones in written text. The service can analyze tone at both the document and sentence levels. You can use the service to understand how your written communications are perceived and then to improve the tone of your communications. Businesses can use the service to learn the tone of their customers' communications and to respond to each customer appropriately, or to understand and improve their customer conversations.

API Endpoint


https://gateway.watsonplatform.net/tone-analyzer/api/v3

The code examples on this tab use the client library that is provided for Node.js.

GitHub

https://github.com/watson-developer-cloud/node-sdk

Node Package Manager


npm install watson-developer-cloud

The code examples on this tab use the client-side library that is provided for Java.

GitHub

https://github.com/watson-developer-cloud/java-sdk

Maven


<dependency>
  <groupId>com.ibm.watson.developer_cloud</groupId>
  <artifactId>java-sdk</artifactId>
  <version>3.8.0</version>
</dependency>

Gradle


compile 'com.ibm.watson.developer_cloud:java-sdk:3.8.0'

The code examples on this tab use the client-side library that is provided for Python.

https://github.com/watson-developer-cloud/python-sdk

Python


pip install --upgrade watson-developer-cloud

easy_install --upgrade watson-developer-cloud

Synchronous and asynchronous requests

The Java SDK supports both synchronous (blocking) and asynchronous (non-blocking) execution of all methods. All methods are called with the Java ServiceCall interface.

  • To call a method synchronously, use the execute method of the ServiceCall interface. You can also call the execute method directly from an instance of the service, as shown in Analyze general tone. Note that the method can return an unchecked RuntimeException.

  • To call a method asynchronously, use the enqueue method of the ServiceCall interface to receive a callback when the response arrives. The ServiceCallback interface of the method's argument provides onResponse and onFailure methods that you override to handle the callback.

Example synchronous request


ServiceCall call = service.getTone(text, null);
ToneAnalysis tone = call.execute();

Example asynchronous request


ServiceCall call = service.getTone(text, null);
call.enqueue(new ServiceCallback<ToneAnalysis>() {
  @Override public void onResponse(ToneAnalysis tone) {
    . . .
  }
  @Override public void onFailure(Exception e) {
    . . .
  }
});

More information

An interactive tool for testing calls to the API and viewing live responses from the service is available in the Tone Analyzer API explorer. Descriptions of Node classes referred to in this reference are available in the Node documentation for the Watson Developer Cloud Node.js SDK.. Descriptions of Java classes referred to in this reference are available in the Javadoc for the Watson Developer Cloud Java SDK. Descriptions of Python modules referred to in this reference are available in the Python documentation for the Watson Developer Cloud Python SDK. Detailed information about using the service is available at About Tone Analyzer.

Authentication

You authenticate to the Tone Analyzer API by providing the username and password that are provided in the service credentials for the service instance that you want to use. The API uses HTTP basic authentication.

After creating an instance of the Tone Analyzer service, select Service Credentials from the navigation on the left side of its dashboard page to see the username and password that are associated with the instance. For more information, see Service credentials for Watson services.

Applications can also use tokens to establish authenticated communications with Watson services without embedding their service credentials in every call. You write an authentication proxy in Bluemix to obtain a token for your client application, which can then use the token to call the service directly. You use your service credentials to obtain a token for that service. For more information, see Tokens for authentication.

Replace {username} and {password} with your service credentials. Replace {version} with the version of the API you want to use (for example, 2016-05-19). Use either of the two constructors shown.


curl -u "{username}":"{password}"
"https://gateway.watsonplatform.net/tone-analyzer/api/v3/{method}"

var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
var tone_analyzer = new ToneAnalyzerV3({
  username: '{username}',
  password: '{password}',
  version_date: '{version}'
});

ToneAnalyzer service = new ToneAnalyzer("{version}");
service.setUsernameAndPassword("{username}", "{password}");

ToneAnalyzer service = new ToneAnalyzer("{version}", "{username}", "{password}");

tone_analyzer = ToneAnalyzerV3(
  version='{version}',
  username='{username}',
  password='{password}'
)

Methods

Analyze general tone

Analyzes the tone of a piece of text. The message is analyzed for several tones - social, emotional, and language. For each tone, various traits are derived. For example, conscientiousness, agreeableness, and openness.

Use GET /v3/tone for smaller request data sizes and for URL query parameters, and use POST /v3/tone for larger request data sizes and for JSON requests.


GET /v3/tone
POST /v3/tone

Request

Parameter Type Description
text query string For an HTTP GET request, text that contains the content to be analyzed. The Tone Analyzer Service supports up to 128 KB of text, or about 1000 sentences. Sentences with less than three words cannot be analyzed. Not supported for POST requests.
body body string For an HTTP POST request, JSON, plain text, or HTML that contains the content to be analyzed. Not supported for GET requests.
Content-Type header string For an HTTP POST request, the content type of the request:
  • text/plain for plain text
  • text/html for text in HTML
  • application/json for text in JSON format
Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content type of plain text or HTML, include the charset parameter to indicate the character encoding of the input text; for example: Content-Type: text/plain;charset=utf-8. Omit for GET requests.
version query string When we make breaking changes to the API, we release a new, dated version. The value for the version parameter is the date for the version of the API that you want to call. The current version is 2016-05-19, and the documentation reflects the current version. For a list of available versions, see the Release notes for the changelog.
tones query string[, string...] Filter the results by a specific tone. Valid values for tones are emotion, language, and social.
sentences query boolean Filter your response to remove the sentence level analysis. Valid values for sentences are true and false. This parameter defaults to true when it is not set, which means that a sentence level analysis is automatically provided. Change sentences=false to filter out the sentence level analysis.

Example request GET

curl -u "{username}":"{password}" "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19&text=A%20word%20is%20dead%20when%20it%20is%20said,%20some%20say.%20Emily%20Dickinson"

Example request POST

curl -u "{username}":"{password}" -H "Content-Type: application/json" -d "{\"text\": \"A word is dead when it is said, some say. Emily Dickinson\"}" "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2016-05-19"

Example request


var watson = require('watson-developer-cloud');

var tone_analyzer = watson.tone_analyzer({
  username: '{username}',
  password: '{password}',
  version: 'v3',
  version_date: '2016-05-19'
});

tone_analyzer.tone({
  text: 'A word is dead when it is said, some say. Emily Dickinson'
}, function(err, tone) {
  if (err) {
    console.log(err);
  } else {
    console.log(JSON.stringify(tone, null, 2));
  }
});

Example request


ToneAnalyzer service = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19);
service.setUsernameAndPassword("{username}", "{password}");

String text =
  "I know the times are difficult! Our sales have been "
  + "disappointing for the past three quarters for our data analytics "
  + "product suite. We have a competitive data analytics product "
  + "suite in the industry. But we need to do our job selling it! "
  + "We need to acknowledge and fix our sales challenges. "
  + "We can’t blame the economy for our lack of execution! "
  + "We are missing critical sales opportunities. "
  + "Our product is in no way inferior to the competitor products. "
  + "Our clients are hungry for analytical tools to improve their "
  + "business outcomes. Economy has nothing to do with it.";

// Call the service and get the tone
ToneAnalysis tone = service.getTone(text, null).execute();
System.out.println(tone);

Example request


import json
from watson_developer_cloud import ToneAnalyzerV3

tone_analyzer = ToneAnalyzerV3(
  username='{username}',
  password='{password}',
  version='2016-05-19'
)

text = 'A word is dead when it is said, some say. Emily Dickinson'
print(json.dumps(tone_analyzer.tone(text=text), indent=2))

Response

Name Description
document_tone The tone analysis of the full document.
tone_categories The tone analysis categories. Possible tone categories are emotion, language, and social.
tones Analysis organized by tones.
  • The emotion tones are anger, disgust, fear, joy, and sadness.
  • The language tones are analytical, confident, and tentative.
  • The social tones are openness, conscientiousness, extraversion, agreeableness, and emotional_range.
score The score of the tone.
tone_id Unique ID of the tone.
category_id The unique ID of the category.
category_name The tone analysis categories. Possible tone categories are emotion, language, and social.
sentences_tone The sentence level tone analysis. Returns sentence scores for the first 100 sentences.
sentence_id Unique ID for each sentence.
text Text of the sentence being analyzed.
input_from The character number of the first character in the sentence.
input_to The character number of the last character in the sentence.

Example response


{
  "document_tone": {
    "tone_categories": [{
        "tones": [{
            "score": 0.25482,
            "tone_id": "anger",
            "tone_name": "Anger"
          },
          {
            "score": 0.345816,
            "tone_id": "disgust",
            "tone_name": "Disgust"
          },
          {
            "score": 0.121116,
            "tone_id": "fear",
            "tone_name": "Fear"
          },
          {
            "score": 0.078903,
            "tone_id": "joy",
            "tone_name": "Joy"
          },
          {
            "score": 0.199345,
            "tone_id": "sadness",
            "tone_name": "Sadness"
          }
        ],
        "category_id": "emotion_tone",
        "category_name": "Emotion Tone"
      },
      {
        "tones": [{
            "score": 0.999,
            "tone_id": "analytical",
            "tone_name": "Analytical"
          },
          {
            "score": 0.999,
            "tone_id": "confident",
            "tone_name": "Confident"
          },
          {
            "score": 0.694,
            "tone_id": "tentative",
            "tone_name": "Tentative"
          }
        ],
        "category_id": "language_tone",
        "category_name": "Language Tone"
      },
      {
        "tones": [{
            "score": 0.271,
            "tone_id": "openness_big5",
            "tone_name": "Openness"
          },
          {
            "score": 0.11,
            "tone_id": "conscientiousness_big5",
            "tone_name": "Conscientiousness"
          },
          {
            "score": 0.844,
            "tone_id": "extraversion_big5",
            "tone_name": "Extraversion"
          },
          {
            "score": 0.257,
            "tone_id": "agreeableness_big5",
            "tone_name": "Agreeableness"
          },
          {
            "score": 0.497,
            "tone_id": "emotional_range_big5",
            "tone_name": "Emotional Range"
          }
        ],
        "category_id": "social_tone",
        "category_name": "Social Tone"
      }
    ]
  }
}

Analyze customer engagement tone

Use the Tone Analyzer for Customer Engagement Endpoint to monitor customer service and customer support conversations.


POST /v3/tone_chat

Request

Parameter Type Description
body body object A JSON object that contains the content to be analyzed.
Content-Type header string The type of content to be analyzed: application/json (the default).
version query string When we make breaking changes to the API, we release a new, dated version. The value for the version parameter is the date for the version of the API that you want to call. The current version is 2016-05-19, and the documentation reflects the current version. For a list of available versions, see the Release notes for the changelog.

Example request

curl -u "{username}":"{password}" -H "Content-Type: application/json" -d '{"utterances": [{"text": "Hello, can you help me", "user": "customer"}, {"text": "How are you ?", "user": "agent"}, {"text": "Nothing is working", "user": "customer"}, {"text": "Sorry to hear this", "user": "agent"}]}' "https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone_chat?version=2016-05-19"

Example request


var tone_analyzer = new ToneAnalyzerV3({
  username: '{username}',
  password: '{password}',
  version_date: '2016-05-19'
});

var params = {
  utterances: [{
    text: 'My charger isn’t working.',
    user: 'customer'
  }, {
    text: 'Thanks for reaching out. Can you give me some more detail about the issue?',
    user: 'agent'
  }, {
    text: 'I put my charger in my phone last night to charge and it isn\'t working. Which is ridiculous, it\'s a new charger, I bought it yesterday.',
    user: 'customer'
  }, {
    text: 'I\'m sorry you’re having issues with charging. What kind of charger do you have?',
    user: 'agent'
  }]
};

tone_analyzer.tone_chat(params, function(err, tone) {
  if (err) {
    console.log(err);
  } else {
    console.log(JSON.stringify(tone, null, 2));
  }
});

Example request


ToneAnalyzer service = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19);
service.setUsernameAndPassword("{username}", "{password}");

String[] texts = {
  "My charger isn't working.",
  "Thanks for reaching out. Can you give me some more detail about the issue?",
  "I put my charger in my tablet to charge it up last night and it keeps saying it isn't"
    + " charging. The charging icon comes on, but it stays on even when I take the charger out. "
    + "Which is ridiculous, it's brand new.",
  "I'm sorry you're having issues with charging. What kind of charger are you using?"
};

String[] users = { "customer", "agent", "customer", "agent" };

List<Utterance> utterances = new ArrayList<Utterance>();
for (int i = 0; i < texts.length; i++) {
  Utterance utterance = new Utterance.Builder()
    .text(texts[i])
    .user(users[i])
    .build();
  utterances.add(utterance);
}

ToneChatRequest toneChatInput = new ToneChatRequest.Builder()
  .utterances(utterances)
  .build();

UtterancesTone utterancesTone = service.getChatTone(toneChatInput).execute();
System.out.println(utterancesTone);

Example request


import json
from watson_developer_cloud import ToneAnalyzerV3

tone_analyzer = ToneAnalyzerV3(
  username='{username}',
  password='{password}',
  version='2016-05-19'
)

utterances = [
  {"text": "Hello, can you help me", "user": "customer"},
  {"text": "How are you ?", "user": "agent"},
  {"text": "Nothing is working", "user": "customer"},
  {"text": "Sorry to hear this", "user": "agent"}
]

print(json.dumps(tone_analyzer.tone(utterances=utterances), indent=2))

Response

Name Description
utterance_tone Tone chat analysis.
utterance_id The score of the tone.
utterance_text Text analyzed.
tones Analysis organized by the most common tones and their scores.

Example response


{
  "utterances_tone": [{
      "utterance_id": 0,
      "utterance_text": "Hello, can you help me",
      "tones": [{
        "score": 0.794472,
        "tone_id": "polite",
        "tone_name": "polite"
      }]
    },
    {
      "utterance_id": 1,
      "utterance_text": "How are you ?",
      "tones": [

      ]
    },
    {
      "utterance_id": 2,
      "utterance_text": "Nothing is working",
      "tones": [{
          "score": 0.801019,
          "tone_id": "sad",
          "tone_name": "sad"
        },
        {
          "score": 0.66593,
          "tone_id": "frustrated",
          "tone_name": "frustrated"
        }
      ]
    },
    {
      "utterance_id": 3,
      "utterance_text": "Sorry to hear this",
      "tones": [{
          "score": 0.987011,
          "tone_id": "polite",
          "tone_name": "polite"
        },
        {
          "score": 0.746323,
          "tone_id": "sympathetic",
          "tone_name": "sympathetic"
        }
      ]
    }
  ]
}

Data collection

By default, Bluemix collects data from all requests and uses the data to improve the services. If you do not want to share your data, set a header parameter X-Watson-Learning-Opt-Out with the value 1 for all requests. If you do not specify this header in all payload data, data is collected and used to improve the service.

Response handling

The Tone Analyzer service uses standard HTTP response codes to display whether a method completed successfully. A 200 response always indicates success. A 400 type response is some sort of failure, and a 500 type response usually indicates an internal system error.

Error information

200 - OK Success.
201 - OK Created.
400 - Bad Request Missing a required parameter or invalid parameter value.
401 - Unauthorized No API key provided or the API key provided was not valid.
404 - Not Found The requested item or parameter doesn't exist.
429 - Throttle limit Your organization ID made more than 1200 requests per minute, so your calls have been throttled.
500 - Server Errors Internal server error.

Error format

Name Description
error Error description.
code HTTP Status code.
help (Optional) Help message.

Catching an error

Example error


{
  "code" : 400,
  "error" : "The request does not contain a Content-Type"
}