Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building Cognitive Apps Using IBM Bluemix

DZone's Guide to

Building Cognitive Apps Using IBM Bluemix

See how IBM's cloud accents its cognitive services as we build a simple conversation app, complete with a guide for user interaction.

· Cloud Zone ·
Free Resource

Insight into the right steps to take for migrating workloads to public cloud and successfully reducing cost as a result. Read the Guide.

If cloud was a term you were getting used to in the world of IT, there is another bit of jargon that has created buzz lately. Cognitive computing, or cognitive services, is the buzz that you hear everywhere. In this blog post, I take a dive into the world of cognitive computing using IBM Bluemix and Watson Services on Bluemix. Let’s start the journey.

Cognitive Computing

If you are not familiar with the term cognitive computing, don’t worry. We will figure it out together as we proceed. The first thing I did was to check the dictionary of the web – Wikipedia. According to Wikipedia, cognitive computing is defined as follows:

“New hardware/software that mimics the functioning of human brain and helps to improve human decision-making. Cognitive Computing is all about trying to build accurate models of how human brain/mind senses, reasons and responds to stimulus”.

Some real-world use cases that apply cognitive computing are:

  • Conversations
  • Speech recognition
  • Sentiment analysis
  • Face detection
  • Recommendations

Cognitive Computing in IBM Bluemix

On Bluemix (IBM’s Cloud), IBM is offering cognitive computing services using what is popularly called Watson APIs. Watson is nothing but a set of open APIs and SaaS products. Key features of Watson APIs and products are as follows:

  • Understanding all forms of data. This includes unstructured text, images, audio, and video.
  • Interact naturally with people. Conversation APIs help you build chat bots and engage in dialogue.
  • Learn and reason. Use machine learning to improve subject matter expertise and offer recommendations.

You get all the above features at scale. IBM makes sure that Watson services scale as your business needs scale. IBM manages the scaling while you manage your business needs.

Watson APIs and Services

Some of the Watson APIs and services we will be considering in this post are listed below:

  • Conversation
  • Visual Recognition
  • Text to Speech
  • Language Translator
  • Tone Analyzer
  • Personality Insights

For a complete list of APIs and services, you can have a look at the Watson product offering page here.

Prerequisites

For the rest of the blog post, I am assuming that you have a Bluemix account. If not, head over to https://console.bluemix.net/  and create a free account for yourself. It will be easier to follow the rest of the post if you have your own Bluemix account and log in.

Conversation Service

The first service we will look at is Watson Conversation. With the Conversation service, you can quickly build and deploy chat bots or virtual agents. These chat bots/agents can be made available across a variety of channels such as mobile devices and messaging platforms. Let’s start by building a simple conversation bot using this service. Let’s get started.

Creating a Conversation Service

Log into the Bluemix console with your credentials. Click on the “Catalog” menu. Select “Watson” from the Services category. You will be presented with all the services available under Watson. You will see Conversation as one of the services. Click on Conversation.

clip_image002

Next, we will need to provide a name for our service. Click create once you're done.

clip_image002[6]

Bluemix will go ahead and get the service ready in our console. To work with the Conversation API, we will need to use a separate tool. Click on the Launch tool button.

image

Watson Conversation Tool

In the Watson Conversation tool, we will need to first create a workspace for our app. This workspace is like a container for our app and will hold all the Watson artifacts for the app. Give a name for your container and a description and click Create.

clip_image002[8]

Below is a screenshot of the Watson Conversation tool interface:

clip_image004

Creating Intents

Next, we create Intents. An Intent is nothing but the purpose of a user’s input or actions that the user wants to perform. To keep it simple, I will create two intents – one for saying Hello and one for saying Goodbye. Click “Create new” in the Intents tab.

Name the Intent hello. To make the conversation service learn what "hello" is, enter phrases such as “hello”, “Hi” – anything that depicts the Intent hello. Enter these phrases in the user example.

clip_image002[10]

Similarly, create two more intents named time and goodbye. And add user examples that depict the Intents time and goodbye.

clip_image004[5]

Now we have three intents created – hello, time, and goodbye. Your intent tab should look like below:

clip_image006

Creating Dialogues

Next, we will need to build a dialogue. A dialogue in Watson is nothing but a conversation flow. We define the conversation flow in a logical tree format. Select the Dialog tab and click Create to add new dialog.

We will have two nodes in the logical tree – “Welcome” and “Anything else”.  The“Welcome” node contains a greeting that is displayed when a user engages with the conversation bot. “Anything else” contains phrases that the bot uses when user input is not recognized.

clip_image002[12]

Next, we will add three nodes to handle our hello, time, and goodbye Intents. Hello is to greet the user, Time handles a user’s question on the current time, and Goodbye handles exits.

