What do I have to do for the continuous conversation of watson chatbot?
I want to have a continuous conversation with watson chatbot.
current situation : The chatbox does not remember the status of the conversation you previously sent.
I installed the Django framework on the server and created a watson.py file to load the workspace and work with KakaoTalk, a Korean chat application.
The chatbot's conversation flow that I want is as follows.
User: I want to make a reservation
Chatbot: When is the meeting date?
User: tomorrow
Chatbot: How is your meeting time?
User: 14:00
We need your help very much.
watson.py
import json
from watson_developer_cloud import ConversationV1
from .models import Test
from . import views
import simplejson
conversation = ConversationV1(
username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
password = "xxxxxxxxxxxxxxxxxxxxxx",
version = '2017-05-26' )
workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' #workspace
def test(return_str):
result = ''
except Exception as err:
pass
response = conversation.message(
workspace_id = workspace_id,
message_input = {'text': return_str},
)
for i in range(len(response['output']['text'])):
result += response['output']['text'][i] +'\n'
return result
views.py
import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Jidum, Test
from . import watson
# Create your views here.
def keyboard(request):
return JsonResponse({
'type':'text',
})
@csrf_exempt
def message(request):
message = ((request.body).decode('utf-8'))
return_json_str = json.loads(message)
return_str = return_json_str['content']
return JsonResponse({
'message': {
'text': watson.test(return_str),
},
'keyboard': {
'type':'text',
},
})
Answer
To have a continuous conversation with Watson that maintains the context of the conversation (i.e., remembering previous interactions such as the meeting date and time), you need to implement context management within your watson.py
and views.py
files.
In IBM Watson's Conversation service, the concept of "context" is critical. The context object helps the service remember past conversation states. When you send a message to Watson, you also pass the context from the previous message, so Watson can continue the conversation flow. Without passing the context, Watson will treat each message as an isolated interaction.
Here’s how you can modify your code to handle the context and ensure continuous conversation:
Steps:
- Keep Track of Context: You'll need to store the context of the conversation and send it back with each new message to maintain the conversation flow.
- Send Context to Watson: You need to include the context from the previous response in the next
conversation.message()
call.
Updated watson.py
:
You can modify watson.py
to keep track of the context and pass it with every call to Watson. The conversation.message()
method has a context
parameter, which is where you pass the context of the previous message.
import json
from watson_developer_cloud import ConversationV1
from .models import Test
from . import views
import simplejson
conversation = ConversationV1(
username="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
password="xxxxxxxxxxxxxxxxxxxxxx",
version="2017-05-26"
)
workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Workspace ID
# Store context globally or in some session-like storage (depends on your setup)
conversation_context = {}
def test(return_str, context=None):
# If no context is provided, use the global context
if context is None:
context = conversation_context
result = ''
try:
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': return_str},
context=context # Pass the context to Watson
)
# Save the updated context for the next call
conversation_context.update(response.get('context', {}))
# Build the response text
for text in response['output']['text']:
result += text + '\n'
except Exception as err:
result = f"Error: {str(err)}"
return result, conversation_context
Explanation:
- Storing Context: We added a global
conversation_context
variable to store the context of the conversation. Each time you calltest()
, you pass the context to Watson, and Watson updates the context with each response. - Passing Context: The context returned from Watson (
response.get('context', {})
) is saved and passed back with the next message, allowing Watson to maintain conversation flow.
Updated views.py
:
You need to update your views.py
to handle the context properly. Every time you receive a new message from the user, you should call the test()
function with the correct context.
import json
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Jidum, Test
from . import watson
# Create your views here.
def keyboard(request):
return JsonResponse({
'type': 'text',
})
@csrf_exempt
def message(request):
message = (request.body).decode('utf-8')
return_json_str = json.loads(message)
return_str = return_json_str['content']
# Retrieve the context from the session (or store it in the session)
# You may want to store the context in the user session or database
context = None # Replace with logic to get the context from the session
# Get the chatbot response and the updated context
response_text, updated_context = watson.test(return_str, context)
# Save the updated context for the next interaction
# For example, store updated_context in the session or database
return JsonResponse({
'message': {
'text': response_text,
},
'keyboard': {
'type': 'text',
},
})
Explanation:
- Retrieve Context: In the
message()
function, you retrieve the context for the user. This could be from a session, database, or memory. In the example above,context = None
is a placeholder, and you would replace it with your actual logic for retrieving the context. - Pass Context: The context is passed to
watson.test()
. After Watson processes the message, you get both the response and the updated context. - Store Context: You then store the updated context (either in the session, a database, or elsewhere) to be used in the next request.
How to Store the Context:
- Session Storage: If you’re using Django's session framework, you can store the context in the session:
And then retrieve it like this:request.session['conversation_context'] = updated_context
context = request.session.get('conversation_context', None)
- Database: If you want to persist the context across different devices or sessions, you can store it in your database associated with the user.
Final Notes:
- The context object that is returned by Watson contains information about the current state of the conversation, including entities, intents, and variables. You need to pass this context with each new message so Watson knows how to respond.
- If you don’t pass the context, Watson will treat every new message as if it’s the start of a new conversation, which is why the conversation flow would be lost.
- For better persistence, you may consider using Django’s
session
to keep track of each user's conversation state, especially if users are interacting across multiple devices.
With these changes, Watson should now be able to remember the conversation state and maintain a continuous conversation.