Curl Node Java Python

Tone Analyzer

API Reference

Introduction

The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional 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.9.1</version>
</dependency>

Gradle


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

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 that 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}'
)

Request logging

By default, all Watson services log requests and their results. Logging is done only to improve the services for future users. The logged data is not shared or made public. To prevent IBM from accessing your data for general service improvements, set the X-Watson-Learning-Opt-Out request header to true for all requests. (Any value other than false or 0 disables request logging for that call.) You must set the header on each request that you do not want IBM to access for general service improvements. set the X-Watson-Learning-Opt-Out request header to true when you create the instance. (Any value other than false or 0 disables request logging for that instance.) You must set the header when you create the instance whose calls you do not want IBM to access for general service improvements. set the x-watson-learning-opt-out header parameter to true when you create the instance. (Any value other than false or 0 disables request logging for that instance.) You must set the header when you create the instance whose calls you do not want IBM to access for general service improvements.


curl -u "{username}":"{password}"
--header "X-Watson-Learning-Opt-Out: true"
"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}'
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Watson-Learning-Opt-Out", "true");

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

tone_analyzer = ToneAnalyzerV3(
  version='{version}',
  username='{username}',
  password='{password}',
  x-watson-learning-opt-out=True
)

Response handling

The Tone Analyzer service uses standard HTTP response codes to indicate whether a method completed successfully. A 200-level response always indicates success. A 300-level response indicates the requested resource has not been modified. A 400-level response indicates some sort of input failure. And a 500-level response typically indicates an internal system error. Response codes are listed with the individual calls.

Response codes that indicate success are not readily available with the Node.js SDK. In general, the lack of an error response indicates a 200-level success response. For errors, response codes are indicated in the error object that is returned.

The Java SDK raises equivalent exceptions, which are listed with the individual methods. The exceptions include the error message returned by the service. All methods that accept an argument can throw the following exception.

Exception Description
IllegalArgumentException An illegal argument was passed to the method.

The Python SDK can raise the following exceptions. The exceptions include the error message returned by the service.

Exception Description
WatsonInvalidArgument The call to the Python method was invalid; for example, the call passed an invalid argument. The Python module raises this exception without calling the service.
WatsonException The service returned an error in response to the call. The Python module raises this exception to report the error from the service.

Error format

Name Description
code integer The HTTP status code.
sub_code string A service-specific error code.
error string A description of the error.
help string A URL to documentation explaining the cause and possibly solutions for the error.
Name Description
Exception string The name of the exception that was raised.
status integer The HTTP status code.
error string A description of the error.
Name Description
Exception string The name of the exception that was raised.
Error string A description of the error.
Code integer The HTTP status code.

Example error


{
  "code": 400,
  "sub_code": "C00012",
  "error": "Invalid JSON input at line 2, column 12"
}

{
  Error: Missing a minor version parameter in the URL. To use the latest version, add the following query argument: version=2017-09-21
  . . .
  code: 400,
  sub_code: 'C00005',
  error: 'Missing a minor version parameter in the URL. To use the latest version, add the following query argument: version=2017-09-21'
}

SEVERE: POST https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21, status: 401, error: Not Authorized
Exception in thread "main" com.ibm.watson.developer_cloud.service.exception.UnauthorizedException: Unauthorized: Access is denied due to invalid credentials
  . . .

Traceback (most recent call last):
  . . .
    raise WatsonException(error_message)
watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: Invalid {0} argument value: emotional, Code: 400

Methods

Analyze general tone

Use the general purpose endpoint to analyze the tone of your input content. The service analyzes the content for emotional and language tones. The method always analyzes the tone of the full document; by default, it also analyzes the tone of each individual sentence of the content.

Use the general purpose endpoint to analyze the tone of your input content. The service can analyze the input for several tones: emotion, language, and social. It derives various characteristics for each tone that it analyzes. The method always analyzes the tone of the full document; by default, it also analyzes the tone of each individual sentence of the input. You can submit a maximum of 128 KB of content in plain text or HTML format. in plain text format.

You can submit no more than 128 KB of total input content and no more than 1000 individual sentences in JSON, plain text, or HTML format. The service analyzes the first 1000 sentences for document-level analysis and only the first 100 sentences for sentence-level analysis.

Use the POST request method to analyze larger amounts of content in any of the available formats. Use the GET request method to analyze smaller quantities of plain text content.


GET /v3/tone
POST /v3/tone

