Customer Support Chatbot using Python
Using a chatbot is more beneficial than a simple question/answer format for several reasons. Chatbots provide a more interactive and engaging user experience, offering real-time responses and the ability to handle a wide range of queries dynamically. Unlike static FAQs or predefined Q&A formats, chatbots can understand the context and intent behind user inputs, enabling them to provide more accurate and relevant responses. Additionally, chatbots can handle multiple queries in a conversational manner, making the interaction feel more natural and personalized. This project involves the creation of a custom chatbot API using Python’s Flask framework and integrating it into a Flutter mobile application. The chatbot uses a text classification model trained on common customer support queries to predict the intent of user input and provide appropriate responses using a pre-trained model for natural language understanding (NLU) such as spaCy.
Step-by-Step Guide
Setup Environment:
- Setup Python Programming language (if not setup previously).
- Install necessary libraries.
- Use a pre-trained model for natural language understanding (NLU) such as spaCy.
Define the Chatbot Structure:
- Create a basic conversational flow.
- Integrate with support systems (FAQs, ticketing systems).
Implement User Interface:
- Create a command-line interface for simplicity.
- Extend to a web-based interface using Flask.
Handle User Input and Responses:
- Process user queries.
- Provide responses from pre-defined answers or escalate to human support.
Sample Code
Here’s a simplified version of a contact support chatbot using spaCy for NLU and a basic command-line interface.
1. Setup Project & Virtual Environment
mkdir chatbot
cd chatbot
python3 -m venv venv
source venv/bin/activate
1. Install Necessary Libraries
pip install spacy
pip install spacy scikit-learn
python3 -m spacy download en_core_web_sm
2. Prepare the Dataset
Create a dataset with user queries and their corresponding intents. For simplicity, we’ll define a small dataset directly in the code.
import spacy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Load the spaCy model
nlp = spacy.load('en_core_web_sm')
# Sample dataset
data = [
("how can i reset my password", "reset_password"),
("i forgot my password", "reset_password"),
("what is the status of my order", "order_status"),
("where is my order", "order_status"),
("how can i contact support", "contact_support"),
("i need help", "contact_support")
]
# Split the data into training and test sets
train_data, test_data = train_test_split(data, test_size=0.25, random_state=42)
train_texts, train_labels = zip(*train_data)
test_texts, test_labels = zip(*test_data)
3. Preprocess the Data and Train the Model
We will use CountVectorizer
and MultinomialNB
from scikit-learn
to create a text classification pipeline.
# Create a text classification pipeline
model = make_pipeline(CountVectorizer(), MultinomialNB())
# Train the model
model.fit(train_texts, train_labels)
# Test the model
predicted_labels = model.predict(test_texts)
print("Test Results:")
for text, label, prediction in zip(test_texts, test_labels, predicted_labels):
print(f"Text: {text}\nActual: {label}\nPredicted: {prediction}\n")
# Check model accuracy
accuracy = accuracy_score(test_labels, predicted_labels)
print(f"Model Accuracy: {accuracy * 100:.2f}%")
4. Implement the Chatbot
Integrate the trained model into the chatbot to handle user queries.
def get_intent(text):
return model.predict([text])[0]
def get_response(intent):
responses = {
"reset_password": "To reset your password, click on 'Forgot Password' at the login screen and follow the instructions.",
"order_status": "You can check the status of your order in the 'My Orders' section of our website.",
"contact_support": "You can contact support via email at support@example.com or call us at 123-456-7890."
}
return responses.get(intent, "I'm not sure how to help with that. Please contact support directly at support@example.com.")
def chatbot():
print("Welcome to Support Chatbot. How can I assist you today?")
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit', 'bye']:
print("Chatbot: Goodbye! Have a great day!")
break
intent = get_intent(user_input)
response = get_response(intent)
print(f"Chatbot: {response}")
if __name__ == "__main__":
chatbot()
Explanation of Improvements
- Enhanced Dataset: More training examples have been added to improve the model’s understanding of different queries.
- Train/Test Split: Using
train_test_split
fromsklearn
to split the data more robustly. - Model Accuracy: Added accuracy check to evaluate the model performance on the test set.
- Improved Preprocessing: Using
CountVectorizer
which handles basic text preprocessing.
Running the Chatbot
This enhanced version should provide better responses due to improved training data and preprocessing. Running this script will start the chatbot in a command-line interface where it can handle various user queries more accurately.
If the responses are still not accurate, consider:
- Increasing the dataset size with more examples for each intent.
- Exploring more advanced models like
TfidfVectorizer
or even neural network-based models using libraries likeTensorFlow
orPyTorch
. - Fine-tuning the parameters of the
CountVectorizer
andMultinomialNB
model to better fit the data.
To create an API from your existing chatbot code, we can use Flask, which is a popular web framework for Python. Flask will allow us to expose endpoints that can interact with your chatbot functionality. Here’s how you can structure your code to create a basic Flask API for your chatbot:
Step-by-Step Guide to Create Flask API for Chatbot
1. Install Flask
If you haven’t already installed Flask, you can do so using pip:
pip install Flask
1. Create Flask Endpoint
# import flask
from flask import Flask, request, jsonify
# initialize the app
app = Flask(__name__)
# create api endpint
@app.route('/chatbot', methods=['POST'])
def chatbotapi():
data = request.get_json()
user_input = data['user_input']
intent = get_intent(user_input)
response = get_response(intent, user_input)
return jsonify({'response': response})
if __name__ == "__main__":
app.run(debug=True)
Testing the API
To test your Flask API:
- Save the Code: Save the above code into a file, for example,
chatbot_api.py
. - Run the Flask App: Open your terminal or command prompt, navigate to the directory where
chatbot_api.py
is saved, and run:
python3 chatbot_api.py
- Send POST Requests: You can use tools like Postman or
curl
to send POST requests tohttp://127.0.0.1:5000/chatbot
with JSON data:
{
"user_input": "How can I reset my password?"
}
- Receive Responses: The Flask app will respond with JSON containing the chatbot’s response:
{
"response": "To reset your password, click on 'Forgot Password' at the login screen and follow the instructions."
}
Security Considerations
- Authentication: Consider adding authentication (e.g., API keys, JWT tokens) to secure your API endpoints.
- Input Validation: Validate and sanitize user inputs to prevent security vulnerabilities (e.g., SQL injection, XSS).
- HTTPS: Deploy your Flask app with HTTPS to encrypt data transmitted over the network.
This setup provides a basic API for your chatbot that can be accessed from any client capable of making HTTP requests, such as mobile apps, web applications, or other backend services.
Conclusion
By following this project, you have successfully created a functional chatbot that can handle basic customer support queries. The chatbot leverages machine learning for intent classification and provides relevant responses based on user input. Integrating this chatbot into a Flutter application demonstrates how web APIs can be used to enhance mobile applications by providing dynamic and intelligent interactions.
This project can be further extended in various ways:
- Expand the Dataset: Increase the variety and number of sample queries to improve the chatbot’s accuracy and robustness.
- Enhance the Model: Experiment with more advanced machine learning models or fine-tune existing models for better performance.
- Improve the UI: Develop a more sophisticated user interface in Flutter to enhance user experience.
- Secure the API: Implement authentication and authorization mechanisms to secure the API endpoints.
Overall, this project provides a solid foundation for building and integrating AI-powered chatbots into mobile applications, demonstrating the power of combining Flask, machine learning, and Flutter for modern software development.
Get complete source code at: https://github.com/AyeshaIftikhar/cs-chatbot