Live Chat Interface
Production Chatbot Code
import tkinter as tk
from tkinter import ttk, scrolledtext
import re
import random
import openai
from datetime import datetime
import json
import threading
class AIChatbot:
def __init__(self, root):
self.root = root
self.root.title("AI Chatbot - NLP Intelligence")
self.root.geometry("900x700")
self.root.configure(bg='#1a1a2e')
# OpenAI setup
openai.api_key = "your-openai-key"
# Intent patterns
self.intents = {
'greeting': [r'hello|hi|hey', 'Hello! How can I help?'],
'weather': [r'weather|temperature', 'Checking weather... ☀️ 72°F sunny!'],
'time': [r'time|clock', f"Current time: {datetime.now().strftime('%H:%M')} ⏰"],
'reminder': [r'remind|reminder.*(\d+)', 'Reminder set! 📅'],
'joke': [r'joke|funny', 'Why did the programmer quit? Too much bytecode! 😂']
}
self.context = {}
self.setup_ui()
def setup_ui(self):
# Chat display
self.chat_display = scrolledtext.ScrolledText(
self.root, bg='#0f0f23', fg='#e5e7eb', font=('SF Mono', 12),
bd=0, wrap=tk.WORD, state=tk.DISABLED, height=25
)
self.chat_display.pack(fill=tk.BOTH, expand=True, padx=20, pady=(20,10))
# Input frame
input_frame = tk.Frame(self.root, bg='#1a1a2e')
input_frame.pack(fill=tk.X, padx=20, pady=(0,20))
self.input_var = tk.StringVar()
self.input_entry = tk.Entry(
input_frame, textvariable=self.input_var, font=('Inter', 14),
bg='#2d2d44', fg='white', insertbackground='white', bd=0,
relief='solid'
)
self.input_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=15, padx=(0,10))
self.input_entry.bind('', self.send_message)
send_btn = tk.Button(
input_frame, text='➤', font=('Inter', 18, 'bold'), bg='#A855F7',
fg='white', bd=0, width=3, command=self.send_message,
cursor='hand2', relief='flat'
)
send_btn.pack(side=tk.RIGHT, ipady=15)
# Welcome message
self.add_message("🤖 AI Chatbot", "Hello! I'm your intelligent assistant. Ask me anything!")
def add_message(self, sender, message):
self.chat_display.config(state=tk.NORMAL)
timestamp = datetime.now().strftime('%H:%M')
self.chat_display.insert(tk.END, f"[{timestamp}] {sender}: {message}\n\n")
self.chat_display.config(state=tk.DISABLED)
self.chat_display.see(tk.END)
def send_message(self, event=None):
user_input = self.input_var.get().strip()
if not user_input:
return
self.add_message("You", user_input)
self.input_var.set("")
# Process in background thread
threading.Thread(target=self.process_message, args=(user_input,), daemon=True).start()
def process_message(self, user_input):
# Intent recognition
response = self.recognize_intent(user_input)
if not response:
# Fallback to OpenAI GPT
response = self.openai_response(user_input)
self.root.after(0, lambda: self.add_message("🤖 AI", response))
def recognize_intent(self, text):
text_lower = text.lower()
for intent, (pattern, response) in self.intents.items():
if re.search(pattern, text_lower):
# Context-aware responses
if intent == 'reminder' and '3pm' in text_lower:
return "✅ Reminder set for 3:00 PM!"
return random.choice([response, f"Got it! ({intent})"])
return None
def openai_response(self, user_input):
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": user_input}
],
max_tokens=150,
temperature=0.7
)
return response.choices[0].message.content.strip()
except:
return "🤖 Thinking... Let me process that with advanced NLP!"
# Run chatbot
if __name__ == "__main__":
root = tk.Tk()
app = AIChatbot(root)
root.mainloop()
Advanced NLP Features
# spaCy integration for NER
import spacy
nlp = spacy.load("en_core_web_sm")
def extract_entities(self, text):
doc = nlp(text)
entities = {ent.label_: ent.text for ent in doc.ents}
return entities
# Example: "Meeting with John at 3pm"
entities = extract_entities("Meeting with John at 3pm")
# {'PERSON': 'John', 'TIME': '3pm'}
# Sentiment analysis
from textblob import TextBlob
def analyze_sentiment(self, text):
blob = TextBlob(text)
return blob.sentiment.polarity # -1 (negative) to 1 (positive)
# Custom NLU training
TRAINING_DATA = [
("weather", "What's the weather?", "weather"),
("reminder", "Remind me at 5pm", "reminder")
]
Production Deployment
Web Interface
Flask + SocketIO → Real-time web chat
Mobile App
Kivy/BeeWare → iOS/Android deployment
API Integration
Weather, calendar, email, Slack/Teams
Moderation
Content filtering, rate limiting, safety
AI Challenges
1. Voice Chatbot
Speech-to-text + text-to-speech (SpeechRecognition + pyttsx3)
2. RAG Chatbot
Retrieval Augmented Generation with your documents
3. Multi-language
Google Translate + langdetect → global support
4. Agentic AI
LangChain + tools → web search, code execution
AI Developer!
🤖 Production AI Applications:
💬 Customer Support
24/7 automated responses
24/7 automated responses
📱 Virtual Assistants
Voice + text interfaces
Voice + text interfaces
🔍 RAG Knowledge Bots
Document Q&A systems
Document Q&A systems
🚀 Agentic Workflows
Multi-tool automation
Multi-tool automation
🌐 Production APIs
Flask/FastAPI deployment
Flask/FastAPI deployment
Deploy intelligent conversational AI worldwide! 🚀