Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconNatural Language Processing with Python Updated Edition
Natural Language Processing with Python Updated Edition

Chapter 10: Introduction to Chatbots

Practical Exercises

Exercise 1: Rule-Based Chatbot

Task: Implement a rule-based chatbot that can answer basic questions about a fictional company's contact information, hours of operation, and services offered.

Solution:

def rule_based_chatbot(user_input):
    responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what are your hours of operation?": "Our office is open from 9 AM to 5 PM, Monday to Friday.",
        "where are you located?": "We are located at 123 Main Street, Anytown, USA.",
        "what services do you offer?": "We offer web development, mobile app development, and digital marketing services.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input = user_input.lower()
    return responses.get(user_input, "I'm sorry, I don't understand that. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = rule_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 2: Retrieval-Based Chatbot

Task: Implement a retrieval-based chatbot that uses TF-IDF vectorizer and cosine similarity to match user queries with predefined responses.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def retrieval_based_chatbot(user_input):
    user_input_vector = vectorizer.transform([user_input])
    similarities = cosine_similarity(user_input_vector, X)
    response_index = similarities.argmax()
    return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = retrieval_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 3: Generative Chatbot

Task: Implement a simple generative chatbot using an existing Seq2Seq model for generating responses. For this exercise, we'll simulate the use of a pre-trained model.

Solution:
Since training a Seq2Seq model from scratch is complex and requires a significant amount of data, we will simulate the responses as if generated by a pre-trained Seq2Seq model.

# Simulated pre-trained Seq2Seq model responses
pretrained_responses = {
    "hello": "Hello! How can I help you today?",
    "how are you?": "I'm just a chatbot, but I'm here to assist you!",
    "what is your name?": "I am ChatBot, your virtual assistant.",
    "bye": "Goodbye! Take care!"
}

def generative_chatbot(user_input):
    user_input = user_input.lower()
    return pretrained_responses.get(user_input, "I'm still learning. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Take care!")
        break
    response = generative_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 4: Hybrid Chatbot

Task: Implement a hybrid chatbot that uses rule-based responses for common greetings and self-learning (retrieval-based) responses for other queries.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 5: Enhancing the Hybrid Chatbot with More Responses

Task: Enhance the hybrid chatbot by adding more rule-based responses and expanding the retrieval-based corpus.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services.",
    "You can contact us at support@company.com.",
    "Our phone number is (123) 456-7890."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def enhanced_hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what is your phone number?": "Our phone number is (123) 456-7890.",
        "what is your email address?": "You can contact us at support@company.com.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = enhanced_hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

These exercises provide hands-on experience with different types of chatbots, reinforcing the concepts covered in this chapter.

Practical Exercises

Exercise 1: Rule-Based Chatbot

Task: Implement a rule-based chatbot that can answer basic questions about a fictional company's contact information, hours of operation, and services offered.

Solution:

def rule_based_chatbot(user_input):
    responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what are your hours of operation?": "Our office is open from 9 AM to 5 PM, Monday to Friday.",
        "where are you located?": "We are located at 123 Main Street, Anytown, USA.",
        "what services do you offer?": "We offer web development, mobile app development, and digital marketing services.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input = user_input.lower()
    return responses.get(user_input, "I'm sorry, I don't understand that. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = rule_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 2: Retrieval-Based Chatbot

Task: Implement a retrieval-based chatbot that uses TF-IDF vectorizer and cosine similarity to match user queries with predefined responses.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def retrieval_based_chatbot(user_input):
    user_input_vector = vectorizer.transform([user_input])
    similarities = cosine_similarity(user_input_vector, X)
    response_index = similarities.argmax()
    return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = retrieval_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 3: Generative Chatbot

Task: Implement a simple generative chatbot using an existing Seq2Seq model for generating responses. For this exercise, we'll simulate the use of a pre-trained model.

Solution:
Since training a Seq2Seq model from scratch is complex and requires a significant amount of data, we will simulate the responses as if generated by a pre-trained Seq2Seq model.

# Simulated pre-trained Seq2Seq model responses
pretrained_responses = {
    "hello": "Hello! How can I help you today?",
    "how are you?": "I'm just a chatbot, but I'm here to assist you!",
    "what is your name?": "I am ChatBot, your virtual assistant.",
    "bye": "Goodbye! Take care!"
}

def generative_chatbot(user_input):
    user_input = user_input.lower()
    return pretrained_responses.get(user_input, "I'm still learning. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Take care!")
        break
    response = generative_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 4: Hybrid Chatbot

Task: Implement a hybrid chatbot that uses rule-based responses for common greetings and self-learning (retrieval-based) responses for other queries.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 5: Enhancing the Hybrid Chatbot with More Responses

Task: Enhance the hybrid chatbot by adding more rule-based responses and expanding the retrieval-based corpus.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services.",
    "You can contact us at support@company.com.",
    "Our phone number is (123) 456-7890."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def enhanced_hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what is your phone number?": "Our phone number is (123) 456-7890.",
        "what is your email address?": "You can contact us at support@company.com.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = enhanced_hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

These exercises provide hands-on experience with different types of chatbots, reinforcing the concepts covered in this chapter.

Practical Exercises

Exercise 1: Rule-Based Chatbot

Task: Implement a rule-based chatbot that can answer basic questions about a fictional company's contact information, hours of operation, and services offered.

Solution:

def rule_based_chatbot(user_input):
    responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what are your hours of operation?": "Our office is open from 9 AM to 5 PM, Monday to Friday.",
        "where are you located?": "We are located at 123 Main Street, Anytown, USA.",
        "what services do you offer?": "We offer web development, mobile app development, and digital marketing services.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input = user_input.lower()
    return responses.get(user_input, "I'm sorry, I don't understand that. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = rule_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 2: Retrieval-Based Chatbot

Task: Implement a retrieval-based chatbot that uses TF-IDF vectorizer and cosine similarity to match user queries with predefined responses.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def retrieval_based_chatbot(user_input):
    user_input_vector = vectorizer.transform([user_input])
    similarities = cosine_similarity(user_input_vector, X)
    response_index = similarities.argmax()
    return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = retrieval_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 3: Generative Chatbot

Task: Implement a simple generative chatbot using an existing Seq2Seq model for generating responses. For this exercise, we'll simulate the use of a pre-trained model.

Solution:
Since training a Seq2Seq model from scratch is complex and requires a significant amount of data, we will simulate the responses as if generated by a pre-trained Seq2Seq model.

# Simulated pre-trained Seq2Seq model responses
pretrained_responses = {
    "hello": "Hello! How can I help you today?",
    "how are you?": "I'm just a chatbot, but I'm here to assist you!",
    "what is your name?": "I am ChatBot, your virtual assistant.",
    "bye": "Goodbye! Take care!"
}

def generative_chatbot(user_input):
    user_input = user_input.lower()
    return pretrained_responses.get(user_input, "I'm still learning. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Take care!")
        break
    response = generative_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 4: Hybrid Chatbot

Task: Implement a hybrid chatbot that uses rule-based responses for common greetings and self-learning (retrieval-based) responses for other queries.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 5: Enhancing the Hybrid Chatbot with More Responses

Task: Enhance the hybrid chatbot by adding more rule-based responses and expanding the retrieval-based corpus.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services.",
    "You can contact us at support@company.com.",
    "Our phone number is (123) 456-7890."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def enhanced_hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what is your phone number?": "Our phone number is (123) 456-7890.",
        "what is your email address?": "You can contact us at support@company.com.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = enhanced_hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

These exercises provide hands-on experience with different types of chatbots, reinforcing the concepts covered in this chapter.

Practical Exercises

Exercise 1: Rule-Based Chatbot

Task: Implement a rule-based chatbot that can answer basic questions about a fictional company's contact information, hours of operation, and services offered.

Solution:

def rule_based_chatbot(user_input):
    responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what are your hours of operation?": "Our office is open from 9 AM to 5 PM, Monday to Friday.",
        "where are you located?": "We are located at 123 Main Street, Anytown, USA.",
        "what services do you offer?": "We offer web development, mobile app development, and digital marketing services.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input = user_input.lower()
    return responses.get(user_input, "I'm sorry, I don't understand that. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = rule_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 2: Retrieval-Based Chatbot

Task: Implement a retrieval-based chatbot that uses TF-IDF vectorizer and cosine similarity to match user queries with predefined responses.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def retrieval_based_chatbot(user_input):
    user_input_vector = vectorizer.transform([user_input])
    similarities = cosine_similarity(user_input_vector, X)
    response_index = similarities.argmax()
    return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = retrieval_based_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 3: Generative Chatbot

Task: Implement a simple generative chatbot using an existing Seq2Seq model for generating responses. For this exercise, we'll simulate the use of a pre-trained model.

Solution:
Since training a Seq2Seq model from scratch is complex and requires a significant amount of data, we will simulate the responses as if generated by a pre-trained Seq2Seq model.

# Simulated pre-trained Seq2Seq model responses
pretrained_responses = {
    "hello": "Hello! How can I help you today?",
    "how are you?": "I'm just a chatbot, but I'm here to assist you!",
    "what is your name?": "I am ChatBot, your virtual assistant.",
    "bye": "Goodbye! Take care!"
}

def generative_chatbot(user_input):
    user_input = user_input.lower()
    return pretrained_responses.get(user_input, "I'm still learning. Can you please rephrase?")

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Take care!")
        break
    response = generative_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 4: Hybrid Chatbot

Task: Implement a hybrid chatbot that uses rule-based responses for common greetings and self-learning (retrieval-based) responses for other queries.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

Exercise 5: Enhancing the Hybrid Chatbot with More Responses

Task: Enhance the hybrid chatbot by adding more rule-based responses and expanding the retrieval-based corpus.

Solution:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

corpus = [
    "Our office is open from 9 AM to 5 PM, Monday to Friday.",
    "We are located at 123 Main Street, Anytown, USA.",
    "We offer web development, mobile app development, and digital marketing services.",
    "You can contact us at support@company.com.",
    "Our phone number is (123) 456-7890."
]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

def enhanced_hybrid_chatbot(user_input):
    rule_based_responses = {
        "hello": "Hello! How can I assist you today?",
        "hi": "Hi there! What can I do for you?",
        "what is your phone number?": "Our phone number is (123) 456-7890.",
        "what is your email address?": "You can contact us at support@company.com.",
        "bye": "Goodbye! Have a great day!"
    }

    user_input_lower = user_input.lower()
    if user_input_lower in rule_based_responses:
        return rule_based_responses[user_input_lower]
    else:
        user_input_vector = vectorizer.transform([user_input])
        similarities = cosine_similarity(user_input_vector, X)
        response_index = similarities.argmax()
        return corpus[response_index]

# Test the chatbot
while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("ChatBot: Goodbye! Have a great day!")
        break
    response = enhanced_hybrid_chatbot(user_input)
    print(f"ChatBot: {response}")

These exercises provide hands-on experience with different types of chatbots, reinforcing the concepts covered in this chapter.