'Is it possible to format my json file for a Yes or No chat flow for my chatbot
I'm currently trying to create a chatbot as an IT support for FAQs on IT Department.
Since every computer problems have more than 1 solution, is there anyway I could format my json file in such a way that the conversation could flow like this:
Chatbot : Hello, what can I do for you?
User: My Wi-Fi keeps disconnecting
Chatbot: Solution 1: Click on the Network & Internet icon in the system....(Please type Y if this solved your problem, and Type N if No)
User: No
Chatbot; Soution 2: DISABLE WIFI SENSE. Click on the Windows icon in your taskbar...(Please type Y if this solved your problem, and Type N if No)
User: Yes
Chatbot: Glad I could help.
here's my sample code below #Python
import random,json,pickle,numpy as np,nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import load_model
# import tech_supp._sample_chatbot.nlp.training
__my_file_path = 'tech_supp/python/chatbot/nlp/'
lemmatizer = WordNetLemmatizer()
intents = json.loads(open(f'{__my_file_path}intents.json').read())
words = pickle.load(open(f'{__my_file_path}words.pkl', 'rb'))
classes = pickle.load(open(f'{__my_file_path}classes.pkl', 'rb'))
model = load_model(f'{__my_file_path}chatbotmodel.h5')
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
return sentence_words
def bag_of_words(sentence):
sentent_words = clean_up_sentence(sentence)
bag = [0] * len(words)
for w in sentent_words:
for i,word in enumerate(words):
if word == w:
bag[i]=1
return np.array(bag)
def predict_class(sentence):
bow = bag_of_words(sentence)
res = model.predict(np.array([bow]))[0]
ERROR_THRESHOLD = 0.80
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
results.sort(key=lambda x:x[1],reverse= True)
return_list = []
for r in results:
probability = round(r[1] * 100,ndigits=2)
probability = str(probability)+'%'
return_list.append({'intent':classes[r[0]],'probability':probability})
return return_list
def get_response(message):
intents_list = predict_class(message)
# for each_intent_list in intents_list:
# print(each_intent_list)
if len(intents_list)>0:
tag = intents_list[0]['intent']
accuracy = intents_list[0]['probability']
else:
#fallback message
return "I'm sorry I don't understand you."
list_of_intents = intents['intents']
for i in list_of_intents:
if i['tag'] == tag:
# return f'Accuracy: "{accuracy}" {random.choice(i["responses"])}'
return random.choice(i["responses"])
print('Go! Bot is running!')
#Javascript
function open_chatbot(){
document.getElementById("chatbot").innerHTML =
`<div>
<button class="btn btn-outline-info" onclick="minimize_chatbot()">Minimize</button>
<label>Was this chatbot helpful?</label>
<button class="right-msg btn btn-outline-info" onclick="save_chat_session('yes')">Yes</button>
<button class="right-msg btn btn-outline-info " onclick="save_chat_session('no')">No</button>
<div class="msger-chat"></div>
<form class="msger-inputarea">
<input type="text" class="msger-input" id="textInput" placeholder="Enter your query...">
<button type="submit" class="msger-send-btn">Send</button>
</form>
</div>`;
const msgerForm = get(".msger-inputarea");
const msgerInput = get(".msger-input");
const msgerChat = get(".msger-chat");
//Icons made by Freepik from www.flaticon.com
const BOT_NAME = "Jayvee";
const PERSON_NAME = "You";
msgerForm.addEventListener("submit", event =>
{
event.preventDefault();
const msgText = msgerInput.value;
if (!msgText) return;
appendMessage(PERSON_NAME, "right", msgText);
msgerInput.value = "";
botResponse(msgText);
});
function appendMessage(name, side, text)
{
//Simple solution for small apps
const msgHTML =
`
<div class="msg ${side}-msg">
<div class="msg-img"></div>
<div class="msg-bubble">
<div class="msg-info">
<div name="message-name" class="msg-info-name">${name}</div>
<div name="message-datetime" class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div name="message-text" class="msg-text">${text}</div>
</div>
</div>
`;
msgerChat.insertAdjacentHTML("beforeend", msgHTML);
msgerChat.scrollTop += 500;
}
function botResponse(rawText) {
// Bot Response
$.get("/chat", { msg: rawText }).done(function (data)
{
const msgText = data;
appendMessage(BOT_NAME, "left", msgText);
});
}
// Utils
function get(selector, root = document)
{
return root.querySelector(selector);
}
//chabot introduction
appendMessage(BOT_NAME, "left", "Hello! I\'m Jayvee your computer technical-support Chatbot.");
}
function minimize_chatbot(){
document.getElementById("chatbot").innerHTML =
'<button class="btn btn-outline-info" onclick="open_chatbot()">Chatbot</button>';
}
function formatDate(date){
var hour = date.getHours();
var minute = date.getMinutes();
if(hour==0)
hour=12;
var ampm = "AM";
if( hour > 12 ) {
hour -= 12;
ampm = "PM";
}
hour = "0" + hour;
minute = "0" + minute;
return `${hour.slice(-2)}:${minute.slice(-2)} ${ampm}`;
}
function save_chat_session(result){
/*
* result
* name
* datetime
* message
*/
let name= document.getElementsByName("message-name");
let datetime= document.getElementsByName("message-datetime");
let message= document.getElementsByName("message-text");
let conversation=[];
for (let i = 0; i < name.length; i++) {
let obj = {
"name":name[i].innerHTML,
"datetime":datetime[i].innerHTML,
"message":message[i].innerHTML
}
conversation.push(obj);
}
fetch('/admin/chatbot/save_session',{
headers: {'Content-Type': 'application/json' },
method: 'POST',
body: JSON.stringify(
{
"result": result,
"conversation":conversation
}
)
})
.then(function (response) {return response.text();})
.then(function (text) {console.log('POST response: '+text);});
minimize_chatbot();
}
minimize_chatbot();
#Excerpt from my JSON FILE
{
"intents": [
{
"tag": "greetings",
"patterns": [
"hello",
"hey",
"hi",
"good day",
"Greetings",
"what's up?",
"how is it going?"
],
"responses": [
"Hello, Welcome to Our IT Chatbot",
"Good to see you, Welcome to our IT Chatbot",
"Hi there, how can I help?"
]
},
{
"tag": "Cannot access email",
"patterns": [
"can't access email",
"email inaccessible",
"cannot acess email"
],
"responses": [
"1.Restart the e-mail application. Log in with your credentials <br> 2.Try accessing your e-mail through the web. If you can access it, the problem lies in the application\u00e2\u20ac\u2122s software.<br> 3.Check the service status for any general e-mail issues.<br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for greater assistance!"
]
},
{
"tag": "Slow downloading and uploading speeds",
"patterns": [
"slow download speed, download slow",
"slow download",
"internet download slow",
"slow internet"
],
"responses": [
"Try running a speed test online. Ideally, you should get half of the speed that your service provider is claiming to offer.<br>If the tests are positive, double-check the background for any hidden files that are downloading or uploading <br> Also, check whether the network card needs updating or not. <br> 2.If slow speed still occurs, try resetting the modem to solve the network problems.<br> If the issue is not resolved, call your service provider to check if they are having problems from their end. <br> If you're connecting wirelessly, then the location may be the problem. The signal is not necessarily strong in all corners of the building. Similarly, you could just be too far away. If this is not the issue, then spyware or viruses are a likely cause. <br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for in-depth assistance!"
]
},
{
"tag": "Windows takes a long time to start",
"patterns": [
"windows starts slow",
"pc starts slow",
"turning on pc loads slow",
"slow startup"
],
"responses": [
"1.Disable Fast Startup-open Settings and browse to System then click Power & sleep. <br> On the right side of this screen, click Additional power settings to open the Power Options menu in the Control Panel and untick Turn on fast startup click Save.<br> <br> 2.Adjust Paging File Settings- Click Start Menu, choose the Adjust the appearance and performance of Windows. Under the Advanced tab, click Change. Uncheck Automatically manage paging file size for all drives then choose Custom Size and set the Initial Size and Maximum Size then Restart your computer.<br> <br> 3.Update Graphics Drivers- Open the Device Manager by right-clicking on the Start button (or hitting Win + X) and choose Device Manager. Go to Display adapters to see which graphics card you're using (others are Nvidia or AMD).Install any new version <br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for greater assistance! "
]
},
{
"tag": "How to fix lag on a PC",
"patterns": [
"How to fix lag on a PC",
"lag pc",
"solutions for lag pc"
],
"responses": [
"Solution 1: Run Disk Defragmenter.<br> Step 1: Press the Windows button. Click *All Programs* and open *Accessories*.<br> Step 2: Right-click *Command Prompt*. Choose *Run as Administrator*.<br> Step 3: Type *defrag X: -v* in the prompt, X representing the letter of your hard disk. For instance, if you want to defrag drive E type *defrag E: -v* in the prompt. Press *Enter*.<br> Step 4: Wait for the defragmentation to complete. Reboot your system once it is complete.<br><br> Solution 2: Run Disk Cleanup<br> Step 1: Press the Windows button. Type *Disk Cleanup* in the *Start Search* field. Press *Enter*.<br>Step 2: Click *My Files Only* when the Disk Cleanup Options prompt appears.<br> Step 3: Choose the drive and click *OK*. Allow the tool to scan for possible space to free up.<br>Step 4: Place a check by the files you want to delete. Click *OK*.<br> Step 5: Click *Delete Files* when the *Are You Sure You Want To Permanently Delete These Files?* prompt launches.<br> <br> Solution 3: Scan for Harmful Software<br>Step 1: Press the Windows button. Click *All Programs* and open *Windows Defender*.<br>Step 2: Click the *Scan* option toward the top of the window.<br> Step 3: Choose the repair option once the scan is complete. Reboot your system once the repair is complete.<br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for in-depth assistance!"
]
}
]
}
Thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