tone(params, callback())

ServiceCall<ToneAnalysis> getTone(String text, ToneOptions options)

tone(text, tones=None, sentences=None, content_type='text/plain')

Request

Parameter Type Description
text query string For an HTTP GET request, plain text input that contains the content to be analyzed. You must URL-encode the input. Not supported for POST requests.
body body object | string For an HTTP POST request, JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type ToneInput. 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. For text/html, the service removes HTML tags and analyzes only the textual content. Omit for GET requests.
version query string The requested version of the response format as a date in the form YYYY-MM-DD; for example, specify 2017-09-21 for September 21, 2017. The parameter allows the service to update its interface and response format for new versions without breaking existing clients.

The date that you specify does not need to match a version of the service exactly; the service replies with the response format whose version is no later than the date you provide. If you specify a date that is earlier than the initial release of version 3, the service returns the response format for that version. If you specify a date that is in the future or otherwise later than the most recent version, the service returns the response format for the latest version.
Content-Language header string The language of the input text for the request:
  • en (English, the default)
  • fr (French)
Regional variants are treated as their parent language; for example, en-US is interpreted as en. The input content must match the specified language. Do not submit content that contains both languages. You can use different languages for Content-Language and Accept-Language.
Accept-Language header string The desired language of the response:
  • ar (Arabic)
  • de (German)
  • en (English, the default)
  • es (Spanish)
  • fr (French)
  • it (Italian)
  • ja (Japanese)
  • ko (Korean)
  • pt-br (Brazilian Portuguese)
  • zh-cn (Simplified Chinese)
  • zh-tw (Traditional Chinese)
For two-character arguments, regional variants are treated as their parent language; for example, en-US is interpreted as en. You can use different languages for Content-Language and Accept-Language.
sentences query boolean Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If true (the default), the service returns results for each sentence.
tones query string[, string...] Do not use. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.
ToneInput
Parameter Description
text string The input content that the service is to analyze.
Arguments for params
Parameter Description
text string Plain text or HTML input that contains the content to be analyzed. For HTML input, set the isHTML parameter to true. Submit a maximum of 128 KB of content.
tones string[, string...] A comma-separated list of tones for which the service is to return its analysis of the input; the indicated tones apply both to the full document and to individual sentences of the document. You can specify one or more of the following values:
  • emotion
  • language
  • social
Omit the parameter to request results for all tones.
sentences boolean Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If true (the default), the service returns results for each sentence. The service returns results only for the first 100 sentences of the input.
isHTML boolean Indicates whether the text parameter provides HTML input. If false (the default), the input is assumed to be plain text. If true, the service removes HTML tags and analyzes only the textual content.
Parameter Description
text string Plain text or HTML input that contains the content to be analyzed. For HTML input, use the Java ToneOptions object to set the html parameter to true. Submit a maximum of 128 KB of content.
options object A Java ToneOptions object that specifies the parameters of the request. Pass a value of null to use the default parameters. To create an instance of the object, use the ToneOptions.Builder static nested class.
Java ToneOptions object
Parameter Description
tones List A list of tones for which the service is to return its analysis of the input; the indicated tones apply both to the full document and to individual sentences of the document. Add a tone to the List by specifying one of the following constants in a call to the addTone method of the ToneOptions.Builder class:
  • Tone.EMOTION
  • Tone.LANGUAGE
  • Tone.SOCIAL
Omit the parameter to request results for all tones.
includeSentences boolean Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If true (the default), the service returns results for each sentence. The service returns results only for the first 100 sentences of the input.
html boolean Indicates whether the text parameter provides HTML input. If false (the default), the input is assumed to be plain text. If true, the service removes HTML tags and analyzes only the textual content.
Constructor: ToneOptions.Builder
Parameter Description
text string Plain text input that contains the content to be analyzed. Submit a maximum of 128 KB of content.
tones string[, string...] A comma-separated list of tones for which the service is to return its analysis of the input; the indicated tones apply both to the full document and to individual sentences of the document. You can specify one or more of the following values:
  • emotion
  • language
  • social
Omit the parameter to request results for all tones.
sentences boolean Indicates whether the service is to return an analysis of each individual sentence in addition to its analysis of the full document. If true (the default), the service returns results for each sentence. The service returns results only for the first 100 sentences of the input.
content_type string The content type of the request:
  • text/plain for plain text (the default)
  • 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). For text/html, the service removes HTML tags and analyzes only the textual content.

Example GET request