Click the More icon on the Welcome node and then select “Add node below”. Give a name for the Intent. In this case, we will name it Hello. Then select the intent #hello in the condition. Add a response phrase – let’s say “Good day to you”. Click the big X to finish adding the node.

clip_image004[7]

Similarly, add nodes for the Time and Goodbye Intents. Provide a response phrase for the dialogues created for Time and Goodbye intent.

clip_image006[5]

Try It Out

Now that we have finished adding the Intents and dialogues, it’s time to test the Intent recognition and dialogue rendering. Click the chat icon found at the right-hand top corner of the page. We will be presented with the “Try it out” pane. Here, we can enter inputs as if a user is typing it out. We will see that the Watson conversation service detects the right Intent and the response phrase we have added for the Intent is presented to the user.

clip_image002[14]

With the above steps, we just finished creating a simple conversation with two Intents – Hello and Goodbye. Now that our conversation service is in place, you can deploy this to any channels of your choice to create a bot.

Client Application to Consume Conversation API

Now that we have a simple conversation service set up, it’s time to create a client application that can consume it. I have chosen Node as the platform to write a simple client application. You will need to install Node on your system to follow the code below. Let’s see what it takes to build the client app.

Create a new folder in your system and give it a name of your choice. Open a command prompt, navigate to your newly created folder, and execute command – “npm”. NPM will ask you some questions. Provide the answers and, once done, you will have a package.json file created. Next, let’s install Watson-developer-cloud and prompt-sync package. Execute the following command:

npm install watson-developer-cloud prompt-sync –save


Watson-developer-cloud package will provide us with the API required to communicate with our conversation service. Prompt sync package provides the API for prompting users for input. Now, create a new file and name it index.js. We will add code in index.js to communicate with the service. Add the following code to initialize the Conversation API:

var prompt = require(‘prompt - sync’)();
var ConversationV1 = require(‘watson - developer - cloud / conversation / v1′);
ConversationV1.URL = ‘ < Watson Conversation Service URL > ';

// Set up Conversation service wrapper.
var conversation = new ConversationV1({
            username: ‘ < your user name > ’, // replace with username from service key
            password: ‘ < your password > ’, // replace with password from service key
            path: {
                workspace_id: '<your workspace id>’ }, // replace with workspace ID
                    version_date: ConversationV1.VERSION_DATE_2016_07_11
            });


Watson Conversation URL, your username/password, and your workspace id can be found in your Watson Conversation service tool. Click on the Deploy icon and you will be presented with these details:

clip_image002[16]

Next, we start the conversation by sending an empty message to our service. Add the following line of code:

conversation.message({}, processResponse);


We handle the response from the service in a function named processResponse. Let’s see the code for processResponse:

function processResponse(err, response) {
    var endConversation = false;
    if (err) {
        console.error(err); // something went wrong
        return;
    }
    var message = “”;
    if (response.output.text.length != 0) {
        message = response.output.text[0];
    }
    // If an intent was detected, log it out to the console.
    if (response.intents.length > 0) {
        console.log(‘Detected intent: #’+response.intents[0].intent);
        if (response.intents[0].intent === ‘time’)
            message = new Date().toLocaleTimeString();
        if (response.intents[0].intent === ‘goodbye’)
            endConversation = true;
    }
    console.log(message);

    // Prompt for the next round of input.
    if (!endConversation) {
        var newMessageFromUser = prompt(‘ >> ‘);
        conversation.message({
            input: {
                text: newMessageFromUser
            }
        }, processResponse)
    }
}


The code above is self-explanatory. We take user input and post it to our conversation service. The Conversation service detects the Intent from users' input. We check the intent through the response object of our Conversation service. If the intent was “Hello”, we show the response phrase from the service. If the Intent was detected as Time, we show the local time to the user. We prompt the user for input until we see that the Intent entered by the user was Goodbye. Here is a screenshot of the dialogue output with our conversation service:

clip_image002[18]

Notice how the Conversation service detects Intents outside of the defined ones and can return an appropriate response.

Summary

Watson Cognitive Services are a bunch of APIs that are available as services on the IBM Bluemix cloud. We looked at one of the interesting services, namely Conversation, in this blog post. This was my first time exploring the cognitive services from IBM Bluemix, and so far, the experience of using the service has been good. I could get up and running with the service without much hassle. As you have seen from the above sections, I was able to create the Conversation service without writing a single line of code. Of course, the service I created was a Hello World experience but if that’s made difficult – my impression on using the service would have varied to a large extent. Also, we saw that consuming the conversation service within your app is also super easy. With the Node package, I could write 10 lines of code and create a simple chat experience in no time.

What I showcased was a simple conversation, but the potential of the Watson Conversation API is left to your imagination.

TrueSight Cloud Cost Control provides visibility and control over multi-cloud costs including AWS, Azure, Google Cloud, and others.

Topics:
cloud ,ibm bluemix ,cognitive computing ,watson ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}