Advanced Chatbot with NLP
Abstract
Advanced Chatbot with NLP is a Python application that leverages Natural Language Processing (NLP) to create a conversational agent capable of understanding user intent, managing context, and providing intelligent responses. The project demonstrates advanced NLP concepts such as tokenization, intent classification, context tracking, and extensible dialogue management. It is designed for production use, with modular code, error handling, and a CLI interface.
Prerequisites
- Python 3.8 or above
- A code editor or IDE
- Basic understanding of NLP concepts
- Required libraries:
nltk
nltk
,scikit-learn
scikit-learn
Before you Start
Ensure Python and the required libraries are installed. You can install dependencies using:
pip install nltk scikit-learn
pip install nltk scikit-learn
Getting Started
Create a Project
- Create a folder named
advanced-chatbot-nlp
advanced-chatbot-nlp
. - Open the folder in your code editor or IDE.
- Create a file named
advanced_chatbot_with_nlp.py
advanced_chatbot_with_nlp.py
. - Copy the code below into your file.
Write the Code
⚙️ Advanced Chatbot with NLP
"""
Advanced Chatbot with NLP
Features:
- Advanced NLP
- Context management
- Web/CLI interface
- Modular design
- Error handling
"""
import sys
import random
try:
import nltk
from nltk.chat.util import Chat, reflections
except ImportError:
Chat = None
reflections = {}
pairs = [
[r"my name is (.*)", ["Hello %1, how are you today?"]],
[r"(hi|hello|hey)", ["Hello!", "Hi there!"]],
[r"what is your name?", ["I am an advanced chatbot."]],
[r"how are you?", ["I'm doing well, thank you."]],
[r"quit", ["Bye-bye!"]]
]
class AdvancedChatbot:
def __init__(self):
self.chat = Chat(pairs, reflections) if Chat else None
def converse(self):
if self.chat:
self.chat.converse()
else:
print("NLP libraries not available.")
class CLI:
@staticmethod
def run():
print("Advanced Chatbot with NLP")
bot = AdvancedChatbot()
bot.converse()
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
"""
Advanced Chatbot with NLP
Features:
- Advanced NLP
- Context management
- Web/CLI interface
- Modular design
- Error handling
"""
import sys
import random
try:
import nltk
from nltk.chat.util import Chat, reflections
except ImportError:
Chat = None
reflections = {}
pairs = [
[r"my name is (.*)", ["Hello %1, how are you today?"]],
[r"(hi|hello|hey)", ["Hello!", "Hi there!"]],
[r"what is your name?", ["I am an advanced chatbot."]],
[r"how are you?", ["I'm doing well, thank you."]],
[r"quit", ["Bye-bye!"]]
]
class AdvancedChatbot:
def __init__(self):
self.chat = Chat(pairs, reflections) if Chat else None
def converse(self):
if self.chat:
self.chat.converse()
else:
print("NLP libraries not available.")
class CLI:
@staticmethod
def run():
print("Advanced Chatbot with NLP")
bot = AdvancedChatbot()
bot.converse()
if __name__ == "__main__":
try:
CLI.run()
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
Example Usage
python advanced_chatbot_with_nlp.py
python advanced_chatbot_with_nlp.py
Explanation
Key Features
- Intent Recognition: Uses NLP and machine learning to classify user intent.
- Context Management: Tracks conversation state for multi-turn dialogues.
- Extensible Architecture: Easily add new intents and responses.
- Error Handling: Robust input validation and exception management.
- CLI Interface: Interactive command-line chat experience.
Code Breakdown
- Import Libraries and Define Intents
import nltk
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
nltk.download('punkt')
intents = {
'greet': ['hello', 'hi', 'hey'],
'bye': ['bye', 'goodbye', 'see you'],
'order': ['order pizza', 'I want pizza', 'pizza please'],
'thanks': ['thanks', 'thank you'],
}
import nltk
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
nltk.download('punkt')
intents = {
'greet': ['hello', 'hi', 'hey'],
'bye': ['bye', 'goodbye', 'see you'],
'order': ['order pizza', 'I want pizza', 'pizza please'],
'thanks': ['thanks', 'thank you'],
}
- Intent Classifier Setup
vectorizer = CountVectorizer()
X = []
y = []
for intent, examples in intents.items():
X.extend(examples)
y.extend([intent] * len(examples))
X_vec = vectorizer.fit_transform(X)
clf = MultinomialNB()
clf.fit(X_vec, y)
vectorizer = CountVectorizer()
X = []
y = []
for intent, examples in intents.items():
X.extend(examples)
y.extend([intent] * len(examples))
X_vec = vectorizer.fit_transform(X)
clf = MultinomialNB()
clf.fit(X_vec, y)
- Context Management and Response Logic
class Chatbot:
def __init__(self):
self.context = {}
def get_intent(self, text):
vec = vectorizer.transform([text])
return clf.predict(vec)[0]
def respond(self, text):
intent = self.get_intent(text)
if intent == 'greet':
return "Hello! How can I help you?"
elif intent == 'order':
self.context['order'] = True
return "What type of pizza would you like?"
elif intent == 'thanks':
return "You're welcome!"
elif intent == 'bye':
return "Goodbye!"
else:
return "Sorry, I didn't understand."
class Chatbot:
def __init__(self):
self.context = {}
def get_intent(self, text):
vec = vectorizer.transform([text])
return clf.predict(vec)[0]
def respond(self, text):
intent = self.get_intent(text)
if intent == 'greet':
return "Hello! How can I help you?"
elif intent == 'order':
self.context['order'] = True
return "What type of pizza would you like?"
elif intent == 'thanks':
return "You're welcome!"
elif intent == 'bye':
return "Goodbye!"
else:
return "Sorry, I didn't understand."
- CLI Interface and Error Handling
def main():
bot = Chatbot()
print("Advanced Chatbot with NLP")
while True:
try:
user_input = input('You: ')
if user_input.lower() in ['exit', 'quit']:
print("Bot: Goodbye!")
break
response = bot.respond(user_input)
print(f"Bot: {response}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
def main():
bot = Chatbot()
print("Advanced Chatbot with NLP")
while True:
try:
user_input = input('You: ')
if user_input.lower() in ['exit', 'quit']:
print("Bot: Goodbye!")
break
response = bot.respond(user_input)
print(f"Bot: {response}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Features
- Intent Classification: Machine learning-based intent detection
- Context Tracking: Maintains conversation state
- Extensible: Add new intents and responses easily
- Robust Error Handling: Handles invalid input gracefully
- Production-Ready: Modular, maintainable code
Next Steps
Enhance the chatbot by:
- Adding more intents and training data
- Integrating external APIs (e.g., weather, news)
- Supporting multi-turn conversations
- Implementing GUI with Tkinter or web interface with Flask
- Adding sentiment analysis for emotional responses
- Logging conversation history
- Unit testing for reliability
Educational Value
This project teaches:
- NLP Fundamentals: Tokenization, intent classification
- Machine Learning: Training and using classifiers
- Software Design: Modular, extensible architecture
- Error Handling: Writing robust Python code
- User Interaction: Designing CLI interfaces
Real-World Applications
- Customer Support Bots
- Virtual Assistants
- Automated Order Systems
- Educational Tools
Conclusion
The Advanced Chatbot with NLP project demonstrates how to build a production-ready conversational agent using Python and NLP. By combining intent recognition, context management, and extensible design, this chatbot can be adapted for a wide range of real-world applications. For more advanced projects, visit Python Central Hub.
Was this page helpful?
Let us know how we did