UNPKG

28.3 kBMarkdownView Raw
1# Watson APIs Node.js SDK
2
3[![Build Status](https://secure.travis-ci.org/watson-developer-cloud/node-sdk.svg)](http://travis-ci.org/watson-developer-cloud/node-sdk)
4[![codecov](https://codecov.io/gh/watson-developer-cloud/node-sdk/branch/master/graph/badge.svg)](https://codecov.io/gh/watson-developer-cloud/node-sdk)
5[![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net)
6[![npm-version](https://img.shields.io/npm/v/watson-developer-cloud.svg)](https://www.npmjs.com/package/watson-developer-cloud)
7[![npm-downloads](https://img.shields.io/npm/dm/watson-developer-cloud.svg)](https://www.npmjs.com/package/watson-developer-cloud)
8[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
9
10Node.js client library to use the Watson APIs.
11
12<details>
13 <summary>Table of Contents</summary>
14
15 * [Before you begin](#before-you-begin)
16 * [Installation](#installation)
17 * [Usage](#usage)
18 * [Client-side usage](#client-side-usage)
19 * [Authentication](#authentication)
20 * [IAM](#iam)
21 * [Username and password](#username-and-password)
22 * [API key](#api-key)
23 * [Callbacks vs Promises](#callbacks-vs-promises)
24 * [Sending request headers](#sending-request-headers)
25 * [Parsing HTTP response](#parsing-http-response)
26 * [Data collection opt-out](#data-collection-opt-out)
27 * [Documentation](#documentation)
28 * [Questions](#questions)
29 * [IBM Watson services](#ibm-watson-services)
30 * [Authorization](#authorization)
31 * [Assistant v2](#assistant-v2)
32 * [Assistant v1](#assistant-v1)
33 * [Discovery](#discovery)
34 * [Language Translator](#language-translator)
35 * [Natural Language Classifier](#natural-language-classifier)
36 * [Natural Language Understanding](#natural-language-understanding)
37 * [Personality Insights](#personality-insights)
38 * [Speech to Text](#speech-to-text)
39 * [Text to Speech](#text-to-speech)
40 * [Tone Analyzer](#tone-analyzer)
41 * [Visual Recognition](#visual-recognition)
42 * [Composing Services](#composing-services)
43 * [Debug](#debug)
44 * [Tests](#tests)
45 * [License](#license)
46 * [Contributing](#contributing)
47
48</details>
49
50## Before you begin
51* You need an [IBM Cloud][ibm-cloud-onboarding] account.
52
53## Installation
54
55```sh
56npm install watson-developer-cloud
57```
58
59## Usage
60
61The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have [service credentials](#getting-credentials).
62
63Credentials are checked for in the following order:
64
651. Hard-coded or programatic credentials passed to the service constructor
66
672. Environment variables:
68- `SERVICE_NAME_USERNAME` and `SERVICE_NAME_PASSWORD` environment properties
69- If using IAM: `SERVICE_NAME_IAM_APIKEY` and optionally `SERVICE_NAME_IAM_URL`, or `SERVICE_NAME_IAM_ACCESS_TOKEN`
70- Optionally, `SERVICE_NAME_URL`
71
723. IBM-Cloud-supplied credentials (via the `VCAP_SERVICES` JSON-encoded environment property)
73
74If you run your app in IBM Cloud, the SDK gets credentials from the [`VCAP_SERVICES`][vcap_services] environment variable.
75
76### Client-side usage
77
78See the `examples/` folder for [Browserify](http://browserify.org/) and [Webpack](http://webpack.github.io/) client-side SDK examples (with server-side generation of auth tokens.)
79
80Note: not all services currently support CORS, and therefore not all services can be used client-side.
81Of those that do, most require an auth token to be generated server-side via the [Authorization Service](#authorization).
82
83## Authentication
84Watson services are migrating to token-based Identity and Access Management (IAM) authentication.
85
86- With some service instances, you authenticate to the API by using **[IAM](#iam)**.
87- In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance.
88
89### Getting credentials
90
91To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:
92
931. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com/) page.
942. Either click an existing Watson service instance in your [resource list](https://cloud.ibm.com/resources) or click [**Create resource > AI**](https://cloud.ibm.com/catalog?category=ai) and create a service instance.
953. Click on the **Manage** item in the left nav bar of your service instance.
96
97On this page, you should be able to see your credentials for accessing your service instance.
98
99In your code, you can use these values in the service constructor or with a method call after instantiating your service.
100
101### Supplying credentials
102
103There are two ways to supply the credentials you found above to the SDK for authentication:
104
105#### Credentials file (easier!)
106
107With a credentials file, you just need to put the file in the right place and the SDK will do the work of parsing it and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance.
108
109The file downloaded will be called `ibm-credentials.env`. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your `ibm-credentials.env` file in the following places (in order):
110
111- Directory provided by the environment variable `IBM_CREDENTIALS_FILE`
112- Your system's home directory
113- Your current working directory (the directory Node is executed from)
114
115As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:
116
117```js
118const DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
119const discovery = new DiscoveryV1({ version: '2019-02-01' });
120```
121
122And that's it!
123
124If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning credentials to their appropriate services.
125
126If you would like to configure the location/name of your credential file, you can set an environment variable called `IBM_CREDENTIALS_FILE`. **This will take precedence over the locations specified above.** Here's how you can do that:
127
128```bash
129export IBM_CREDENTIALS_FILE="<path>"
130```
131
132where `<path>` is something like `/home/user/Downloads/<file_name>.env`. If you just provide a path to a directory, the SDK will look for a file called `ibm-credentials.env` in that directory.
133
134#### Manually
135
136The SDK also supports setting credentials manually in your code. You will either use IAM credentials or Basic Authentication (username/password) credentials.
137
138##### IAM
139
140Some services use token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.
141
142You supply either an IAM service **API key** or an **access token**:
143
144- Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
145- Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://console.bluemix.net/docs/services/watson/getting-started-iam.html). If you want to switch to API key, override your stored IAM credentials with an IAM API key.
146
147###### Supplying the IAM API key
148
149```js
150// in the constructor, letting the SDK manage the IAM token
151const discovery = new DiscoveryV1({
152 url: '<service_url>',
153 version: '<version-date>',
154 iam_apikey: '<iam_api_key>',
155 iam_url: '<iam_url>', // optional - the default value is https://iam.bluemix.net/identity/token
156});
157```
158
159###### Supplying the access token
160
161```js
162// in the constructor, assuming control of managing IAM token
163const discovery = new DiscoveryV1({
164 url: '<service_url>',
165 version: '<version-date>',
166 iam_access_token: '<access-token>'
167});
168```
169
170```js
171// after instantiation, assuming control of managing IAM token
172const discovery = new DiscoveryV1({
173 url: '<service_url>',
174 version: '<version-date>'
175});
176
177discovery.setAccessToken('<access-token>')
178```
179
180### Username and password
181
182```javascript
183var DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
184
185var discovery = new DiscoveryV1({
186 version: '{version}',
187 username: '{username}',
188 password: '{password}'
189 });
190```
191
192### Callbacks vs Promises
193
194All SDK methods are asynchronous, as they are making network requests to Watson services. To handle receiving the data from these requests, the SDK offers support for both Promises and Callback functions. A Promise will be returned by default unless a Callback function is provided.
195
196```js
197const discovery = new watson.DiscoveryV1({
198/* iam_apikey, version, url, etc... */
199});
200
201// using Promises
202discovery.listEnvironments()
203 .then(body => {
204 console.log(JSON.stringify(body, null, 2));
205 })
206 .catch(err => {
207 console.log(err);
208 });
209
210// using Promises provides the ability to use async / await
211async function callDiscovery() { // note that callDiscovery also returns a Promise
212 const body = await discovery.listEnvironments();
213}
214
215// using a Callback function
216discovery.listEnvironments((err, res) => {
217 if (err) {
218 console.log(err);
219 } else {
220 console.log(JSON.stringify(res, null, 2));
221 }
222});
223```
224
225### Setting the service URL
226
227You can set the service URL by calling the setServiceUrl() method.
228
229```javascript
230const discovery = new DiscoveryV1({
231 version: '<version-date>'
232});
233
234discovery.setServiceUrl('https://gateway-wdc.watsonplatform.net/discovery/api');
235```
236
237### Sending request headers
238
239Custom headers can be passed with any request. Each method has an optional parameter `headers` which can be used to pass in these custom headers, which can override headers that we use as parameters.
240
241For example, this is how you can pass in custom headers to Watson Assistant service. In this example, the `'custom'` value for `'Accept-Language'` will override the default header for `'Accept-Language'`, and the `'Custom-Header'` while not overriding the default headers, will additionally be sent with the request.
242
243```js
244var assistant = new watson.AssistantV1({
245/* username, password, version, url, etc... */
246});
247
248assistant.message({
249 workspace_id: 'something',
250 input: {'text': 'Hello'},
251 headers: {
252 'Custom-Header': 'custom',
253 'Accept-Language': 'custom'
254
255 }
256}, function(err, result, response) {
257 if (err)
258 console.log('error:', err);
259 else
260 console.log(JSON.stringify(result, null, 2));
261});
262
263```
264
265### Parsing HTTP response
266
267To retrieve the HTTP response, all methods can be called with a callback function with three parameters, with the third being the response. Users for example may retrieve the response headers with this usage pattern.
268
269If using Promises, the parameter `return_response` must be added and set to `true`. Then, the result returned will be equivalent to the third argument in the callback function - the entire response.
270
271Here is an example of how to access the response headers for Watson Assistant:
272
273```js
274var assistant = new watson.AssistantV1({
275/* username, password, version, url, etc... */
276});
277
278assistant.message(params, function(err, result, response) {
279 if (err)
280 console.log('error:', err);
281 else
282 console.log(response.headers);
283});
284
285// using Promises
286
287params.return_response = true;
288
289assistant.message(params)
290 .then(response => {
291 console.log(response.headers);
292 })
293 .catch(err => {
294 console.log('error:', err);
295 });
296
297```
298
299### Data collection opt-out
300
301By default, [all requests are logged](https://console.bluemix.net/docs/services/watson/getting-started-logging.html). This can be disabled of by setting the `X-Watson-Learning-Opt-Out` header when creating the service instance:
302
303```js
304var myInstance = new watson.WhateverServiceV1({
305 /* username, password, version, url, etc... */
306 headers: {
307 "X-Watson-Learning-Opt-Out": true
308 }
309});
310```
311
312### Configuring the HTTP client
313
314The HTTP client can be configured to disable SSL verification. Note that this has serious security implications - only do this if you really mean to! ⚠️
315
316To do this, set `disable_ssl_verification` to `true` in the service constructor, like below:
317
318```
319const discovery = new DiscoveryV1({
320 url: '<service_url>',
321 version: '<version-date>',
322 iam_apikey: '<iam_api_key>',
323 disable_ssl_verification: true, // this will disable SSL verification for any request made with this object
324});
325```
326
327## Documentation
328
329You can find links to the documentation at https://console.bluemix.net/developer/watson/documentation. Find the service that you're interested in, click **API reference**, and then select the **Node** tab.
330
331There are also auto-generated JSDocs available at http://watson-developer-cloud.github.io/node-sdk/master/
332
333## Questions
334
335If you are having difficulties using the APIs or have a question about the Watson services, please ask a question at [dW Answers](https://developer.ibm.com/answers/questions/ask/?topics=watson) or [Stack Overflow](http://stackoverflow.com/questions/ask?tags=ibm-watson-cognitive).
336
337## IBM Watson services
338
339### Authorization
340
341The Authorization service can generate auth tokens for situations where providing the service username/password is undesirable.
342
343Tokens are valid for 1 hour and may be sent using the `X-Watson-Authorization-Token` header or the `watson-token` query param.
344Note that the token is supplied URL-encoded, and will not be accepted if it is double-encoded in a querystring.
345
346> _NOTE_: Authenticating with the `X-Watson-Authorization-Token` header or the `watson-token` query param is now deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. For details see [Authenticating with IAM tokens](https://console.bluemix.net/docs/services/watson/getting-started-iam.html#iam) or the README in the IBM Watson SDK you use.
347The Authorization SDK now supports returning IAM Access Tokens when instantiated with an IAM API key.
348
349```javascript
350var watson = require('watson-developer-cloud');
351
352// to get an IAM Access Token
353var authorization = new watson.AuthorizationV1({
354 iam_apikey: '<Service API key>',
355 iam_url: '<IAM endpoint URL - OPTIONAL>',
356});
357
358authorization.getToken(function (err, token) {
359 if (!token) {
360 console.log('error:', err);
361 } else {
362 // Use your token here
363 }
364});
365
366// to get a Watson Token - NOW DEPRECATED
367var authorization = new watson.AuthorizationV1({
368 username: '<Text to Speech username>',
369 password: '<Text to Speech password>',
370 url: 'https://stream.watsonplatform.net/authorization/api', // Speech tokens
371});
372
373authorization.getToken({
374 url: 'https://stream.watsonplatform.net/text-to-speech/api'
375},
376function (err, token) {
377 if (!token) {
378 console.log('error:', err);
379 } else {
380 // Use your token here
381 }
382});
383```
384
385### Assistant v2
386
387Use the [Assistant][conversation] service to determine the intent of a message.
388
389Note: You must first create a workspace via IBM Cloud. See [the documentation](https://console.bluemix.net/docs/services/conversation/index.html#about) for details.
390
391```js
392var AssistantV2 = require('watson-developer-cloud/assistant/v2');
393
394var assistant = new AssistantV2({
395 username: '<username>',
396 password: '<password>',
397 url: 'https://gateway.watsonplatform.net/assistant/api/',
398 version: '2018-09-19'
399});
400
401assistant.message(
402 {
403 input: { text: "What's the weather?" },
404 assistant_id: '<assistant id>',
405 session_id: '<session id>',
406 },
407 function(err, response) {
408 if (err) {
409 console.error(err);
410 } else {
411 console.log(JSON.stringify(response, null, 2));
412 }
413 }
414);
415```
416
417### Assistant v1
418
419Use the [Assistant][assistant] service to determine the intent of a message.
420
421Note: You must first create a workspace via IBM Cloud. See [the documentation](https://console.bluemix.net/docs/services/conversation/index.html#about) for details.
422
423```js
424var AssistantV1 = require('watson-developer-cloud/assistant/v1');
425
426var assistant = new AssistantV1({
427 username: '<username>',
428 password: '<password>',
429 url: 'https://gateway.watsonplatform.net/assistant/api/',
430 version: '2018-02-16'
431});
432
433assistant.message(
434 {
435 input: { text: "What's the weather?" },
436 workspace_id: '<workspace id>'
437 },
438 function(err, response) {
439 if (err) {
440 console.error(err);
441 } else {
442 console.log(JSON.stringify(response, null, 2));
443 }
444 }
445);
446```
447
448### Compare Comply
449
450Use the Compare Comply service to compare and classify documents.
451
452```javascript
453const fs = require('fs');
454const CompareComplyV1 = require('watson-developer-cloud/compare-comply/v1');
455
456const compareComply = new CompareComplyV1({
457 iam_apikey: '<iam_apikey>',
458 url: 'https://gateway.watsonplatform.net/compare-comply/api',
459 version: '2018-12-06'
460});
461
462compareComply.compareDocuments(
463 {
464 file_1: fs.createReadStream('<path-to-file-1>'),
465 file_1_filename: '<filename-1>',
466 file_1_label: 'file-1',
467 file_2: fs.createReadStream('<path-to-file-2>'),
468 file_2_filename: '<filename-2>',
469 file_2_label: 'file-2',
470 },
471 function(err, response) {
472 if (err) {
473 console.error(err);
474 } else {
475 console.log(JSON.stringify(response, null, 2));
476 }
477 }
478);
479
480```
481
482### Discovery
483
484Use the [Discovery Service][discovery] to search and analyze structured and unstructured data.
485
486```javascript
487var DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
488
489var discovery = new DiscoveryV1({
490 username: '<username>',
491 password: '<password>',
492 url: 'https://gateway.watsonplatform.net/discovery/api/',
493 version: '2017-09-01'
494});
495
496discovery.query(
497 {
498 environment_id: '<environment_id>',
499 collection_id: '<collection_id>',
500 query: 'my_query'
501 },
502 function(err, response) {
503 if (err) {
504 console.error(err);
505 } else {
506 console.log(JSON.stringify(response, null, 2));
507 }
508 }
509);
510
511```
512
513### Language Translator
514
515Translate text from one language to another or idenfity a language using the [Language Translator][language_translator] service.
516
517```javascript
518const LanguageTranslatorV3 = require('watson-developer-cloud/language-translator/v3');
519
520const languageTranslator = new LanguageTranslatorV3({
521 iam_apikey: '<apikey>',
522 url: 'https://gateway.watsonplatform.net/language-translator/api/',
523 version: 'YYYY-MM-DD',
524});
525
526languageTranslator.translate(
527 {
528 text: 'A sentence must have a verb',
529 source: 'en',
530 target: 'es'
531 },
532 function(err, translation) {
533 if (err) {
534 console.log('error:', err);
535 } else {
536 console.log(JSON.stringify(translation, null, 2));
537 }
538);
539
540languageTranslator.identify(
541 {
542 text:
543 'The language translator service takes text input and identifies the language used.'
544 },
545 function(err, language) {
546 if (err) {
547 console.log('error:', err);
548 } else {
549 console.log(JSON.stringify(language, null, 2));
550 }
551 }
552);
553```
554
555### Natural Language Classifier
556
557Use [Natural Language Classifier](https://console.bluemix.net/docs/services/natural-language-classifier/getting-started.html) service to create a classifier instance by providing a set of representative strings and a set of one or more correct classes for each as training. Then use the trained classifier to classify your new question for best matching answers or to retrieve next actions for your application.
558
559```javascript
560var NaturalLanguageClassifierV1 = require('watson-developer-cloud/natural-language-classifier/v1');
561
562var classifier = new NaturalLanguageClassifierV1({
563 username: '<username>',
564 password: '<password>',
565 url: 'https://gateway.watsonplatform.net/natural-language-classifier/api/'
566});
567
568classifier.classify(
569 {
570 text: 'Is it sunny?',
571 classifier_id: '<classifier-id>'
572 },
573 function(err, response) {
574 if (err) {
575 console.log('error:', err);
576 } else {
577 console.log(JSON.stringify(response, null, 2));
578 }
579 }
580);
581```
582
583See this [example](https://github.com/watson-developer-cloud/node-sdk/blob/master/examples/natural_language_classifier.v1.js) to learn how to create a classifier.
584
585
586### Natural Language Understanding
587
588Use Natural Language Understanding is a collection of natural language processing APIs that help you understand sentiment,
589 keywords, entities, high-level concepts and more.
590
591```javascript
592var fs = require('fs');
593var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
594
595var nlu = new NaturalLanguageUnderstandingV1({
596 username: '<username>',
597 password: '<password>',
598 version: '2018-04-05',
599 url: 'https://gateway.watsonplatform.net/natural-language-understanding/api/'
600});
601
602nlu.analyze(
603 {
604 html: file_data, // Buffer or String
605 features: {
606 concepts: {},
607 keywords: {}
608 }
609 },
610 function(err, response) {
611 if (err) {
612 console.log('error:', err);
613 } else {
614 console.log(JSON.stringify(response, null, 2));
615 }
616 }
617);
618```
619
620
621### Personality Insights
622
623Analyze text in English and get a personality profile by using the
624[Personality Insights][personality_insights] service.
625
626```javascript
627var PersonalityInsightsV3 = require('watson-developer-cloud/personality-insights/v3');
628
629var personalityInsights = new PersonalityInsightsV3({
630 username: '<username>',
631 password: '<password>',
632 version: '2016-10-19',
633 url: 'https://gateway.watsonplatform.net/personality-insights/api/'
634});
635
636personalityInsights.profile(
637 {
638 content: 'Enter more than 100 unique words here...',
639 content_type: 'text/plain',
640 consumption_preferences: true
641 },
642 function(err, response) {
643 if (err) {
644 console.log('error:', err);
645 } else {
646 console.log(JSON.stringify(response, null, 2));
647 }
648 }
649);
650```
651
652
653### Speech to Text
654
655Use the [Speech to Text][speech_to_text] service to recognize the text from a `.wav` file.
656
657```javascript
658var SpeechToTextV1 = require('watson-developer-cloud/speech-to-text/v1');
659var fs = require('fs');
660
661var speechToText = new SpeechToTextV1({
662 username: '<username>',
663 password: '<password>',
664 url: 'https://stream.watsonplatform.net/speech-to-text/api/'
665});
666
667var params = {
668 // From file
669 audio: fs.createReadStream('./resources/speech.wav'),
670 content_type: 'audio/l16; rate=44100'
671};
672
673speechToText.recognize(params, function(err, res) {
674 if (err)
675 console.log(err);
676 else
677 console.log(JSON.stringify(res, null, 2));
678});
679
680// or streaming
681fs.createReadStream('./resources/speech.wav')
682 .pipe(speechToText.recognizeUsingWebSocket({ content_type: 'audio/l16; rate=44100' }))
683 .pipe(fs.createWriteStream('./transcription.txt'));
684```
685
686
687### Text to Speech
688
689Use the [Text to Speech][text_to_speech] service to synthesize text into an audio file.
690
691```js
692var TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');
693var fs = require('fs');
694
695var textToSpeech = new TextToSpeechV1({
696 username: '<username>',
697 password: '<password>',
698 url: 'https://stream.watsonplatform.net/text-to-speech/api/'
699});
700
701var params = {
702 text: 'Hello from IBM Watson',
703 voice: 'en-US_AllisonVoice', // Optional voice
704 accept: 'audio/wav'
705};
706
707// Synthesize speech, correct the wav header, then save to disk
708// (wav header requires a file length, but this is unknown until after the header is already generated and sent)
709textToSpeech
710 .synthesize(params, function(err, audio) {
711 if (err) {
712 console.log(err);
713 return;
714 }
715 textToSpeech.repairWavHeader(audio);
716 fs.writeFileSync('audio.wav', audio);
717 console.log('audio.wav written with a corrected wav header');
718});
719
720
721// or, using WebSockets
722textToSpeech.synthesizeUsingWebSocket(params);
723synthStream.pipe(fs.createWriteStream('./audio.ogg'));
724// see more information in examples/text_to_speech_websocket.js
725```
726
727
728
729### Tone Analyzer
730
731Use the [Tone Analyzer][tone_analyzer] service to analyze the
732emotion, writing and social tones of a text.
733
734```js
735var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
736
737var toneAnalyzer = new ToneAnalyzerV3({
738 username: '<username>',
739 password: '<password>',
740 version: '2016-05-19',
741 url: 'https://gateway.watsonplatform.net/tone-analyzer/api/'
742});
743
744toneAnalyzer.tone(
745 {
746 tone_input: 'Greetings from Watson Developer Cloud!',
747 content_type: 'text/plain'
748 },
749 function(err, tone) {
750 if (err) {
751 console.log(err);
752 } else {
753 console.log(JSON.stringify(tone, null, 2));
754 }
755 }
756);
757```
758
759
760### Visual Recognition
761
762Use the [Visual Recognition][visual_recognition] service to recognize the
763following picture.
764
765<img src="https://visual-recognition-demo.ng.bluemix.net/images/samples/5.jpg" />
766
767```js
768var VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
769var fs = require('fs');
770
771var visualRecognition = new VisualRecognitionV3({
772 url: '<service_url>',
773 version: '2018-03-19',
774 iam_apikey: '<iam_api_key>',
775});
776
777var params = {
778 images_file: fs.createReadStream('./resources/car.png')
779};
780
781visualRecognition.classify(params, function(err, res) {
782 if (err) {
783 console.log(err);
784 } else {
785 console.log(JSON.stringify(res, null, 2));
786 }
787});
788```
789
790
791## Composing services
792
793### Integration of Tone Analyzer with Conversation
794Sample code for [integrating Tone Analyzer and Assistant][assistant_tone_analyzer_example] is provided in the [examples directory][examples].
795
796## Unauthenticated requests
797By default, the library tries to authenticate and will ask for `iam_apikey`, `iam_access_token`, or `username` and `password` to send an `Authorization` header. You can avoid this by using:
798
799`use_unauthenticated`.
800
801```javascript
802var watson = require('watson-developer-cloud');
803
804var assistant = new watson.AssistantV1({
805 use_unauthenticated: true
806});
807```
808
809## Debug
810
811This library relies on the `request` npm module writted by
812[request][request_github] to call the Watson Services. To debug the apps, add
813'request' to the `NODE_DEBUG` environment variable:
814
815```sh
816$ NODE_DEBUG='request' node app.js
817```
818where `app.js` is your Node.js file.
819
820## Tests
821Running all the tests:
822```sh
823$ npm test
824```
825
826Running a specific test:
827```sh
828$ jest '<path to test>'
829```
830
831## Open source @ IBM
832[Find more open source projects on the IBM Github Page.](http://ibm.github.io/)
833
834## License
835
836This library is licensed under Apache 2.0. Full license text is available in
837[COPYING][license].
838
839## Contributing
840
841See [CONTRIBUTING](https://github.com/watson-developer-cloud/node-sdk/blob/master/.github/CONTRIBUTING.md).
842
843[assistant]: https://www.ibm.com/watson/services/conversation/
844[discovery]: https://www.ibm.com/watson/services/discovery/
845[personality_insights]: https://www.ibm.com/watson/services/personality-insights/
846[visual_recognition]: https://www.ibm.com/watson/services/visual-recognition/
847[tone_analyzer]: https://www.ibm.com/watson/services/tone-analyzer/
848[text_to_speech]: https://www.ibm.com/watson/services/text-to-speech/
849[speech_to_text]: https://www.ibm.com/watson/services/speech-to-text/
850[language_translator]: https://www.ibm.com/watson/services/language-translator/
851[ibm_cloud]: https://console.bluemix.net
852[watson-dashboard]: https://console.bluemix.net/dashboard/apps?category=watson
853[npm_link]: https://www.npmjs.com/package/watson-developer-cloud
854[request_github]: https://github.com/request/request
855[examples]: https://github.com/watson-developer-cloud/node-sdk/tree/master/examples
856[document_conversion_integration_example]: https://github.com/watson-developer-cloud/node-sdk/tree/master/examples/document_conversion_integration.v1.js
857[assistant_tone_analyzer_example]: https://github.com/watson-developer-cloud/node-sdk/tree/master/examples/conversation_tone_analyzer_integration
858[license]: http://www.apache.org/licenses/LICENSE-2.0
859[vcap_services]: https://console.bluemix.net/docs/services/watson/getting-started-variables.html
860[ibm-cloud-onboarding]: http://console.bluemix.net/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Node
861