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

Important: If you have IBM® Cloud Dedicated, this might not be your endpoint. Check your endpoint URL on the Service credentials page for your instance of the Tone Analyzer service.

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>4.1.0</version>
</dependency>

Gradle


compile 'com.ibm.watson.developer_cloud:java-sdk:4.1.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 -I watson-developer-cloud==1.0.1

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.tone(toneOptions);
ToneAnalysis tone = call.execute();

Example asynchronous request


ServiceCall call = service.tone(toneOptions);
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 of the service credentials for the instance of the service that you want to use. The API uses HTTP basic authentication. For information about creating a service instance and obtaining service credentials, 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 IBM Cloud 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, 2017-09-21). 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.

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> tone(ToneOptions toneOptions)

tone(tone_input, content_type='application/json', sentences=None, tones=None,
  content_language=None, accept_language=None)

Request

Parameter 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.
tone_input 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.
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 For an HTTP POST request, the content type of the input for 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.
Content-Language header string The language of the input text for the request:
  • en (English, the default; versions 2017-09-21 and 2016-05-19)
  • fr (French; version 2017-09-21 only)
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...] 2017-09-21: Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.

2016-05-19: 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.
Arguments for params
Parameter Description
tone_input object | string JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type ToneInput.
content_type string The content type of the input for 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: text/plain;charset=utf-8. For text/html, the service removes HTML tags and analyzes only the textual content.
content_language string The language of the input text for the request:
  • en (English, the default; versions 2017-09-21 and 2016-05-19)
  • fr (French; version 2017-09-21 only)
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 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 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...] 2017-09-21: Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.

2016-05-19: 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.
Parameter Description
toneOptions object A Java ToneOptions object that specifies the parameters of the request. To create an instance of the object, use the ToneOptions.Builder static nested class.
Java ToneOptions object
Parameter Description
toneInput object A Java ToneInput object that provides plain text input content that is to be analyzed. To create an instance of the object, use the ToneInput.Builder static nested class.
text string Provides plain text input content that is to be analyzed.
html string Provides HTML input content that is to be analyzed. The service removes HTML tags and analyzes only the textual content.
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.
tones List 2017-09-21: Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.

2016-05-19: A list of tones for which the service is to return its analysis of the input. A specified list completely replaces an existing list. The indicated tones apply both to the full document and to individual sentences of the document:
  • emotion
  • language
  • social
Omit the parameter to request results for all tones.
addTone string 2017-09-21: Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.

2016-05-19: Adds a tone to the list of tones for which the service is to return its analysis of the input. The list does not need to already exist. The indicated tone applies both to the full document and to individual sentences of the document:
  • emotion
  • language
  • social
Omit the parameter to request results for all tones.
Constructor: ToneOptions.Builder
Parameter Description
tone_input object | string JSON, plain text, or HTML input that contains the content to be analyzed. For JSON input, provide an object of type ToneInput.
content_type string The content type of the request:
  • application/json for text in JSON format (the default)
  • text/plain for plain text
  • text/html for text in HTML
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: text/plain;charset=utf-8. For text/html, the service removes HTML tags and analyzes only the textual content.
content_language string The language of the input text for the request:
  • en (English, the default; versions 2017-09-21 and 2016-05-19)
  • fr (French; version 2017-09-21 only)
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 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 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 string[, string...] 2017-09-21: Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response.

2016-05-19: 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.
ToneInput (Java ToneInput object)
Parameter Description
text string The input content that the service is to analyze.
Constructor: ToneInput.Builder

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: '2017-09-21'
});

var params = {
  'tone_input': require('tone.json'),
  'content_type': 'application/json'
};


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("2017-09-21");
service.setUsernameAndPassword("{username}", "{passsord}");

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

tone_analyzer = ToneAnalyzerV3(
  username='{username}',
  password='{passsword}',
  version='2017-09-21'
)

with open(join(dirname(__file__), 'tone.json')) as tone_json:
  tone = tone_analyzer.tone(tone_json.read())

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

Response

