Framing the Chatbot
I'm now zeroing in on the core functionality. My focus is on understanding the fundamental goal: a Python script for a simple, learning-enabled chatbot. Analyzing these requirements is the next critical step. I'm taking note of the specified language and the overarching need for machine learning integration.
Pinpointing the Implementation
Now I'm evaluating the technical route. The task is now about weighing different approaches. Hard-coding rules falls short, deep learning is over-engineered. The ChatterBot library seems most fitting. TF-IDF with Scikit-learn is also an option, but needs extra work to learn dynamically.
Choosing the Best Path
I'm now shifting to a simpler solution, dropping ChatterBot to improve stability. Using Scikit-learn will allow me to show the core ML concepts. I'm building a dictionary-based system from scratch for easy learning. The focus is now on making the system interactive, by saving unknown responses.
Revising the Implementation
Now, I'm pivoting to a from-scratch strategy, as the previous solutions proved to have too many dependencies or possible instability. I'll focus on a JSON file for the knowledge base, coupled with difflib.get_close_matches for matching user input. My next step involves defining the data structure and the core logic flow to ensure that the chatbot interacts and learns from new responses. I aim to create a minimal, yet functional, solution for an improved approach.
Formulating the Core Logic
I'm now consolidating the design and starting to flesh out the main components of the Python script. I will be making a bot that matches input to a dataset. I'll implement a JSON file for the knowledge base. Then, I'll use difflib.get_close_matches for matching input. I'm focusing on creating functions for loading, saving, and the core matching logic to allow the bot to respond effectively and learn from each interaction.
Analyzing the Design
I'm now fully focused on the technical design phase. Given the requirements, I've opted for a JSON-based knowledge store coupled with difflib for matching input. The plan is to create a core loop that gets user input, finds a match, and responds. The ability for the bot to learn from unknown inputs will be the central focus, ensuring that unknown queries will be saved.
Simplifying the Implementation
Now I'm narrowing the implementation. The current plan is a JSON-based knowledge store paired with difflib.get_close_matches for matching user inputs. I will focus on the ability of the bot to "learn" by adding new data to the knowledge base. It avoids complex machine learning libraries, keeping the code simple and easy to understand. I will prepare the code in Python with descriptive comments.
Here is a complete, working Python script for a simple chatbot that "learns" from you.
This bot uses heuristic matching (a basic form of Machine Learning logic similar to "Nearest Neighbor"). It compares your input to a database of known questions. If it doesn't recognize what you said, it asks you to teach it the correct response, saves it to a JSON file, and remembers it for next time.
The Python Code
Create a file named chatbot.py and paste this code:
import json
from difflib import get_close_matches
# File path where the "brain" is stored
KNOWLEDGE_BASE_FILE = 'knowledge_base.json'
def load_knowledge_base(file_path: str) -> dict:
"""
Loads the knowledge base from a JSON file.
If the file doesn't exist, returns a default empty structure.
"""
try:
with open(file_path, 'r') as file:
data = json.load(file)
return data
except (FileNotFoundError, json.JSONDecodeError):
return {"questions": []}
def save_knowledge_base(file_path: str, data: dict):
"""
Saves the current knowledge base dictionary to the JSON file.
"""
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:
"""
Uses basic pattern matching to find the most similar question
in the database to what the user asked.
"""
matches = 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:
"""
Retrieves the answer associated with the specific question.
"""
for q in knowledge_base["questions"]:
if q["question"] == question:
return q["answer"]
return None
def chat_bot():
knowledge_base = load_knowledge_base(KNOWLEDGE_BASE_FILE)
print("Bot: Hello! I am a bot that learns. Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
# Extract all known questions to compare against
question_list = [q["question"] for q in knowledge_base["questions"]]
# Find the closest match
best_match = find_best_match(user_input, question_list)
if best_match:
# If a match is found, return the answer
answer = get_answer_for_question(best_match, knowledge_base)
print(f"Bot: {answer}")
else:
# If no match is found, ask the user to teach the bot
print("Bot: I don't know the answer to that. Can you teach me?")
new_answer = 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_FILE, knowledge_base)
print("Bot: Thank you! I've learned a new response!")
if __name__ == '__main__':
chat_bot()
How to run it
- Make sure you have Python installed.
- Save the code above into a file named
chatbot.py.
- Open your terminal or command prompt.
- Run the script:
python chatbot.py
How to use it (Example Conversation)
Because the database starts empty, the interaction will look like this at first:
Bot: Hello! I am a bot that learns. Type 'quit' to exit.
You: Hello!
Bot: I don't know the answer to that. Can you teach me?
Type the answer: Hi there! How can I help you?
Bot: Thank you! I've learned a new response!
Now, run the script again (or continue chatting):
You: Hello!
Bot: Hi there! How can I help you?
How it works (The Logic)
json Storage: The bot creates a file called knowledge_base.json. This acts as its brain. It stores data as pairs of questions and answers.
difflib.get_close_matches: This is the "Artificial Intelligence" part. It doesn't look for exact matches.
- If you teach the bot "Hello", and later you type "hallo" (a typo), the
cutoff=0.6 parameter allows the bot to recognize that "hallo" is 60% similar to "Hello" and still give the correct answer.
- The Feedback Loop: When the matching algorithm fails (returns
None), the bot switches to "Training Mode" and asks the user for the label (the answer) to the input data. This is known as Supervised Learning.