Here is a complete, functional Python program that creates a chatbot using spaCy.
This solution uses spaCy's semantic similarity features. This allows the bot to understand the meaning behind sentences, rather than just matching exact keywords. For example, it can understand that "goodbye" and "see you later" mean the same thing.
Prerequisites
You will need to install spacy and download the English language model (en_core_web_md is recommended because it includes word vectors necessary for similarity matching).
import spacy
import random
class SpacyChatBot:
def __init__(self, model_name="en_core_web_md"):
"""
Initialize the chatbot by loading the spaCy model.
We use 'md' (medium) or 'lg' (large) because they contain word vectors
required for semantic similarity. 'sm' does not.
"""
print("Loading spaCy model... (this may take a moment)")
try:
self.nlp = spacy.load(model_name)
except OSError:
raise OSError(f"Model '{model_name}' not found. Please run: python -m spacy download {model_name}")
self.intents = []
self.similarity_threshold = 0.65 # Minimum score to consider a match
def add_intent(self, tag, patterns, responses):
"""
Store intents with pre-processed spaCy docs for patterns.
"""
# Process patterns into Doc objects once to save computation during chat
processed_patterns = [self.nlp(text) for text in patterns]
self.intents.append({
"tag": tag,
"patterns": processed_patterns,
"responses": responses
})
def get_response(self, user_input):
"""
Determine the best response based on semantic similarity.
"""
input_doc = self.nlp(user_input)
b