curl -X GET -u "{username}":"{password}"
"https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&text=Team,%20I%20know%20that%20times%20are%20tough!%20Product%20sales%20have%20been%20disappointing%20for%20the%20past%20three%20quarters.%20We%20have%20a%20competitive%20product,%20but%20we%20need%20to%20do%20a%20better%20job%20of%20selling%20it!"

Example POST request


curl -X POST -u "{username}":"{password}"
--header "Content-Type: application/json"
--data-binary @tone.json
"https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21"

Example request


var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');

var tone_analyzer = new ToneAnalyzerV3({
  username: '{username}',
  password: '{password}',
  version_date: '{version}'
});

var params = {
  // Get the text from the JSON file.
  text: require('tone.json').text,
  tones: 'emotion'
};

tone_analyzer.tone(params, function(error, response) {
  if (error)
    console.log('error:', error);
  else
    console.log(JSON.stringify(response, null, 2));
  }
);

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

try {
  JsonReader jReader = new JsonReader(new FileReader("tone.json"));
  JsonParser jParser = new JsonParser();
  JsonObject jObject = (JsonObject) jParser.parse(jReader);
  ToneOptions options = new ToneOptions.Builder()
    .addTone(Tone.EMOTION).build();
  ToneAnalysis tone =
    service.getTone(jObject.get("text").getAsString(), options).execute();
  System.out.println(tone);
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

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

with open(join(dirname(__file__), 'tone.json')) as tone_json:
  tone = tone_analyzer.tone(json.load(tone_json)['text'], tones='emotion',
    content_type='text/plain')

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

Response

ToneAnalysis
Parameter Description
document_tone object An object of type DocumentAnalysis that provides the results of the analysis for the full input document.
sentences_tone object[ ] An array of SentenceAnalysis objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the sentences parameter of the request is set to false.
DocumentAnalysis
Parameter Description
tones object[ ] An array of ToneScore objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold.
warning string A warning message if the overall content exceeds 128 KB or contains more than 1000 sentences. The service analyzes only the first 1000 sentences for document-level analysis and the first 100 sentences for sentence-level analysis.
SentenceAnalysis
Parameter Description
sentence_id integer The unique identifier of a sentence of the input content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one.
text string The text of the input sentence.
tones object[ ] An array of ToneScore objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold.
ToneScore
Parameter Description
score double The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the content.
tone_id string The unique, non-localized identifier of the tone. The service can return results for the following tone IDs:
  • anger
  • fear
  • joy
  • sadness
  • analytical
  • confident
  • tentative
The service returns results only for tones whose scores meet a minimum threshold of 0.5.
tone_name string The user-visible, localized name of the tone.
ToneAnalysis (Java ToneAnalysis object)
Parameter Description
document_tone object An object of type DocumentAnalysis A Java object of type ElementTone that provides the results of the analysis for the full document of the input content.
sentences_tone object[ ] List An array of SentenceAnalysis A list of Java SentenceTone objects that provides the results for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the sentences includeSentences parameter of the request is set to false.
DocumentAnalysis (Java ElementTone object)
Parameter Description
tone_categories object[ ] List An array of A list of Java ToneCategory objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified with the tones parameter of the request.
SentenceAnalysis (Java SentenceTone object)
Parameter Description
sentence_id integer The unique identifier of a sentence of the input content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one.
text string The text of the input sentence.
input_from integer The offset of the first character of the sentence in the overall input content.
input_to integer The offset of the last character of the sentence in the overall input content.
tone_categories object[ ] List An array of A list of Java ToneCategory objects that provides the results for the tone analysis of the sentence. The service returns results only for the tones specified with the tones parameter of the request.
ToneCategory (Java ToneCategory object)
Parameter Description
tones object[ ] List An array of A list of Java ToneScore objects that provides the results for the tones of the category.
category_id string The unique, non-localized identifier of the category for the results. The service can return results for the following category IDs:
  • emotion_tone
  • language_tone
  • social_tone
category_name string The user-visible, localized name of the category.
ToneScore (Java ToneScore object)
Parameter Description
score double The score for the tone in the range of 0 to 1. A score less than 0.5 indicates that the tone is unlikely to be perceived in the content; a score greater than 0.75 indicates a high likelihood that the tone is perceived.
tone_id string The unique, non-localized identifier of the tone for the results. The service can return results for the following tone IDs of the different categories:
  • For the emotion category: anger, disgust, fear, joy, and sadness
  • For the language category: analytical, confident, and tentative
  • For the social category: openness_big5, conscientiousness_big5, extraversion_big5, agreeableness_big5, and emotional_range_big5
The service returns scores for all tones of a category, regardless of their values.
tone_name string The user-visible, localized name of the tone.

Response codes

Exception Description
200 OK The request succeeded. If the input is partially correct, the response can include warning or error fields with appropriate messages.
400 Bad Request A required input parameter is null or a specified input parameter or header value is invalid or not supported.
401 Unauthorized Access is denied due to invalid service credentials.
404 Not Found A requested item or parameter does not exist.
429 Too Many Requests The service is throttling your request because your Bluemix ID submitted more than 1200 requests per minute.
500 Internal Server Error The service encountered an internal error.

Response codes

Exception Description
200 OK The request succeeded.
400 Bad Request A required input parameter is null or a specified input parameter or header value is invalid or not supported.
401 Unauthorized Access is denied due to invalid service credentials.
404 Not Found A requested item or parameter does not exist.
429 Too Many Requests Your organization ID submitted more than 1200 requests per minute, so the service is throttling your calls.
500 Internal Server Error The service encountered an internal error.

Exceptions thrown

Exception Description
IllegalArgumentException An illegal argument was passed to the method.
BadRequestException A required input parameter is null or a specified input parameter or header value is invalid or not supported. (HTTP response code 400.)
UnauthorizedException Access is denied due to invalid service credentials. (HTTP response code 401.)
NotFoundException A requested item or parameter does not exist. (HTTP response code 404.)
TooManyRequestsException Your organization ID submitted more than 1200 requests per minute, so the service is throttling your calls. (HTTP response code 429.)
InternalServerErrorException The service experienced an internal error. (HTTP response code 500.)

Example response


{
  "document_tone": {
    "tones": [
      {
        "score": 0.6165,
        "tone_id": "sadness",
        "tone_name": "Sadness"
      },
      {
        "score": 0.829888,
        "tone_id": "analytical",
        "tone_name": "Analytical"
      }
    ]
  },
  "sentences_tone": [
    {
      "sentence_id": 0,
      "text": "Team, I know that times are tough!",
      "tones": [
        {
          "score": 0.801827,
          "tone_id": "analytical",
          "tone_name": "Analytical"
        }
      ]
    },
    {
      "sentence_id": 1,
      "text": "Product sales have been disappointing for the past three quarters.",
      "tones": [
        {
          "score": 0.771241,
          "tone_id": "sadness",
          "tone_name": "Sadness"
        },
        {
          "score": 0.687768,
          "tone_id": "analytical",
          "tone_name": "Analytical"
        }
      ]
    },
    {
      "sentence_id": 2,
      "text": "We have a competitive product, but we need to do a better job of selling it!",
      "tones": [
        {
          "score": 0.506763,
          "tone_id": "analytical",
          "tone_name": "Analytical"
        }
      ]
    }
  ]
}

{
  "document_tone": {
    "tone_categories": [
      {
        "tones": [
          {
            "score": 0.134622,
            "tone_id": "anger",
            "tone_name": "Anger"
          },
          {
            "score": 0.013182,
            "tone_id": "disgust",
            "tone_name": "Disgust"
          },
          {
            "score": 0.092403,
            "tone_id": "fear",
            "tone_name": "Fear"
          },
          {
            "score": 0.013411,
            "tone_id": "joy",
            "tone_name": "Joy"
          },
          {
            "score": 0.635069,
            "tone_id": "sadness",
            "tone_name": "Sadness"
          }
        ],
        "category_id": "emotion_tone",
        "category_name": "Emotion Tone"
      }
    ]
  },
  "sentences_tone": [
    {
      "sentence_id": 0,
      "text": "Team, I know that times are tough!",
      "input_from": 0,
      "input_to": 34,
      "tone_categories": [
        {
          "tones": [
            {
              "score": 0.150882,
              "tone_id": "anger",
              "tone_name": "Anger"
            },
            . . .
            {
              "score": 0.410121,
              "tone_id": "sadness",
              "tone_name": "Sadness"
            }
          ],
          "category_id": "emotion_tone",
          "category_name": "Emotion Tone"
        }
      ]
    },
    {
      "sentence_id": 1,
      "text": "Product sales have been disappointing for the past three quarters.",
      "input_from": 35,
      "input_to": 101,
      "tone_categories": [
        {
          "tones": [
            {
              "score": 0.106857,
              "tone_id": "anger",
              "tone_name": "Anger"
            },
            . . .
            {
              "score": 0.758459,
              "tone_id": "sadness",
              "tone_name": "Sadness"
            }
          ],
          "category_id": "emotion_tone",
          "category_name": "Emotion Tone"
        }
      ]
    },
    {
      "sentence_id": 2,
      "text": "We have a competitive product, but we need to do a better job of selling it!",
      "input_from": 102,
      "input_to": 178,
      "tone_categories": [
        {
          "tones": [
            {
              "score": 0.094095,
              "tone_id": "anger",
              "tone_name": "Anger"
            },
            . . .
            {
              "score": 0.193997,
              "tone_id": "sadness",
              "tone_name": "Sadness"
            }
          ],
          "category_id": "emotion_tone",
          "category_name": "Emotion Tone"
        }
      ]
    }
  ]
}

Analyze customer engagement tone

Use the customer engagement endpoint to analyze the tone of customer service and customer support conversations. For each utterance of a conversation, the method reports the most prevalent subset of the following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic.

If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the service returns an error for that utterance and does not analyze the utterance. The request fails if all utterances have more than 500 characters.


POST /v3/tone_chat

tone_chat(params, callback())

ServiceCall<UtterancesTone> getChatTone(ToneChatRequest chatInput)

tone_chat(utterances)

Request

Parameter Type Description
body body object A JSON object of type ToneChatInput that contains the content to be analyzed.
version query string The requested version of the response format as a date in the form YYYY-MM-DD; for example, specify 2017-09-21 for September 21, 2017. The parameter allows the service to update its interface and response format for new versions without breaking existing clients.

The date that you specify does not need to match a version of the service exactly; the service replies with the response format whose version is no later than the date you provide. If you specify a date that is earlier than the initial release of version 3, the service returns the response format for that version. If you specify a date that is in the future or otherwise later than the most recent version, the service returns the response format for the latest version.
Content-Type header string The content type of the request; only the default, application/json, is supported. Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8.
Accept-Language header string The desired language of the response:
  • ar (Arabic)
  • de (German)
  • en (English, the default)
  • es (Spanish)
  • fr (French)
  • it (Italian)
  • ja (Japanese)
  • ko (Korean)
  • pt-br (Brazilian Portuguese)
  • zh-cn (Simplified Chinese)
  • zh-tw (Traditional Chinese)
For two-character arguments, regional variants are treated as their parent language; for example, en-US is interpreted as en.
ToneChatInput
Parameter Description
utterances object[ ] An array of Utterance objects that provides the input content that the service is to analyze.
Arguments for params
Parameter Description
utterances object[ ] An array of Utterance objects that provides the input content that the service is to analyze.
Parameter Description
chatInput object A Java ToneChatRequest object that contains the content to be analyzed. To create an instance of the object, use the ToneChatRequest.Builder static nested class.
Java ToneChatRequest object
Parameter Description
utterances List A list of Java Utterance objects that provides the input content that the service is to analyze. To create an instance of the object, use the Utterance.Builder static nested class.
Constructor: ToneChatRequest.Builder
Utterance (Java Utterance object)
Parameter Description
text string An utterance contributed by a user in the conversation that is to be analyzed. The utterance can contain multiple sentences.
user string A string that identifies the user who contributed the utterance specified by the text parameter.
Constructor: Utterance.Builder

Example request


curl -X POST -u "{username}":"{password}"
--header "Content-Type: application/json"
--data-binary @tone-chat.json
"https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone_chat?version=2017-09-21"

var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');

var tone_analyzer = new ToneAnalyzerV3({
  username: '{username}',
  password: '{password}',
  version_date: '{version}'
});

var params = require('tone-chat.json');

tone_analyzer.tone_chat(params, function(error, response) {
  if (error)
    console.log('error:', error);
  else
    console.log(JSON.stringify(response, null, 2));
  }
);

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

try {
  JsonReader jReader = new JsonReader(new FileReader("tone-chat.json"));
  JsonParser jParser = new JsonParser();
  JsonObject jObject = (JsonObject) jParser.parse(jReader);
  JsonArray jArray = jObject.getAsJsonArray("utterances");

  List<Utterance> utterances = new ArrayList<>();
  Iterator<JsonElement> iterator = jArray.iterator();
  while (iterator.hasNext()) {
    JsonObject jObj = (JsonObject) iterator.next();
    Utterance utterance = new Utterance.Builder()
      .text(jObj.get("text").toString())
      .user(jObj.get("user").toString())
      .build();
    utterances.add(utterance);
  }

  ToneChatRequest options = new ToneChatRequest.Builder()
    .utterances(utterances).build();
  UtterancesTone tone = service.getChatTone(options).execute();
  System.out.println(tone);
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

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

with open(join(dirname(__file__),'tone-chat.json')) as tone_json:
  tone = tone_analyzer.tone_chat(json.load(tone_json)['utterances'])

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

Response

UtteranceAnalyses (Java UtterancesTone object)
Parameter Description
utterances_tone object[ ] List An array of A list of Java UtteranceAnalysis objects that provides the results for each utterance of the input.
warning string A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances.
UtteranceAnalysis (Java UtteranceAnalysis object)
Parameter Description
utterance_id integer The unique identifier of the utterance. The first utterance has ID 0, and the ID of each subsequent utterance is incremented by one.
utterance_text string The text of the utterance.
tones object[ ] List An array of ToneChatScore A list of Java ToneScore objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold.
error string An error message if the utterance contains more than 500 characters. The service does not analyze the utterance.
ToneChatScore (Java ToneScore object)
Parameter Description
score double The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the utterance.
tone_id string The unique, non-localized identifier of the tone for the results. The service can return results for the following tone IDs:
  • sad
  • frustrated
  • satisfied
  • excited
  • polite
  • impolite
  • sympathetic
The service returns results only for tones whose scores meet a minimum threshold of 0.5.
tone_name string The user-visible, localized name of the tone.

Response codes

Exception Description
200 OK The request succeeded. If the input is partially correct, the response can include warning or error fields with appropriate messages.
400 Bad Request A required input parameter is null or a specified input parameter or header value is invalid or not supported. The response is also returned if all utterances of the input have more than 500 characters.
401 Unauthorized Access is denied due to invalid service credentials.
404 Not Found A requested item or parameter does not exist.
429 Too Many Requests The service is throttling your request because your Bluemix ID submitted more than 1200 requests per minute.
500 Internal Server Error The service encountered an internal error.

Response codes

Exception Description
200 OK The request succeeded.
400 Bad Request A required input parameter is null or a specified input parameter or header value is invalid or not supported.
401 Unauthorized Access is denied due to invalid service credentials.
404 Not Found A requested item or parameter does not exist.
429 Too Many Requests Your organization ID submitted more than 1200 requests per minute, so the service is throttling your calls.
500 Internal Server Error The service encountered an internal error.

Exceptions thrown

Exception Description
IllegalArgumentException An illegal argument was passed to the method.
BadRequestException A required input parameter is null or a specified input parameter or header value is invalid or not supported. (HTTP response code 400.)
UnauthorizedException Access is denied due to invalid service credentials. (HTTP response code 401.)
NotFoundException A requested item or parameter does not exist. (HTTP response code 404.)
TooManyRequestsException Your organization ID submitted more than 1200 requests per minute, so the service is throttling your calls. (HTTP response code 429.)
InternalServerErrorException The service experienced an internal error. (HTTP response code 500.)

Example response


{
  "utterances_tone": [
    {
      "utterance_id": 0,
      "utterance_text": "Hello, I'm having a problem with your product.",
      "tones": [
        {
          "score": 0.711722,
          "tone_id": "polite",
          "tone_name": "polite"
        }
      ]
    },
    {
      "utterance_id": 1,
      "utterance_text": "OK, let me know what's going on, please.",
      "tones": [
        {
          "score": 0.814275,
          "tone_id": "polite",
          "tone_name": "polite"
        }
      ]
    },
    {
      "utterance_id": 2,
      "utterance_text": "Well, nothing is working :(",
      "tones": [
        {
          "score": 0.753187,
          "tone_id": "frustrated",
          "tone_name": "frustrated"
        },
        {
          "score": 0.940611,
          "tone_id": "sad",
          "tone_name": "sad"
        }
      ]
    },
    {
      "utterance_id": 3,
      "utterance_text": "Sorry to hear that.",
      "tones": [
        {
          "score": 0.992159,
          "tone_id": "polite",
          "tone_name": "polite"
        },
        {
          "score": 0.772394,
          "tone_id": "sympathetic",
          "tone_name": "sympathetic"
        }
      ]
    }
  ]
}