I am glad that I found this tutorial. I am a 2nd semester student in computer science where I am learning python. While I was searching for something new that I can learn in advance of my class, I found this masterpiece that opened my mind and the way of thinking. I really appreciate your effort and I am gonna suggest my friends to follow this.
So for my bonus homework problem, I changed it to asynchronous to work with a discord bot. I added the ability to have multiple answers in a list and to pick a random answer. I also added an add command that will prompt the user to add a question and answer manually. If the answer is not found, it will create a new entry in the knowledge base. If the answer is found, it will change the string answer to a list and add it, or add to a list if there is one. Thank you so much for this! I just started learning programming a few months ago and the way you explained it helped me out a lot.
ive had a hard time getting the import random to work as you wouold want for multiple responses on the answers. but ive only been working on this for 1 hour. probably will get it solved soon
import json from difflib import get_close_matches import os # create database folder if it doesn't exist if not os.path.exists("database"): os.makedirs("database") def loadKnowledgeBase(filepath: str) -> dict: # Load the knowledge base from a file with open(filepath, 'r') as file: data: dict = json.load(file) return data def saveKnowledgeBase(filepath: str, data: dict) -> None: # Save the knowledge base to a file with open(filepath, 'w') as file: json.dump(data, file, indent=2) def findBestMatch(userQuestion: str, questions: list[str]) -> str | None: # Find the best match for the user question bestMatch: list = get_close_matches(userQuestion, questions, n=1, cutoff=0.6) return bestMatch[0] if bestMatch else None def getAnswerForQuestion(question: str, knowledgeBase: dict) -> str | None: # Get the answer for the question for q in knowledgeBase["questions"]: if q["question"] == question: return q["answer"] def chat(): # Chat with the bot knowledgeBase: dict = loadKnowledgeBase("database\\knowledge_base_0.json") while True: userInput = input("You: ") if userInput == "exit": break
bestMatch: str | None = findBestMatch(userInput, [q["question"] for q in knowledgeBase["questions"]])
else: print("Bot: I'm sorry, I don't know the answer to that question, can you provide me with the answer?") userAnswer: str = input("You: ") knowledgeBase["questions"].append({"question": userInput, "answer": userAnswer}) saveKnowledgeBase("database\\knowledge_base_0.json", knowledgeBase) print("Bot: Thank you for the information, I will remember it for next time.") if __name__ == "__main__": chat()
Couldnt find my mistakes, nor a github code lol. So, I went to chatgpt and asked if it could help and it caught a spelling error and I forgot a 'f' statement. Otherwise this was a great code and you were very kind to share it, ty.
.json file: { "questions":[ ] } .py file: import json from difflib import get_close_matches def load_knowledge_base(file_path:str) -> dict: with open(file_path,'r') as file: data:dict=json.load(file) return data def save_knowledge_base(file_path:str,data:dict): with open(file_path,'w') as file: json.dump(data,file,indent=2) def find_best_match(user_question:str,questions:list[str]) -> str|None: matches:list=get_close_matches(user_question,questions,n=1,cutoff=0.6) return matches[0] if matches else None def get_answer_for_question(question:str,knowledge_base:dict) -> str|None: for q in knowledge_base["questions"]: if q["question"]==question: return q["answer"]
def chatbot(): knowledge_base:dict=load_knowledge_base('knowledge_base.json') while True: user_input:str=input('You: ') if user_input.lower()=='quit': break best_match:str|None=find_best_match(user_input,[q['question'] for q in knowledge_base['questions']]) if best_match: answer:str=get_answer_for_question(best_match,knowledge_base) print(f"Bot: {answer}") else: print("Bot: I don't know the answer.can you teach me?") new_answer:str=input("Type the answer or 'skip' to skip: ") if new_answer.lower()!='skip': knowledge_base["questions"].append({"question":user_input,"answer":new_answer}) save_knowledge_base('knowledge_base.json',knowledge_base) print("Bot: Thankyou! I learnt a new response!") if __name__=="__main__": chatbot()
I'm sorry to say this, but this is a sorry excuse for a chat bot, this is no better than writing code to tell it what to say, it never learns. And always returns your answer, there's nothinh to do with this except teach and even then it's a boring experience at that
@nandhaxd Yes i understand that, you understood how to take input, use indexs or lists, dictionary perhaps. But you certainly did not learn how to make a chat bot, not one that is actually chattable anyways you made a dictionary
Really good job man, i implemented this on my ai application, which is now self-training. Thanks for such a beautiful demonstration. really appreciate that
knowledge_base: dict = load_knowledge_base("knowledge_base.json") just tells the programm that it should load the database from the directory the main file is in, but you can replace "knowledge_base.json" with any filepath you want
The json file is created in the same folder as the main app. when we create any file in the same folder or directory, you dont have to give the path, it will automatically read it.
hey there, can I get your code source pls, just simply because I can't find it in the description. However, can I use other languages to train this AI?
Hey, thank you for the informative video! I cannot find the link to the github so I wrote the code as you had shown. However, when I am running it, the terminal says no such file in directory (with regards to the knowledge_base.json) - "File Not Found". Is there something I am missing, as I had done everything exactly as you had shown. I was wondering if it could be the second last line wherein you state if name__ == main... as I do not have a function for that in my VS, so I just typed it from scratch. But it does not select and run the main like yours does, is there an extention I need to download to set the name == main function in VS, thank you!
Yeah because in the terminal you can’t run the file inside of the folder if you want to fix that you need to use the absolute path instead of knowledge_base.json
Hello! I'm wondering how you did this symbol → valid because when i try to copy paste it i'm present with an error. I'm using PyCharm as my IDE and this symbol get's in the way because it throws an error. Very very nice guide though, will be perfect for my learning project. Would appreciate if i can get some clarity regarding this. Thank you in advance!
Nice tutorial, but I'm getting an error. In the function "Find Best Match", I typed "user_question: str, questions: list[str]", but an error is generated saying "Subscript for class "list" will generate runtime exception; enclose type annotation in quotes". I'm currently on Python 3.8.9 64-bit. I am new to this, so maybe I am missing something?
My code has no errors, except I only get "Process finished with exit code 0" after running it. If possible, can you please assist on how to fix this. Thank you!
Wouldnt this glitch kinda bcs ;lets say I wrote "Whats the capital of Italy" and in another chat I wrote "Whats a dish from Italy" wouldnt it say a dish name?
Did you do the with open in a function? If so, you have to pass the name as a parameter (assuming you used a variable name instead of the file name directly in the with open)
Any Idea why when I copy the code and run it in idle3 I get a syntax error on line 14? data: dict = json.load(file) it doesn't like the colon. I don't have much idea what I'm doing, I'm not much of a coder.
probably doesnt work on an older version of python, try updating python or just remove the colon and dict. specifying a variable's type is nice but not required for it to work
I am glad that I found this tutorial. I am a 2nd semester student in computer science where I am learning python. While I was searching for something new that I can learn in advance of my class, I found this masterpiece that opened my mind and the way of thinking. I really appreciate your effort and I am gonna suggest my friends to follow this.
From what university? same here am a second semester CS student
So for my bonus homework problem, I changed it to asynchronous to work with a discord bot. I added the ability to have multiple answers in a list and to pick a random answer. I also added an add command that will prompt the user to add a question and answer manually. If the answer is not found, it will create a new entry in the knowledge base. If the answer is found, it will change the string answer to a list and add it, or add to a list if there is one. Thank you so much for this! I just started learning programming a few months ago and the way you explained it helped me out a lot.
can you show us how?
ive had a hard time getting the import random to work as you wouold want for multiple responses on the answers. but ive only been working on this for 1 hour. probably will get it solved soon
@@carsonhighfill364 Have you figured it out?
type: - and then the > : -> rest is his prettier format
Please give us the link for GitHub repository for this code example. You miss this.
import json
from difflib import get_close_matches
import os
# create database folder if it doesn't exist
if not os.path.exists("database"):
os.makedirs("database")
def loadKnowledgeBase(filepath: str) -> dict: # Load the knowledge base from a file
with open(filepath, 'r') as file:
data: dict = json.load(file)
return data
def saveKnowledgeBase(filepath: str, data: dict) -> None: # Save the knowledge base to a file
with open(filepath, 'w') as file:
json.dump(data, file, indent=2)
def findBestMatch(userQuestion: str, questions: list[str]) -> str | None: # Find the best match for the user question
bestMatch: list = get_close_matches(userQuestion, questions, n=1, cutoff=0.6)
return bestMatch[0] if bestMatch else None
def getAnswerForQuestion(question: str, knowledgeBase: dict) -> str | None: # Get the answer for the question
for q in knowledgeBase["questions"]:
if q["question"] == question:
return q["answer"]
def chat(): # Chat with the bot
knowledgeBase: dict = loadKnowledgeBase("database\\knowledge_base_0.json")
while True:
userInput = input("You: ")
if userInput == "exit":
break
bestMatch: str | None = findBestMatch(userInput, [q["question"] for q in knowledgeBase["questions"]])
if bestMatch:
answer: str | None = getAnswerForQuestion(bestMatch, knowledgeBase)
print(f"Bot: {answer}")
else:
print("Bot: I'm sorry, I don't know the answer to that question, can you provide me with the answer?")
userAnswer: str = input("You: ")
knowledgeBase["questions"].append({"question": userInput, "answer": userAnswer})
saveKnowledgeBase("database\\knowledge_base_0.json", knowledgeBase)
print("Bot: Thank you for the information, I will remember it for next time.")
if __name__ == "__main__":
chat()
Hiya! I wanted to play around, did you find it?
I created a repo for this, but my comment never posted.
Thank you very much @Indently for such a great video. My program is up, running and learning very fast.
Couldnt find my mistakes, nor a github code lol. So, I went to chatgpt and asked if it could help and it caught a spelling error and I forgot a 'f' statement. Otherwise this was a great code and you were very kind to share it, ty.
Thanks a lot mate this tutorial gave me a wonderful insight on how Artificial Intelligence and chat bots are structured, Cheers!
there's no github link???
Nah but if you wanna put in the effort you can pause here and there and copy down what he did. That's what I did
Same
Yeah where's the link
I don't want copy I just 2an understand it by seeing live code
@@battleaxe990fedric said there's a repo in description but there's no repo
.json file:
{
"questions":[
]
}
.py file:
import json
from difflib import get_close_matches
def load_knowledge_base(file_path:str) -> dict:
with open(file_path,'r') as file:
data:dict=json.load(file)
return data
def save_knowledge_base(file_path:str,data:dict):
with open(file_path,'w') as file:
json.dump(data,file,indent=2)
def find_best_match(user_question:str,questions:list[str]) -> str|None:
matches:list=get_close_matches(user_question,questions,n=1,cutoff=0.6)
return matches[0] if matches else None
def get_answer_for_question(question:str,knowledge_base:dict) -> str|None:
for q in knowledge_base["questions"]:
if q["question"]==question:
return q["answer"]
def chatbot():
knowledge_base:dict=load_knowledge_base('knowledge_base.json')
while True:
user_input:str=input('You: ')
if user_input.lower()=='quit':
break
best_match:str|None=find_best_match(user_input,[q['question'] for q in knowledge_base['questions']])
if best_match:
answer:str=get_answer_for_question(best_match,knowledge_base)
print(f"Bot: {answer}")
else:
print("Bot: I don't know the answer.can you teach me?")
new_answer:str=input("Type the answer or 'skip' to skip: ")
if new_answer.lower()!='skip':
knowledge_base["questions"].append({"question":user_input,"answer":new_answer})
save_knowledge_base('knowledge_base.json',knowledge_base)
print("Bot: Thankyou! I learnt a new response!")
if __name__=="__main__":
chatbot()
thank you, this one works!!!!
Thanks a lot
So, essentially I can make my own tutor. Ducking awesome. I'm gonna teach Marvin so Marvin can teach me.
😂
I like this! Now I can start training some custom chatbots :D
Tell about your progress, have you moved to conversational pipelines or was able to pull out of here something?
Hello! I couldn't find the repository link for the platform. Can you please provide the link?
Thank you!
Thanks
Clear explanation and very useful
ohhh cool! I didn't know about difflib.get_close_matches in default python. Thanks for the inspiration to study it! :)
I'm sorry to say this, but this is a sorry excuse for a chat bot, this is no better than writing code to tell it what to say, it never learns. And always returns your answer, there's nothinh to do with this except teach and even then it's a boring experience at that
Thank you for sharing your view
@Indently You are very welcome
No I just learned something new
@nandhaxd Yes i understand that, you understood how to take input, use indexs or lists, dictionary perhaps. But you certainly did not learn how to make a chat bot, not one that is actually chattable anyways you made a dictionary
Really good job man, i implemented this on my ai application, which is now self-training. Thanks for such a beautiful demonstration. really appreciate that
how did you start building your model/ what do you recommend i start with?
@@chy2114 you can start with mistral
Unless I missed something, I never saw you define file_path. How would your script know where to find the json file without defining it first?
I messed around with different file paths and had zero success. But im very new so who knows.
knowledge_base: dict = load_knowledge_base("knowledge_base.json") just tells the programm that it should load the database from the directory the main file is in, but you can replace "knowledge_base.json" with any filepath you want
The json file is created in the same folder as the main app. when we create any file in the same folder or directory, you dont have to give the path, it will automatically read it.
where is github link for the same ?
Hi did you find it?
Hi there , is it possible to integrate openAI with this code?
Amazing tutorial to learn and enjoy to teach own chatbot 🤩🤩
you mentioned including a link to the code i am unable to find the link, might you say what it is? thank you ! :)
hey
hey there, can I get your code source pls, just simply because I can't find it in the description. However, can I use other languages to train this AI?
Yes but if it doesn’t know the language it will still say it in English
love this im learning computer science and ai/ml and this is perfect
this isnt really ai, its just fetching from a json file
Excellent and versatile project!!! Thank you so much sir 💯
You made it very easy to learn, Thank you so much❤❤❤❤❤❤ Masterpiece
How can we train it on large dataset?
Chat Bot part 2: How to connect your bot to an ChatBot API :P
Thanks for this video.. I am able to make my first bot.
U r a life saver for me.....🔥
For me to brother
There is no github link in the description
None at all
Yeah true i needed it asap
Is this how ai chat bots are made or are there more techniques?
Hey, thank you for the informative video! I cannot find the link to the github so I wrote the code as you had shown. However, when I am running it, the terminal says no such file in directory (with regards to the knowledge_base.json) - "File Not Found". Is there something I am missing, as I had done everything exactly as you had shown.
I was wondering if it could be the second last line wherein you state if name__ == main... as I do not have a function for that in my VS, so I just typed it from scratch. But it does not select and run the main like yours does, is there an extention I need to download to set the name == main function in VS, thank you!
Yeah because in the terminal you can’t run the file inside of the folder if you want to fix that you need to use the absolute path instead of knowledge_base.json
sir where is the link for github??
BRO I DONT KNOW EITHER
I can't find the github link
no link in the infobox ??
What libraries did he use? ChatterBot? NLTK?
If you watch any % of the video you will find out
Hi is the source code avaliable?
Thank you it helped us a lot❤❤
Can you please create a video about how to use gui and convert the terminal script into an actual app?
Yes please 🥺
Learn the kivy framework. You'll be able to make an actual Android app & build a GUI for it
you make the back end like this to run form python. 3.11. then you make a gui using PySimpleGUI.. boom
Script kiddy
Thanks so much, this video really helped a lot for my project. Out of curiosity, what text-editor are you using?
My bad, I found it
Pycharm
Can we add database to it or important Wikipedia like module to get answers for random questions??
yes
Great video
Is ther a way to impliment cause-effect logic to this?
Is there a way to make it on one question pick randomly from few correct answers
can anyone please tell me where the github link is i cant find it anywhere
Co ask
Hi, may I know how you type =/= non-equal sign in Visual/python or it is a package i have to download in Visual Studio?
! = that should work...
I dont understand what if i rearranged words in my question, or asked similar thing about other thing?
I want "conversation", not scripted dialoge...
Hello! I'm wondering how you did this symbol → valid because when i try to copy paste it i'm present with an error. I'm using PyCharm as my IDE and this symbol get's in the way because it throws an error. Very very nice guide though, will be perfect for my learning project. Would appreciate if i can get some clarity regarding this. Thank you in advance!
i belive its not the symble but lilke -->
It doesn’t work for python 3.9 or less
@@the_phoenix78 in spyder i just write -> it worked.
It is the symbol "->".
Hi, it's "->" symbol which is indicating a return type of the defined function.
Superb🎉
It says that the indentation is not matching what is wrong? Using VScode
How to give it sources to automatically learn about this world?
Thankyou! ❤❤😊
Is there a way to make this code to work with html. Like make it to work on a website
for some reason the save command isn't defined for me is there any reason why
I'm trying this in visual studio on python 3.12 and getting some errors on the "import long_responses". Just thought I'd mention this.
where's the github repository link, can't find it
i got a problem in load json file what to do?
I can´t find the Github link.
in vs code it doesnt skip a tab and also doesnt show the pre suggested code that you type anyway. did i miss something or is that normal?
its normal i use vs code i consider pycharm for the weak of mind
Which python framework is used here?
Can we use this code as a backend of a chatbot?
Nice tutorial, but I'm getting an error. In the function "Find Best Match", I typed "user_question: str, questions: list[str]", but an error is generated saying "Subscript for class "list" will generate runtime exception; enclose type annotation in quotes". I'm currently on Python 3.8.9 64-bit. I am new to this, so maybe I am missing something?
Is it possible to manage that the bot searches with beautifulscrape after Answers in the web and learns like that?
or make the bot selflearning???
you mean for all questions including greetings or just for general info questions?
@@glassesgaming5831 for all
hi. please help me. how to create custom model from many pdfs in Persian language? tank you.
Can something similar be done using vanilla js?
I get an error saying, no such file or directory. Pls help
me too
Btw can i train this ai with toons of data?
My code has no errors, except I only get "Process finished with exit code 0" after running it. If possible, can you please assist on how to fix this. Thank you!
Code is working awesome❤ I have run it
can you provide me with it's github link? or can you just share the written code with me.
would be a great help
Can it use other languages?
Wouldnt this glitch kinda bcs ;lets say I wrote "Whats the capital of Italy" and in another chat I wrote "Whats a dish from Italy" wouldnt it say a dish name?
i am a 9 yr old and this help me a lot
Is there a way you can connect it to ChatGPT so it can do that for you?
It is not working
Didn't work for me
Thank you so much for making this video! I have learned so much and I am having so much fun with it!
im still confused
Will this work on Jupiter Notebook?
It is showing error in line 5(with open ) how can we reslove it
Did you do the with open in a function? If so, you have to pass the name as a parameter (assuming you used a variable name instead of the file name directly in the with open)
OK I got to learn this project
Thank you Federico
how did you type out the not equal sign?
It's != on IDE's that aren't PyCharm
It says 'r' is not a designated file location?
You have to specify the file location first, then put a comma, then put 'r' or something else depending on what you want to with the file
Wait where did you get the chat_bot() ???? In not see anything that you create a class
The chatbot is the code he typed - if you type everything he did in the video, you will have made the chatbot
Error: _name_ not defined
How I can fix it..?
Any Idea why when I copy the code and run it in idle3 I get a syntax error on line 14?
data: dict = json.load(file) it doesn't like the colon.
I don't have much idea what I'm doing, I'm not much of a coder.
probably doesnt work on an older version of python, try updating python or just remove the colon and dict. specifying a variable's type is nice but not required for it to work
You typed it correct maybe you indented it wrong. python is picky about indents. try giveing it a tab or 4 spaces. from the line above
I think you have to write file name
is this on github??? I think I made a mistake but the video was a little hard to follow.
It's not work on 3.11 don't know why
github link?
where is the link for github repos
Thank you sir
≠ how do I get that?
Thank you very much
im new to coding and i was wondering if this can be used with a discord bot.
yes, but you'd have to make it asynchronous
Thank you, One quick question. What happens when someone feed knowledge hub with the wrong information..
It would output the wrong answer if the question is asked. There is nothing to understand the information given is wrong.
wo is the link?
Can you do a video on how we can extract all text from a word document
you can just do that by using the in-build open feature in python
dude you would do a file open and read to import it as a sring then do a .slice() to index the words [ ] and boom
is it possible to implement this into a discord bot?
cool i searched very long
can i have the code?
There's no github code in the description I badly needed please :(
where is the source code plz?
same question.... where is the link to the github? thanks