Creating a chatbot program
The user wants a Python program that simulates a chat bot using spaCy for natural language processing. I think they’re looking for a simple, rule-based chatbot example, so I should include code for installation, loading models, handling intents, and named entity recognition. A console chat is likely preferred, without being overly verbose.
I’ll prepare a self-contained script, and I'll specify which spaCy model to download, probably en_core_web_sm. This should help illustrate everything clearly!Designing the chatbot structure
I need to be mindful of the environment, but that's manageable. For the chatbot, I’ll start with necessary imports like spaCy, and load the 'en_core_web_sm' model. I'll define a function to classify intent, and another for responses, along with the main chat loop.
I’ll create an intents dictionary that maps intent names to examples and responses. The intent detection process will analyze user input by calculating similarity and applying a threshold, and I’ll include entity extraction for time and date references. A simple fallback response will round things out!Implementing entity detection
To showcase how to use entities, I’ll demonstrate detecting a "PERSON" entity when a user says something like "My name is Alice." I'll store the user's name in a global variable called user_profile.
While analyzing the input, I’ll check for PERSON entities and phrases like "my name is." This will show spaCy's capabilities beyond simple string matching, including tokenization, lemmatization, and entity recognition.
I’ll be writing code that loads the spaCy model, defines intents, and preprocesses example documents accordingly.Defining the intent function and chat loop
I’ll define a function called get_intent(user_text) where I first process the user's input using spaCy. For each intent, I’ll compute similarity with stored examples, tracking the best match. I might need to manage empty text cases here.
Next, I'll create a handle_entities(doc) function to update user memory when they introduce themselves. In generate_response(intent, doc), I'll customize responses based on both intent and known user information, like their name.
The main chat loop will greet the user, handle their input, detect exit commands, and print out responses. I won’t dive into advanced topics and will focus on keeping the comments light but informative.Finalizing the chatbot code
I need to ensure the code is complete and runnable, using random.choice(intent["responses"]) for varied responses. To optimize, I’ll precompute example documents to reduce repeated NLP processing on static strings.
I’ll define a SimpleSpacyChatbot class that loads the spaCy model and organizes intents. The detect_intent function computes similarity scores and includes a fallback if the score is too low. I’ll also implement entity recognition to update user profiles based on their introductions and allow for time inquiries.
In the intent definitions, I’ll include appropriate examples and responses, clearly indicating this is a simple rule-based system. I'll instruct users to download the spaCy model at the top for clarity! Below is a simple, self‑contained Python program that simulates a conversational chatbot using spaCy for natural language processing (tokenization, similarity, and entity recognition).
It runs in the terminal and supports:
- Intent detection using spaCy’s
Doc.similarity
- Remembering the user’s name from sentences like “My name is Alice” or “I’m Bob”
- Simple responses for greeting, time, small talk, etc.
1. Install spaCy and a model (once)
pip install spacy
python -m spacy download en_core_web_sm
2. Chatbot program (spacy_chatbot.py)
import random
from datetime import datetime
import spacy
class SpacyChatbot:
def __init__(self, model_name: str = "en_core_web_sm"):
# Load spaCy model
self.nlp = spacy.load(model_name)
# Define simple intents with example sentences and canned responses
self.intents = {
"greet": {
"examples": [
"hello",
"hi",
"hey",
"good morning",
"good evening",
"hi there"
],
"responses": [
"Hello!",
"Hi there!",
"Hey! How can I help you today?",
"Nice to see you. What can I do for you?"
],
},
"goodbye": {
"examples": [
"bye",
"goodbye",
"see you later",
"see ya",
"catch you later"
],
"responses": [
"Goodbye!",
"See you later!",
"Bye! It was nice talking to you.",
],
},
"thanks": {
"examples": [
"thanks",
"thank you",
"appreciate it",
"thanks a lot"
],
"responses": [
"You're welcome!",
"No problem!",
"Anytime!",
],
},
"name_query": {
"examples": [
"what is your name",
"who are you",
"tell me your name",
"what do I call you"
],
"responses": [
"I'm a simple chatbot built with spaCy.",
"You can call me SpaCyBot.",
],
},
"feeling": {
"examples": [
"how are you",
"how's it going",
"how are you doing",
"what's up"
],
"responses": [
"I'm just code, but I'm running fine. How are you?",
"I'm doing well, thanks for asking. How about you?",
],
},
"time": {
"examples": [
"what time is it",
"tell me the time",
"current time",
"can you tell me the time"
],
"responses": [
# A placeholder; we'll override dynamically with actual time
"Time placeholder",
],
},
"smalltalk": {
"examples": [
"tell me a joke",
"i am bored",
"talk to me",
"say something",
"tell me something"
],
"responses": [
"Sometimes I wonder if I'm just a bunch of if-statements and vectors. Oh wait, I am.",
"I can't tell great jokes yet, but I can chat about simple things!",
"We can talk about anything. What’s on your mind?",
],
},
# Fallback intent for low-confidence matches
"fallback": {
"examples": [],
"responses": [
"I'm not sure I understood that. Could you rephrase?",
"Sorry, I don't quite follow. Can you say it differently?",
"That’s a bit beyond my abilities right now. Try asking something simpler.",
],
},
}
# Precompute spaCy docs for all intent examples for faster similarity
self._compile_intents()
# Simple "memory" about the user
self.user_profile = {"name": None}
def _compile_intents(self):
"""Precompute spaCy docs for each example sentence."""
for intent_name, data in self.intents.items():
examples = data.get("examples", [])
data["example_docs"] = [self.nlp(text) for text in examples]
def update_profile_from_entities(self, doc):
"""
Use entity recognition and simple patterns to remember the user's name from
sentences like:
- "My name is Alice"
- "I'm Bob"
- "I am Charlie"
"""
text_lower = doc.text.lower()
# Check if the user is likely telling their name
name_patterns = ["my name is", "i am", "i'm"]
if any(pat in text_lower for pat in name_patterns):
for ent in doc.ents:
if ent.label_ == "PERSON":
self.user_profile["name"] = ent.text
break # Take the first PERSON entity
def detect_intent(self, doc, threshold: float = 0.65) -> str:
"""
Detect the most likely intent based on similarity between the user's
message and example sentences for each intent.
"""
best_intent = None
best_score = 0.0
for intent_name, data in self.intents.items():
if intent_name == "fallback":
continue # we only use fallback if we don't hit the threshold
example_docs = data.get("example_docs", [])
for ex_doc in example_docs:
score = doc.similarity(ex_doc)
if score > best_score:
best_score = score
best_intent = intent_name
if best_intent is None or best_score < threshold:
return "fallback"
return best_intent
def generate_response(self, intent: str, doc) -> str:
"""
Generate a response given the detected intent and the parsed spaCy doc.
"""
# Dynamic responses for specific intents
if intent == "time":
now = datetime.now().strftime("%H:%M")
return f"The current time is {now}."
if intent == "greet":
name = self.user_profile.get("name")
if name:
return random.choice(
[
f"Hello, {name}!",
f"Nice to see you again, {name}.",
f"Hi {name}! How can I help you today?",
]
)
# Default: choose a canned response
responses = self.intents[intent]["responses"]
return random.choice(responses)
def reply(self, text: str) -> str:
"""
Main entry point: given raw user text, return a chatbot response.
"""
doc = self.nlp(text)
# Update user profile based on entities (e.g., remember their name)
self.update_profile_from_entities(doc)
# Detect intent
intent = self.detect_intent(doc)
# Generate and return a response
return self.generate_response(intent, doc)
def main():
bot = SpacyChatbot()
print("SpaCy Chatbot")
print("Type 'quit' or 'exit' to stop.\n")
while True:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() in {"quit", "exit"}:
print("Bot: Goodbye!")
break
bot_response = bot.reply(user_input)
print("Bot:", bot_response)
if __name__ == "__main__":
main()
How to run
python spacy_chatbot.py
Then type messages such as:
Hello
My name is Alice
What time is it?
What is your name?
I'm bored
Thanks
If you’d like, I can extend this to support more intents, a file-based memory, or a simple REST API wrapper (e.g., using FastAPI or Flask).