How To Build A Chat Bot That Learns From The User In Python Tutorial
Вставка
- Опубліковано 8 лип 2024
- In this video I will be showing you how you can create a chat bot that learns from the user in Python in only 10 minutes. ChatGPT-4 generated most of this, which is pretty cool. There are some parts that can definitely be improved with the Chat Bot, but that's for you to figure out as a bonus homework problem ;)
▶ Become job-ready with Python:
www.indently.io
▶ Follow me on Instagram:
/ indentlyreels
00:00 Intro
00:24 Demo
01:30 Source code
01:57 JSON
02:41 Imports
02:56 Loading JSON
03:35 Saving JSON
04:27 Finding the best matches
06:10 Getting answers for questions
06:52 chat_bot()
10:17 Running the chat bot
11:57 Conclusion
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
Thank you very much @Indently for such a great video. My program is up, running and learning very fast.
So, essentially I can make my own tutor. Ducking awesome. I'm gonna teach Marvin so Marvin can teach me.
Excellent and versatile project!!! Thank you so much sir 💯
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.
Thanks
Clear explanation and very useful
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?
You made it very easy to learn, Thank you so much❤❤❤❤❤❤ Masterpiece
Chat Bot part 2: How to connect your bot to an ChatBot API :P
Thank you it helped us a lot❤❤
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?
Amazing tutorial to learn and enjoy to teach own chatbot 🤩🤩
ohhh cool! I didn't know about difflib.get_close_matches in default python. Thanks for the inspiration to study it! :)
love this im learning computer science and ai/ml and this is perfect
this isnt really ai, its just fetching from a json file
It worked for me, thanks
Thanks for this video.. I am able to make my first bot.
U r a life saver for me.....🔥
For me to brother
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.
Hi there , is it possible to integrate openAI with this code?
Thank you Federico
Hello! I couldn't find the repository link for the platform. Can you please provide the link?
Thank you!
Thank you very much
Superb🎉
Thank you sir
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.
Is ther a way to impliment cause-effect logic to this?
Thankyou! ❤❤😊
Can something similar be done using vanilla js?
How can we train it on large dataset?
you mentioned including a link to the code i am unable to find the link, might you say what it is? thank you ! :)
hey
Is there a way to make it on one question pick randomly from few correct answers
Which python framework is used here?
Great video
for some reason the save command isn't defined for me is there any reason why
Thanks
Hi is the source code avaliable?
Is there a way you can connect it to ChatGPT so it can do that for you?
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
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...
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
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
no link in the infobox ??
Btw can i train this ai with toons of data?
Will this work on Jupiter Notebook?
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
I can't find the github link
Can we add database to it or important Wikipedia like module to get answers for random questions??
yes
Is this how ai chat bots are made or are there more techniques?
where's the github repository link, can't find it
Can we use this code as a backend of a chatbot?
Is there a way to make this code to work with html. Like make it to work on a website
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.
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
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.
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?
where is github link for the same ?
Hi did you find it?
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!
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!
I can´t find the Github link.
hi. please help me. how to create custom model from many pdfs in Persian language? tank you.
sir where is the link for github??
BRO I DONT KNOW EITHER
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
It says that the indentation is not matching what is wrong? Using VScode
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
I dont understand what if i rearranged words in my question, or asked similar thing about other thing?
I want "conversation", not scripted dialoge...
Can you please teach how to build this in C++ 😊😊😊❤❤❤
cool i searched very long
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.
Can you make it learn from the internet though?
Source code could be useful! Thanks :)
Hi! Thank you for your content, this is really great and awesome! Writing the code, I don't get an answer from the bot unless I write 'quit' :/ any idea why it would be that way?
I typed it all out from the video, there was a typo in line 16 where he wrote "questions" instead of "question". you might check that.
Error: _name_ not defined
How I can fix it..?
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
can anyone please tell me where the github link is i cant find it anywhere
Co ask
I cannot find the link to Git repository you referred to. Really useful for me as I'm dyslexic and recently started learning programming...... Mainly trial and error, 2 pc one playing your videos, the other playing with the code in anaconda playing "what if", slow going, but getting on surprisingly well LOL
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?
What libraries did he use? ChatterBot? NLTK?
If you watch any % of the video you will find out
thx,but I don't know why that the data base fail
It's really good one ❤ but can you please tell why we didn't use openai module to make this ? Lots of love from India ❤
To save money
@@Indently 😫👏
@@Indentlyfair enough
@@Indently😂yep I think we should try to build our own chatbot not like using api or library.this way we can make better projects than openai ❤
@@Indently 😂 true fact
how did you type out the not equal sign?
It's != on IDE's that aren't PyCharm
There is no github link in the description
None at all
Yeah true i needed it asap
can i have the code?
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
I get an error saying, no such file or directory. Pls help
me too
≠ how do I get that?
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
It's not work on 3.11 don't know why
is it possible to implement this into a discord bot?
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)
How to give it sources to automatically learn about this world?
next step is to install tensorflow and actually make it a real machine learning model
There's no github code in the description I badly needed please :(
Can someone send the github link of the whole code
is this on github??? I think I made a mistake but the video was a little hard to follow.
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
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
github link?
Didn't work for me
Hi! Can you please provide the code for this chatbot!