ToneAnalysis (Java ToneAnalysis object)
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 (Java DocumentAnalysis object)
Parameter Description
tones object[ ] 2017-09-21: 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.
2016-05-19: Not returned.
tone_categories object[ ] 2017-09-21: Not returned.
2016-05-19: An array of 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.
warning string 2017-09-21: 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.
2016-05-19: Not returned.
SentenceAnalysis (Java SentenceAnalysis 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.
tones object[ ] 2017-09-21: 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.
2016-05-19: Not returned.
tone_categories object[ ] 2017-09-21: Not returned.
2016-05-19: An array of ToneCategory objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the tones parameter of the request.
input_from integer 2017-09-21: Not returned.
2016-05-19: The offset of the first character of the sentence in the overall input content.
input_to integer 2017-09-21: Not returned.
2016-05-19: The offset of the last character of the sentence in the overall input content.
ToneScore (Java ToneScore object)
Parameter Description
score double The score for the tone.
  • 2017-09-21: The score that is returned lies 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.
  • 2016-05-19: The score that is returned lies 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.
  • 2017-09-21: The service can return results for the following tone IDs: anger, fear, joy, sadness, analytical, confident, and tentative. The service returns results only for tones whose scores meet a minimum threshold of 0.5.
  • 2016-05-19: 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.
ToneCategory (Java ToneCategory object)
Parameter Description
tones object[ ] An array of 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, and social_tone.
category_name string The user-visible, localized name of the category.

Response codes

Exception Description
200 OK The request succeeded. If the input is partially correct, the response can include warning 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 IBM Cloud ID submitted more than 1200 requests per minute.
500 Internal Server Error The service experienced 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 The service is throttling your request because your IBM Cloud ID submitted more than 1200 requests per minute. (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"
        }
      ]
    }
  ]
}

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

toneChat(params, callback())

ServiceCall<UtteranceAnalyses> toneChat(ToneChatOptions toneChatOptions)

tone_chat(utterances, accept_language=None)

Request

Parameter Description
utterances 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.
accept_language 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.
Parameter Description
toneChatOptions object A Java ToneChatOptions object that contains the content to be analyzed. To create an instance of the object, use the ToneChatOptions.Builder static nested class.
Java ToneChatOptions 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: ToneChatOptions.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: '2017-09-21'
});

var params = {
  utterances: require('tone-chat.json').utterances
};

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

ToneAnalyzer service = new ToneAnalyzer("2017-09-21");
service.setUsernameAndPassword("{username}", "{passsord}");

try {
  JsonReader jReader =
    new JsonReader(new FileReader("../resources/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);
  }

  ToneChatOptions options = new ToneChatOptions.Builder()
    .utterances(utterances).build();
  UtteranceAnalyses tone = service.toneChat(options).execute();
  System.out.println(tone);
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

tone_analyzer = ToneAnalyzerV3(
  username='{username}',
  password='{passsword}',
  version='2017-09-21'
)

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 UtteranceAnalyses 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 2017-09-21: A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances.
2016-05-19: Not returned.
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 A list of Java ToneChatScore 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 2017-09-21: An error message if the utterance contains more than 500 characters. The service does not analyze the utterance.
2016-05-19: Not returned.
ToneChatScore (Java ToneChatScore 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 IBM Cloud ID submitted more than 1200 requests per minute.
500 Internal Server Error The service experienced 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 The service is throttling your request because your IBM Cloud ID submitted more than 1200 requests per minute. (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.718352,
          "tone_id": "polite",
          "tone_name": "Polite"
        }
      ]
    },
    {
      "utterance_id": 1,
      "utterance_text": "OK, let me know what's going on, please.",
      "tones": []
    },
    {
      "utterance_id": 2,
      "utterance_text": "Well, nothing is working :(",
      "tones": [
        {
          "score": 0.997149,
          "tone_id": "sad",
          "tone_name": "sad"
        }
      ]
    },
    {
      "utterance_id": 3,
      "utterance_text": "Sorry to hear that.",
      "tones": [
        {
          "score": 0.689109,
          "tone_id": "polite",
          "tone_name": "Polite"
        },
        {
          "score": 0.663203,
          "tone_id": "sympathetic",
          "tone_name": "Sympathetic"
        }
      ]
    }
  ]
}