March 3, 2017 By Vidyasagar Machupalli 3 min read

Importance of context in a chatbot conversation

// maintains state.<p></p>
<p>var prompt = require('prompt-sync')();<br>
var ConversationV1 = require('watson-developer-cloud/conversation/v1');</p>
<p>// Set up Conversation service.<br>
var conversation = new ConversationV1({<br>
  username: 'USERNAME', // replace with username from service key<br>
  password: 'PASSWORD', // replace with password from service key<br>
  path: { workspace_id: 'WORKSPACE_ID' }, // replace with workspace ID<br>
  version_date: '2016-07-11'<br>
});</p>
<p>// Start conversation with empty message.<br>
conversation.message({}, processResponse);</p>
<p>// Process the conversation response.<br>
function processResponse(err, response) {<br>
  if (err) {<br>
    console.error(err); // something went wrong<br>
    return;<br>
  }</p>
<p>  // If an intent was detected, log it out to the console.<br>
  if (response.intents.length &gt; 0) {<br>
    console.log('Detected intent: #' + response.intents[0].intent);<br>
  }</p>
<p>  // Display the output from dialog, if any.<br>
  if (response.output.text.length != 0) {<br>
      console.log(response.output.text[0]);<br>
  }</p>
<p>  // Prompt for the next round of input.<br>
    var newMessageFromUser = prompt('&gt;&gt; ');<br>
    // Send back the context to maintain state.<br>
    conversation.message({<br>
      input: { text: newMessageFromUser },<br>
      context : response.context,<br>
    }, processResponse)<br>
}</p>

This post introduces the Importance of Context to maintain the state of a Conversation while building a bot more specifically a chatbot.

A conversation (or chat) is a chain of statements exchanged between two or more individuals. Mostly, conversations happen on a particular topic or in a situation. Whatever the topic or situation is, Context is very important to maintain the state of a conversation.

In the world of cognitive computing, computers are conversing with humans as ChatBots or in short Bots. As Alan Turing famously quoted

A computer would deserve to be called intelligent if it could deceive a human into believing that it was human.

So, even computers need the so called Context to keep the conversation flowing and to deceive us as humans.

Why am I so contextual today? Looks like chatting with a Bot for a week took a toll on me or reading the below line from the Watson Conversation documentation had its impact,

State information for your conversation is maintained using the context. The context is a JSON object that is passed back and forth between your application and the Conversation service. It is the responsibility of your application to maintain the context from one turn of the conversation to the next.

Technically,

A context includes a unique identifier for each conversation with a user, as well as a counter that is incremented with each turn of the conversation. If we don’t preserve the context,  each round of input appeared to be the start of a new conversation. We can fix that by saving the context and sending it back to the Conversation service each time.

Code to achieve Context persistence

In Javascript,

// maintains state.<p></p>
<p>var prompt = require('prompt-sync')();<br>
var ConversationV1 = require('watson-developer-cloud/conversation/v1');</p>
<p>// Set up Conversation service.<br>
var conversation = new ConversationV1({<br>
  username: 'USERNAME', // replace with username from service key<br>
  password: 'PASSWORD', // replace with password from service key<br>
  path: { workspace_id: 'WORKSPACE_ID' }, // replace with workspace ID<br>
  version_date: '2016-07-11'<br>
});</p>
<p>// Start conversation with empty message.<br>
conversation.message({}, processResponse);</p>
<p>// Process the conversation response.<br>
function processResponse(err, response) {<br>
  if (err) {<br>
    console.error(err); // something went wrong<br>
    return;<br>
  }</p>
<p>  // If an intent was detected, log it out to the console.<br>
  if (response.intents.length &gt; 0) {<br>
    console.log('Detected intent: #' + response.intents[0].intent);<br>
  }</p>
<p>  // Display the output from dialog, if any.<br>
  if (response.output.text.length != 0) {<br>
      console.log(response.output.text[0]);<br>
  }</p>
<p>  // Prompt for the next round of input.<br>
    var newMessageFromUser = prompt('&gt;&gt; ');<br>
    // Send back the context to maintain state.<br>
    conversation.message({<br>
      input: { text: newMessageFromUser },<br>
      context : response.context,<br>
    }, processResponse)<br>
}</p>

 

In Android, using Watson Developer Cloud Java SDK

private Map&lt;String,Object&gt; context = new HashMap&lt;&gt;();<p></p>
<p> ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_09_20);<br>
 service.setUsernameAndPassword(&quot;Your Watson service UserName&quot;, &quot;Your watson service PassWord&quot;);<br>
 MessageRequest newMessage = new MessageRequest.Builder().inputText(inputmessage).context(context).build();<br>
 MessageResponse response = service.message(&quot;Your Workspace Id&quot;, newMessage).execute();</p>
<p>   //Passing Context of last conversation<br>
    if(response.getContext() !=null)<br>
      {<br>
        context.clear();<br>
        context = response.getContext();</p>
<p>     }</p>

 

Check the complete Android code –  ChatBot Repo on Github

In Swift 3.0,  using swift watson sdk

import Conversation<p></p>
<p>let username = &quot;your-username-here&quot;<br>
let password = &quot;your-password-here&quot;<br>
let version = &quot;YYYY-MM-DD&quot; // use today's date for the most recent version<br>
let conversation = Conversation(username: username, password: password, version: version)</p>
<p>let workspaceID = &quot;your-workspace-id-here&quot;<br>
let failure = { (error: RestError) in print(error) }<br>
var context: Context? // save context to continue conversation<br>
conversation.message(workspaceID, failure: failure) { response in<br>
    print(response.output.text)<br>
    context = response.context<br>
}</p>

In addition to maintaining our place in the conversation, the context can also be used to store any other data you want to pass back and forth between your application and the Conversation service. This can include persistent data you want to maintain throughout the conversation (such as a customer’s name or account number), or any other data you want to track (such as the current status of option settings).

Additionally,

  • Check Code Samples leveraging the power of Watson conversation Service on IBM Cloud.

  • Watson Developer Cloud SDKs 

Build your own chatbot

Was this article helpful?
YesNo

More from

Introducing probable root cause: Enhancing Instana’s Observability

3 min read - We are thrilled to announce an enhancement to Instana® with the introduction of the probable root cause capability, now available in public preview starting from release 277. This capability delivers superior insights, allowing quick identification of the source of a system fault—with little to no investigation time. Probable root cause Working with IBM Research®, we designed an algorithm that use causal AI and differential observability to analyze data modalities such as traces and topology to identify unhealthy entities after an…

Revolutionizing community access to social services: IBM and Microsoft’s collaborative approach

5 min read - In an era when technological advancements and economic growth are often hailed as measures of success, it is essential to pause and reflect on the underlying societal challenges that these advancements often overlook. And to consider how they can be used to genuinely improve the human condition. IBM Consulting® and Microsoft together with government leaders, are answering that call, partnering to develop a platform to bridge the division and enhance the delivery of social services support to communities in need.…

Optimizing data flexibility and performance with hybrid cloud 

3 min read - As the global data storage market is set to more than triple by 2032, businesses face increasing challenges in managing their growing data. This shift to hybrid cloud solutions is transforming data management, enhancing flexibility and boosting performance across organizations.   By focusing on five key aspects of cloud adoption for optimizing data management—from evolving data strategies to ensuring compliance—businesses can create adaptable, high performing data ecosystems that are primed for AI innovation and future growth.  1. The evolution of data…

IBM Newsletters

Get our newsletters and topic updates that deliver the latest thought leadership and insights on emerging trends.
Subscribe now More newsletters