is an IBM Watson powered ChatBot running on Android and using Conversation Service on IBM Bluemix (an open standards, cloud platform for building, running, and managing apps and services).
Watson Conversation combines a number of cognitive techniques to help you build and train a bot - defining intents and entities and crafting dialog to simulate conversation.
Before you can start using the Conversation service, you must log in to IBM® Bluemix® and create a service instance.
- Log in to Bluemix and navigate to the Conversation service:
- In the Service name field, type a unique name for your new instance of the Conversation service. Check the “Pricing Plans” for data limits for the Conversation service
- Click Create. You’ll see details about your new instance in the “Service Details” page.
You use the Conversation tool to create workspaces. You can either create a new workspace from scratch, or you can import a workspace from a JSON file. You can also duplicate an existing workspace within the same service instance.
- If the Service Details page is not already open, click your Conversation service instance on the Bluemix console. (When you create a service instance, the Service Details page displays.)
- On the “Service Details” page, scroll down to Conversation tooling and click Launch tool.
- Click Create to create a new workspace.
- Specify the details for the new workspace:
- Name: A name no more than 64 characters in length. This value is required.
- Description: A description no more than 128 characters in length.
- Language: The language of the user input the workspace will be trained to understand. The service supports Brazilian Portuguese, English, French, Italian, and Spanish.
- Click Create. The new workspace is created and now appears as a tile on the Workspaces page.
You use the Conversation tool to create intents. The number of intents and examples you can create in a single service instance depends on your Conversation service plan:
Create some intents.
-
In the Conversation tool, open your workspace and then click the Intents tab.
-
Click Create new.
-
In the Intent name field, type a descriptive name for the intent. The intent name can contain letters (in Unicode), numbers, underscores, hyphens, and dots. Intent names cannot contain spaces and must not exceed 128 characters. The following are examples of intent names:
#weather_conditions#pay_bill#escalate_to_agent
Tip: Don’t include the
#character in the intent names when you create them in the Conversation tool. -
In the User example field, type the text of a user example for the intent. An example can be any string up to 1024 characters in length. The following might be examples for the
#pay_billintent:I need to pay my bill.Pay my account balancemake a payment
Important: Intent names and example text can be exposed in URLs when an application interacts with the service. Do not include sensitive or personal information in these artifacts.
Press Enter or click + to save the example.
-
Repeat the same process to add more examples. Provide at least 5 examples for each intent. The more examples you provide, the more accurate your application can be.
-
When you have finished adding examples, click Create to finish creating the intent.
The intent you created is added to the Intents tab, and the system begins to train itself on the new data.
You can click any intent in the list to open it for editing. You can make the following changes:
- Rename the intent.
- Delete the intent.
- Add, edit, or delete examples.
- Move an example to a different intent.
To move an example, select the example by clicking the check box and then click Move to.
After you have finished creating new intents, you can test the system to see if it recognizes your intents as you expect.
-
In the Try it out panel, enter a question or other text string and press Enter to see which intent is recognized. If the wrong intent is recognized, you can improve your model by adding this text as an example to the correct intent.
Tip: If you have recently made changes in your workspace, you might see a message indicating that the system is still retraining. If you see this message, wait until training completes before testing:
The response indicates which intent was recognized from your input.
-
If the system did not recognize the correct intent, you can correct it. To correct the recognized intent, click the displayed intent and then select the correct intent from the list. After your correction is submitted, the system automatically retrains itself to incorporate the new data.
If your intents are not being correctly recognized, consider making the following kinds of changes:
- Add the unrecognized text as an example to the correct intent.
- Move existing examples from one intent to another.
- Consider whether your intents are too similar, and redefine them as appropriate.
You use the Conversation tool to create entities. The number of entities, entity values, and synonyms you can create in a single service instance depends on your Conversation service plan:
-
In the Conversation tool, open your workspace and then click the Entities tab.
-
Click Create new.
-
In the Add the entity name field, type a descriptive name for the entity.
The entity name can contain letters (in Unicode), numbers, underscores, and hyphens. For example:
@location@menu_item@product
Tips:
- Don’t include the
@character in the entity names when you create them in the Conversation tool. - Entity names can’t contain spaces or be longer than 64 characters. And entity names can’t begin with the string
sys-, which is reserved for system entities.
-
In the Value field, type the text of a possible value for the intent. An entity value can be any string up to 64 characters in length.
Important: Don’t include sensitive or personal information in entity names or values. The names and values can be exposed in URLs in an app.
-
In the Synonyms field, type any synonyms for the entity value. A synonym can be any string up to 64 characters in length. Press Enter to save each synonym.
-
Click + and repeat the process to add more entity values.
-
When you are finished adding values and synonyms, click Create.
Post branching Intents and entities, this is how my Conversation Dialog on Bluemix looks like
Android Studio is the Official IDE for Android. Android Studio provides the fastest tools for building apps on every type of Android device.
Click here to download the starter code (.Zip). UnZip the code to a folder.
- Start Android Studio and close any open Android Studio projects.
- From the Android Studio menu click File > New > Import Project.
- Alternatively, from the Welcome screen, click Open an existing Android Studio Project
- Navigate to the folder where the code is downloaded and click OK
- Once gradle build is successful, Click Project on the left pane and navigate to Gradle Scripts -> build.gradle(Module: app) and check the dependencies for following dependencies.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:recyclerview-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'com.squareup.okhttp3:okhttp:3.4.2'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.ibm.watson.developer_cloud:conversation:3.5.1'
testCompile 'junit:junit:4.12'
}
Do a gradle build
-
Once gradle build is successful, Click Project on the left pane and navigate to app -> java
-
Go to the com.example.vmac.watbot - > MainActivity
Replace the existing code with,
import android.content.Context;
import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast;
import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse;
import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
private ArrayList messageArrayList;
private EditText inputMessage;
private ImageButton btnSend;
private Map<String,Object> context = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputMessage = (EditText) findViewById(R.id.message);
btnSend = (ImageButton) findViewById(R.id.btn_send);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(messageArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
btnSend.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(checkInternetConnection()) {
sendMessage();
}
}
});
};
// Sending a message to Watson Conversation Service
private void sendMessage() {
final String inputmessage = this.inputMessage.getText().toString().trim();
Message inputMessage = new Message();
inputMessage.setMessage(inputmessage);
inputMessage.setId("1");
messageArrayList.add(inputMessage);
this.inputMessage.setText("");
mAdapter.notifyDataSetChanged();
Thread thread = new Thread(new Runnable(){
public void run() {
try {
ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_09_20);
service.setUsernameAndPassword("<username>", "<password>");
MessageRequest newMessage = new MessageRequest.Builder().inputText(inputmessage).context(context).build();
MessageResponse response = service.message("<workspace_id>", newMessage).execute();
if(response.getContext() !=null)
{
context.clear();
context = response.getContext();
}
Message outMessage=new Message();
if(response!=null)
{
if(response.getOutput()!=null && response.getOutput().containsKey("text"))
{
final String outputmessage = response.getOutput().get("text").toString().replace("[","").replace("]","");
outMessage.setMessage(outputmessage);
outMessage.setId("2");
messageArrayList.add(outMessage);
}
runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount()-1);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
private boolean checkInternetConnection() {
// get Connectivity Manager object to check connection
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
// Check for network connections
if (isConnected){
return true;
}
else {
Toast.makeText(this, " No Internet Connection available ", Toast.LENGTH_LONG).show();
return false;
}
}
}
* Right click on com.example.vmac.watbot package and select New -> Java Class and name it as <strong>Message</strong>
<p>Add the Following code to the class,</p>
import java.io.Serializable;
public class Message implements Serializable {
String id, message;
public Message() {
}
public Message(String id, String message, String createdAt) {
this.id = id;
this.message = message;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
* Right click on com.example.vmac.watbot package and select New -> Java Class and name it as <strong>ChatRoomThreadAdapter</strong>
<p>Add the following code to the class,</p>
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class ChatRoomThreadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int SELF = 100;
private ArrayList<Message> messageArrayList;
public class ViewHolder extends RecyclerView.ViewHolder {
TextView message;
public ViewHolder(View view) {
super(view);
message = (TextView) itemView.findViewById(R.id.message);
}
}
public ChatRoomThreadAdapter(ArrayList<Message> messageArrayList) {
this.messageArrayList=messageArrayList;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// view type is to identify where to render the chat message
// left or right
if (viewType == SELF) {
// self message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_self, parent, false);
} else {
// WatBot message
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_item_watson, parent, false);
}
return new ViewHolder(itemView);
}
@Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if (message.getId().equals("1")) {
return SELF;
}
return position;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
((ViewHolder) holder).message.setText(message.getMessage());
}
@Override
public int getItemCount() {
return messageArrayList.size();
}
}
## Configure the App
<p>To configure the App you need to get the Watson Conversation service <strong>Username</strong>, <strong>PassWord</strong> and <strong>WorkSpaceId</strong></p>
* In the <strong>MainActivity</strong> class locate the function named <strong>sendMessage()</strong>.
ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_09_20);
service.setUsernameAndPassword("Your Watson service UserName", "Your watson service PassWord");
MessageRequest newMessage = new MessageRequest.Builder().inputText(inputmessage).build();
MessageResponse response = service.message("Your Workspace Id", newMessage).execute();
* Go to the Conversation service , and select the <strong>Service Credentials</strong> tab. Select <strong>password</strong> and <strong>username</strong>.

</p>Add the `password` and `username` in the following code,</p>
service.setUsernameAndPassword("Your Watson service UserName", "Your watson service PassWord");
* Next is to get the <strong>workspace Id</strong>.
<p>Launch the conversation service workspace and from the options select the <strong>View details</strong>.</p>
<p align="center">
<img src="https://github.com/VidyasagarMSC/WatBot/blob/initial/Images/workspace1.png" width="350">
<img src="https://github.com/VidyasagarMSC/WatBot/blob/initial/Images/workspace2.png" width="350">
</p>
<p>Get the <strong>Workspace ID:</strong> and add it in the below code,</p>
MessageResponse response = service.message("Your Workspace Id", newMessage).execute();
* Build and Run your app.
## Chat with your own WatBot
If you have followed all the above instructions, you should be happily chatting with your Wat(son)Bot.
** Remember your bot will be talking to your Conversation Service (Intents, Entities and Dialog).**
### Don't stop here!!! Keep coding and using Bluemix











