:comet: Node.js library to access IBM Watson services.
:comet: Node.js library to access IBM Watson services.
Node.js client library to use the Watson APIs.
npm install ibm-watsonimport AssistantV2 from 'ibm-watson/assistant/v2';
import { IamAuthenticator } from 'ibm-watson/auth';
const assistantClient = new AssistantV2({
authenticator: new IamAuthenticator({ apikey: '{apikey}' }),
version: '{version}',
});
// ...
The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have service credentials.
Starting with v5.0.0, the SDK should work in the browser, out of the box, with most bundlers.
See the examples/ folder for Browserify and Webpack client-side SDK examples (with server-side generation of auth tokens.)
Note: not all services currently support CORS, and therefore not all services can be used client-side. Of those that do, most require an auth token to be generated server-side via the Authorization Service.
Watson services are migrating to token-based Identity and Access Management (IAM) authentication.
Authentication is accomplished using dedicated Authenticators for each authentication scheme. Import authenticators from ibm-watson/auth or rely on externally-configured credentials which will be read from a credentials file or environment variables.
To learn more about the Authenticators and how to use them with your services, see the detailed documentation.
To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:
On this page, you should be able to see your credentials for accessing your service instance.
In your code, you can use these values in the service constructor or with a method call after instantiating your service.
There are two ways to supply the credentials you found above to the SDK for authentication:
With 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.
The 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):
IBM_CREDENTIALS_FILEAs 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 Assistant instance, you just need to do the following:
const AssistantV2 = require('ibm-watson/assistant/v2');
const assistant = new AssistantV2({ version: '2024-08-25' });And that's it!
If 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.
Special Note: Due to legacy issues in Assistant V1 and V2, the following parameter serviceName must be added when creating the service object:
const AssistantV2 = require('ibm-watson/assistant/v2');
const assistant = new AssistantV2({
version: '2024-08-25',
serviceName: 'assistant',
})It is worth noting that if you are planning to rely on VCAP_SERVICES for authentication then the serviceName parameter MUST be removed otherwise VCAP_SERVICES will not be able to authenticate you. See Cloud Authentication Prioritization for more details.
If 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:
export IBM_CREDENTIALS_FILE="<path>"where <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.
The SDK also supports setting credentials manually in your code, using an Authenticator.
Some 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.
To use IAM authentication, you must use an IamAuthenticator or a BearerTokenAuthenticator.
IamAuthenticator 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.BearerTokenAuthenticator if you want to manage the lifecycle yourself. For details, see Authenticating with IAM tokens. If you want to switch your authenticator, you must override the authenticator property directly.To use the SDK in a Cloud Pak, use the CloudPakForDataAuthenticator. This will require a username, password, and URL.
To use the SDK through a third party cloud provider (such as AWS), use the MCSPAuthenticator. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey.
import AssistantV2 from 'ibm-watson/assistant/v2'
import { McspAuthenticator } from 'ibm-watson/auth';
# In the constructor, letting the SDK manage the token
const authenticator = new McspAuthenticator({
url: 'token_service_endpoint',
apikey: 'apikey',
})
const assistant = AssistantV2(version='2024-08-25',
authenticator=authenticator)
assistant.setServiceUrl('<url_as_per_region>')When uploading your application to IBM Cloud there is a certain priority Watson services will use when looking for proper credentials. The order is as follows:
You can set or reset the base URL after constructing the client instance using the setServiceUrl method:
const AssistantV2 = require('ibm-watson/assistant/v2');
const assistant = AssistantV2({
/* authenticator, version, etc... */
});
assistant.setServiceUrl('<new url>');All 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 with Promises.
const AssistantV2 = require('ibm-watson/assistant/v2');
const assistant = new AssistantV2({
/* authenticator, version, serviceUrl, etc... */
});
// using Promises
assistant.listAssistants()
.then(body => {
console.log(JSON.stringify(body, null, 2));
})
.catch(err => {
console.log(err);
});
// using Promises provides the ability to use async / await
async function callAssistant() { // note that callAssistant also returns a Promise
const body = await assistant.listAssistants();
}Custom 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.
For 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.
const assistant = new watson.AssistantV2({
/* authenticator, version, serviceUrl, etc... */
});
assistant.message({
workspaceId: 'something',
input: {'text': 'Hello'},
headers: {
'Custom-Header': 'custom',
'Accept-Language': 'custom'
}
})
.then(response => {
console.log(JSON.stringify(response.result, null, 2));
})
.catch(err => {
console.log('error: ', err);
});The SDK now returns the full HTTP response by default for each method.
Here is an example of how to access the response headers for Watson Assistant:
const assistant = new AssistantV2({
/* authenticator, version, serviceUrl, etc... */
});
assistant.message(params).then(
response => {
console.log(response.headers);
},
err => {
console.log(err);
/*
`err` is an Error object. It will always have a `message` field
and depending on the type of error, it may also have the following fields:
- body
- headers
- name
- code
*/
}
);Every SDK call returns a response with a transaction ID in the X-Global-Transaction-Id header. Together with the service instance region, this ID helps support teams troubleshoot issues from relevant logs.
const assistant = new AssistantV2({
/* authenticator, version, serviceUrl, etc... */
});
assistant.message(params).then(
response => {
console.log(response.headers['X-Global-Transaction-Id']);
},
err => {
console.log(err);
}
);const speechToText = new SpeechToTextV1({
/* authenticator, version, serviceUrl, etc... */
});
const recognizeStream = recognizeUsingWebSocket(params);
// getTransactionId returns a Promise that resolves to the ID
recognizeStream.getTransactionId().then(
globalTransactionId => console.log(globalTransactionId),
err => console.log(err),
);However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace <my-unique-transaction-id> in the following example with a unique transaction ID.
const assistant = new AssistantV2({
/* authenticator, version, serviceUrl, etc... */
});
assistant.message({
workspaceId: 'something',
input: {'text': 'Hello'},
headers: {
'No open issues yet, or sync has not completed.