fbpx
Introduction to IBM Assistant Introduction to IBM Assistant
IBM Assistant is a chatbot service that many companies are deploying either on their websites or their portal. IBM Watson is providing cloud services,... Introduction to IBM Assistant

IBM Assistant is a chatbot service that many companies are deploying either on their websites or their portal. IBM Watson is providing cloud services, one of them is to build chatbots and you can deploy it either on the website or make a window application. In this blog, our main focus is on how to deploy already built IBM assistant using Python as a window application. 

[Related Article: Jupyter Notebook: Python or R—Or Both?]

Requirements

  1. Python 3.6
  2. Ibm_watson API
  3. Sqlite3
  4. Pandas

Get ibm_watson -> pip install ibm-watson (For more information -> Reference link https://pypi.org/project/ibm-watson/)

Sqlite3 is for storing context variables (present in IBM assistant) into the database.

To open up the database, you can download DB Browser for SQLite.

You can download its executable file from here -:

https://download.sqlitebrowser.org/SQLiteDatabaseBrowserPortable_3.11.2_English.paf.exe

After downloading just go to the downloaded folder and open up the application.

How to deploy IBM Assistant as a standalone application?

For this blog, let’s say you have created a chatbot for retail industry which will take some user information like name, phone numbers etc.

So, first, we are setup will all the packages we need.

Apart from that, we need credentials given by Watson while building chatbots.

So, we have APIKey, URL.

IBM Assistant

Other details are also present like Assistant ID etc.

So, just launch your assistant and go to the assistant tab. In that, you will have options like setting in the right corner. Like below shown -:

After that in settings go to API details tab. You will get all the details.

Let’s start coding

 

## Importing all the required libraries

 

## For creating UI

from tkinter import *

## For connecting IBM assistant from IBM Watson

import ibm_watson

## For fetching context variables

import json

## Importing data from chatbots to your local database file

import sqlite3

## For some manipulation

import pandas as pd

 

##————–CREDENTIALS THING———————-##

## Setting credentials of IBM assistant

service = ibm_watson.AssistantV2(iam_apikey=’enter_your_apikey’, version=’version_date’)

 

assistant_id = ‘enter_assistant_id’ # replace with assistant ID

 

# Create session.

session_id = service.create_session(

   assistant_id = assistant_id

).get_result()[‘session_id’]

 

##————-Initializing Tkinter Frame———————##

 

## Creating a window for tkinter

window = Tk()

window.title(“Bot”)

#window.configure(bg=’black’)

 

## Scrollbar in a window

scrollbar = Scrollbar(window)

scrollbar.pack( side = RIGHT, fill = Y )

 

## Message window for all messages to be displayed

messages = Text(window, yscrollcommand = scrollbar.set)

messages.pack()

 

## Synchronizing scrollbar with Text window

scrollbar.config(command = messages.yview)

 

## Entry box with label(message-> “Enter message”) for message from user

label = Label(text=”Enter message”)

label.pack(side=LEFT)

 

input_user = StringVar()

input_field = Entry(window, text=input_user, width=60)

input_field.pack(side=LEFT)

 

##——————–INITIALIZING WITH CONVERSATION——————-##

 

## This block so that first message from bot should come up and then following user message whole conversation goes on

 

# Initialize with empty value to start the conversation.

 

message_input = {

   ‘message_type:’: ‘text’,

   ‘text’: ”,

   ‘options’: {

           ‘return_context’: True

       }

   }

 

response = service.message(

       assistant_id,

       session_id,

       input = message_input

   ).get_result()

 

if response[‘output’][‘generic’]:

       for e in response[‘output’][‘generic’]:

           if e[‘response_type’] == ‘text’:

               messages.insert(INSERT, “BOT: %s\n” % e[‘text’])

           if e[‘response_type’] == ‘option’:

               messages.insert(INSERT, ‘BOT: %s\n’ %  e[‘title’])

               for opt in e[‘options’]:

                   messages.insert(INSERT, ‘BOT: %s\n’ % opt[‘label’])

 

##————-CHATTING IBM AND TKINTER INTEGRATED—————–##

 

## This is the event happen after pressing enter

## (the whole chatting after the first message from bot. i,e as user type some message this event will trigger)

 

def Enter_pressed(event):

 

   ## Referencing to the global variables so that updation should be done in global variable itself

   global message_input

   global response

 

   ## getting value entered in the entry box by user

   input_get = input_field.get()

   print(input_get)

 

   ## inserting that message into the text window

   messages.insert(INSERT, ‘USER: %s\n’ % input_get)

 

   ## Updating message_input for the next round of conversation

   message_type = response[‘output’][‘generic’][0][‘response_type’]

   message_input = {

       ‘message_type:’: message_type,

       ‘text’: input_get,

       ‘options’: {

           ‘return_context’: True

       }

      

   }

  

   ## Getting response from the updated message_input

   response = service.message(

       assistant_id,

       session_id,

       input = message_input

   ).get_result()

 

   ## This is just formatting the response from BOT and appending messages to Text window(messages)

   if response[‘output’][‘generic’]:

           for e in response[‘output’][‘generic’]:

               if e[‘response_type’] == ‘text’:

                   messages.insert(INSERT, ‘BOT: %s\n’ % e[‘text’])

               if e[‘response_type’] == ‘option’:

                   messages.insert(INSERT, ‘BOT: %s\n’ % e[‘title’])

                   messages.insert(INSERT, ‘BOT: Choose among these -:\n’)

                   for opt in e[‘options’]:

                       messages.insert(INSERT, ‘\t %s\n’ % opt[‘label’])

  

 

   input_user.set(”)

 

##————————–CALLING UP THE TKINTER FRAME—————-##

 

frame = Frame(window)  # , width=300, height=300)

## As the user press enter after inputting in the entry box, “Enter_pressed” function called up

input_field.bind(“<Return>”, Enter_pressed)

frame.pack()

 

window.mainloop()

 

##How to connect to database, if you have context variables present in your BOT. How to store it

## Used sqlite for database

##—————DATABASE STUFF———————##

print(json.dumps(response, indent=2))

 

## This will create a db if not exists

conn = sqlite3.connect(“Chatbot.db”)

 

c = conn.cursor()

 

# Create table – USERS

c.execute(”’CREATE TABLE USERS

            ([generated_id] INTEGER PRIMARY KEY, [A1] text, [A2] text)”’)

 

## Storing context variables in variable for storing in a dataframe first and then dump into table USERS

## Replace “name_of_variable_in_your_bot” in below code with the name of your context variable

A1 = response[‘context’][‘skills’][‘main skill’][‘user_defined’][‘name_of_variable_in_your_bot’]

A2 = response[‘context’][‘skills’][‘main skill’][‘user_defined’][‘name_of_variable_in_your_bot’]

 

## Creating a dataframe for above variables

df = pd.DataFrame(columns=[‘A1′,’A2’])

df = df.append({‘A2′:A1,’A2’:A2}, ignore_index=True)

 

## Pushing data from dataframe to USERS TABLE

df.to_sql(‘USERS’, conn, if_exists=’append’, index = False)

 

## SQL statement just to fetch all data

c.execute(”’SELECT * from USERS”’)

print(c.fetchall())

 

# We’re done, so we delete the session.

service.delete_session(

   assistant_id = assistant_id,

   session_id = session_id

)

 

In this code, first we connected with our IBM assistant using credentials. Replace your credentials of assistant in the code above.

 

Second, I have used tkinter for creating an interface. 

 

Finally connected tkinter and IBM assistant to happen a conversation flow.

 

I showed also how to create a database for storing context variables (information of particular user basically). If you wish to store you can use this functionality as well.

 

How this conversation flow happens in IBM assistant -:

There is one variable i.e., response which will helps in happening this flow.

response = service.message(

       assistant_id,

       session_id,

       input = message_input)

In this, there is message_input which is the main thing which helps in go with the flow. As it gets updated on user input. Whatever user entered will be updated in message_inout and then the response will be updated. 

Then out from response is a json format, with the help of which will basically pop up the output from bot (IBM assistant).

Hope you will be able to understand the code and logic behind it.

If you have connected the database as well then open up the application of SQLite and open the database and browse your files.

[Related Article: Logistic Regression with Python]

Conclusion

In this blog, we have seen how to deploy already build IBM assistant in Python using Tkinter as an interface. How we connected the whole conversation flow of IBM (i.e., backend part) with Tkinter(i.e., UI part).  

More on the author: Divyesh is working at a leading mobile & Java web Development Company at NEX. He has several years of experience in the field of online marketing.

Divyesh Dharaiya

Divyesh Dharaiya

Divyesh is working as leading mobile & Java web Development Company at NEX. He has several years of experience in the field of online marketing.

1