Simple Node.js server example using the Watson Assistant API v2

This blog post is about a simple example to use the Watson Assistant API v2 with the Node.js SDK to get a Watson Assistant sessionID and send a message to Watson Assistant using this sessionID. Here is the GitHub project watson-assistant-simple-node-js-server-example.

The objective is only to start a chat session and return the values we get from Watson Assistant API v2 methods. The simple Node.js server has implemented following REST endpoints :

The project contains examples for using Postman. 😉

The blog post is structured in:

  • Connect to an assistant in the right environment
  • Implement a simple endpoint
  • Use the example
  • Summary

Connect to an assistant in the right environment

Therefor we will first connect to our Watson Assistant service instance with the environmentID. Because we need to know to which environment we want to connect our server.

A small diagram with simplified dependencies. In my case I connected to the draft environment.

The GitHub project also contains a bash script to list the environments using cRUL.

The following code shows an extract of a return value of a bash script execution.

{"environments":[
    {"name":"draft",
     "description":"My Example Assistant",
     "environment":"draft",
     "assistant_id":"df8d00f8-e9cc-XXXXXXXX",
     "orchestration":{"search_skill_fallback":false},
     "environment_id":"3d6d1cd6-29fd-XXXXXXXX",
     "session_timeout":120,
      ...
}

The relevant code in server.js file to connect to the right environment of the Watson Assistant service.

const assistant = new AssistantV2({
    version: e_version,
    authenticator: new IamAuthenticator({
      apikey: e_apikey,
    }),
    serviceUrl: e_serverUrl,
  });

Implement a simple endpoint

When we are connected to the right assistant with the right environment, we can use this connection and we mostly just reuse the code given in the Watson Assistant API v2 documentation for the Node.js SDK in the implementation of our REST endpoint.

app.get('/getsession', (req, res) => {   
    assistant.createSession({
        assistantId: e_environmentID
    })
    .then(createSessionresult => {
        console.log(JSON.stringify(createSessionresult.result, null, 2));
        sessionID = JSON.stringify(createSessionresult.result, null, 2);
        res.statusCode = 200;
        res.write(sessionID);
        res.end();
    })
    .catch(createSessionError => {
        console.log(createSessionError);
        res.statusCode = 500;
        res.write(createSessionError);
        res.end();
    });  
});

This is a simplified diagram of the given dependencies of our scenario.

Use the example

Here are the steps you can follow to run this example on your local machine.

Step 1: Clone the project to your local computer

git clone https://github.com/thomassuedbroecker/
watson-assistant-simple-node-js-server-example.git
cd 
watson-assistant-simple-node-js-server-example/code/simple-server

Step 2: Configure the environment variables

Here we need an environmentID. We can find this ID in the Watson Assistant user interface, by navigating to the Environments page and selecting the environment you want to use (such as Draft or Live). Then you open the environment settings and copy the value from the appropriate field. (Contains the Link to the IBM Cloud documentation)

The image below shows the environment ID in the IBM Cloud UI.

We also need an API key and a base URL from the Credentials. The image blow shows the API key and the URL in the IBM Cloud UI.

  • Create an .env file
cat .env-template > .env
  • Configure the .env file to your needs
WATSON_ASSISTANT_VERSION='2021-11-27'
WATSON_ASSISTANT_API_KEY='XXXX'
WATSON_ASSISTANT_SERVICE_URL='https://api.us-south.assistant.watson.cloud.ibm.com'
WATSON_ASSISTANT_ENVIRONMENT_ID='XXX'

Step 3: Run local on port 3010

npm install
npm start

Step 4: Open browser and invoke the get session endpoint

It returns the newly created sessionID.

open http://localhost:3010/getsession
  • Example output:
{
"session_id": "37d13c72-1643-4add-bee5-574c6fd062dc"
}

Step 5: Import the postman collection into postman

The images shows the import button in postman.

Select the /postman/watson-assistant-example.postman_collection.json in the project for the import.

Step 6: After the import you have a new collection inside your postman

The images shows the imported collection.

Step 7: Send a message

Here again the simplified diagram of the given dependencies of our scenario.

Step 7.1: Get a sessionID

Now we need to get the sessionID with GET request using the getsession endpoint. We copy the value of the sessionID to use it inside the next REST endpoint invocation.

Step 7.2: Insert the session ID into the body of the POST request using the sendmessage endpoint

This is the JSON format which is used in the POST request sendmessage body in Postman. Now we insert the copied sessionID into the body of the request inside postman.

{ "sendmessage" : {
  "sessionID" : "XXXX",
  "message_type": "text",
  "text": "Hello"
  }
}

Now we see the output of the sendmessage request in the expected JSON format.

Summary

The usage of the Watson Assistant API v2 is very easy and good documented, but you need to understand the environment topic. At the moment the documentation talks about the assistantID to pass into an invocation as an example, this can cause a misunderstanding. Here a screen shot of the IBM Cloud documentation “createsession” created on 09.12.2022.



I hope this was useful for you and let’s see what’s next?

Greetings,

Thomas

#watsonassistant, #nodejs, #ibmcloud, #rest, #javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: