#!/usr/bin/env python3 """ Intelligent Conversational AI System A comprehensive chatbot that demonstrates various conversational AI techniques Author: MiniMax Agent Date: 2025-12-21 """ import re import json import random import datetime from typing import Dict, List, Tuple, Optional from dataclasses import dataclass, asdict from collections import defaultdict @dataclass class Conversation: """Represents a conversation session""" session_id: str start_time: datetime.datetime messages: List[Dict[str, str]] context: Dict[str, any] def add_message(self, role: str, content: str): """Add a message to the conversation""" self.messages.append({ "role": role, "content": content, "timestamp": datetime.datetime.now().isoformat() }) def get_recent_context(self, num_messages: int = 5) -> List[str]: """Get recent message context""" return [msg["content"] for msg in self.messages[-num_messages:]] class PatternMatcher: """Rule-based pattern matching for responses""" def __init__(self): self.patterns = { # Greeting patterns r'\b(hello|hi|hey|greetings|good morning|good afternoon|good evening)\b': [ "Hello! I'm an AI assistant. How can I help you today?", "Hi there! I'm here to chat and assist you. What's on your mind?", "Hey! Great to meet you. What would you like to talk about?", "Greetings! I'm ready to have a meaningful conversation with you." ], # Weather queries r'\b(weather|temperature|rain|sunny|cloudy|forecast)\b': [ "I'd love to help with weather information! However, I don't have access to real-time weather data. You could check a weather service for current conditions.", "Weather questions are interesting! I can tell you that weather affects our daily activities and mood significantly.", "I don't have live weather access, but I can discuss weather patterns or suggest weather APIs you could use!" ], # Questions about AI r'\b(what are you|who are you|are you human|artificial intelligence|AI|robot)\b': [ "I'm an AI assistant created to have intelligent conversations! I use pattern matching, contextual understanding, and learned responses to engage with humans.", "I'm an artificial intelligence designed to chat, learn, and assist. While I'm not human, I can understand language and respond thoughtfully!", "I'm a conversational AI built with Python. I can understand questions, provide information, and maintain conversations using various AI techniques." ], # Help requests r'\b(help|assist|support|how to|guide|explain)\b': [ "I'm here to help! I can discuss topics, answer questions, provide information, or just have a friendly conversation. What would you like assistance with?", "Absolutely! I can help with various topics like explaining concepts, discussing ideas, or providing information. What do you need help with?", "Of course! I'm designed to assist and engage. Whether you have questions, need explanations, or want to chat, I'm ready to help!" ], # Time/date queries r'\b(time|date|when|current|today|now)\b': [ f"The current time is {datetime.datetime.now().strftime('%H:%M:%S')}, and today is {datetime.datetime.now().strftime('%Y-%m-%d')}.", "I can tell you the current time! I also enjoy discussing how time affects our lives and conversations.", "Time is fascinating - it's constantly moving forward, shaping our experiences and conversations!" ], # Emotions/feelings r'\b(feel|sad|happy|angry|excited|tired|worried|excited)\b': [ "It's great that you're sharing your feelings! Emotions are an important part of human experience. How are you feeling right now?", "I appreciate you opening up about emotions. While I don't have feelings myself, I find human emotions fascinating and worth discussing!", "Emotions make conversations meaningful! Whether you're feeling good or having a tough day, I'm here to listen and chat." ], # Learning/study queries r'\b(learn|study|education|school|university|course|book)\b': [ "Learning is one of the most exciting things we can do! I love discussing educational topics. What subject interests you?", "Education and learning are wonderful topics! I can discuss various subjects or help you think through learning strategies.", "Studying and learning are so important! I'd be happy to chat about different educational approaches or topics you're interested in." ], # Technology questions r'\b(technology|computer|software|programming|coding|internet|digital)\b': [ "Technology is fascinating! I especially enjoy discussions about programming, AI, and how technology shapes our world.", "I love talking about technology! Whether it's programming, AI, or digital innovations, there's always something exciting happening.", "Technology is constantly evolving! I'm particularly interested in conversational AI and natural language processing." ] } self.fallback_responses = [ "That's an interesting point! Could you tell me more about what you're thinking?", "I find that intriguing. What's your perspective on this topic?", "That's worth exploring further. What aspects interest you most?", "I'd love to understand this better from your viewpoint. Could you elaborate?", "You raise a good question. What led you to think about this?", "That's a thoughtful observation. I'd like to hear more about your thoughts on this.", "Interesting! How do you see this fitting into the bigger picture?", "That's a complex topic. What particular angle interests you most?" ] def match_pattern(self, text: str) -> Optional[str]: """Find matching pattern and return appropriate response""" text_lower = text.lower().strip() for pattern, responses in self.patterns.items(): if re.search(pattern, text_lower): return random.choice(responses) return None class ContextualMemory: """Maintains conversation context and learns from interactions""" def __init__(self): self.conversation_topics = defaultdict(list) self.user_preferences = defaultdict(list) self.topic_sentiment = defaultdict(float) def update_context(self, conversation: Conversation): """Update memory based on conversation content""" for message in conversation.messages: if message["role"] == "user": content = message["content"] # Extract topics and update memory self._extract_and_update_topics(content) def _extract_and_update_topics(self, text: str): """Extract topics and update memory""" # Simple keyword extraction words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower()) topics = [word for word in words if len(word) > 3] for topic in topics: self.conversation_topics[topic].append(datetime.datetime.now()) def get_relevant_context(self, current_text: str) -> Dict[str, any]: """Get context relevant to current conversation""" current_words = set(re.findall(r'\b[a-zA-Z]{3,}\b', current_text.lower())) relevant_topics = [] for topic, occurrences in self.conversation_topics.items(): if topic in current_words: relevant_topics.append(topic) return { "relevant_topics": relevant_topics, "conversation_history": len(self.conversation_topics), "user_interests": list(self.user_preferences.keys())[:5] } class PersonalityEngine: """Manages conversational personality and style""" def __init__(self): self.personalities = { "friendly": { "greeting_style": "warm and welcoming", "response_style": "enthusiastic and supportive", "emoji_style": "moderate use", "adjectives": ["great", "wonderful", "fantastic", "awesome", "amazing"] }, "professional": { "greeting_style": "formal and respectful", "response_style": "detailed and informative", "emoji_style": "minimal use", "adjectives": ["excellent", "valuable", "insightful", "important", "significant"] }, "casual": { "greeting_style": "relaxed and informal", "response_style": "conversational and easygoing", "emoji_style": "frequent use", "adjectives": ["cool", "interesting", "nice", "good", "solid"] }, "intellectual": { "greeting_style": "thoughtful and analytical", "response_style": "deep and philosophical", "emoji_style": "rare use", "adjectives": ["profound", "complex", "nuanced", "sophisticated", "intricate"] } } self.current_personality = "friendly" def set_personality(self, personality_type: str): """Set the conversational personality""" if personality_type in self.personalities: self.current_personality = personality_type def get_response_with_personality(self, base_response: str) -> str: """Enhance response with personality traits""" personality = self.personalities[self.current_personality] # Add personality-specific flourishes if self.current_personality == "friendly": if not any(word in base_response.lower() for word in ["hello", "hi", "hey"]): base_response = f"{random.choice(personality['adjectives']).title()}! {base_response}" elif self.current_personality == "casual": base_response += " 😊" elif self.current_personality == "professional": # Make more formal base_response = base_response.replace("I'm", "I am").replace("I'm", "I am") return base_response class IntelligentConversationalAI: """Main conversational AI system""" def __init__(self): self.pattern_matcher = PatternMatcher() self.memory = ContextualMemory() self.personality_engine = PersonalityEngine() self.active_conversations = {} self.conversation_counter = 0 def create_conversation(self) -> str: """Create a new conversation session""" self.conversation_counter += 1 session_id = f"conv_{self.conversation_counter}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}" conversation = Conversation( session_id=session_id, start_time=datetime.datetime.now(), messages=[], context={} ) self.active_conversations[session_id] = conversation return session_id def process_message(self, session_id: str, user_message: str) -> str: """Process user message and generate intelligent response""" # Get or create conversation if session_id not in self.active_conversations: session_id = self.create_conversation() conversation = self.active_conversations[session_id] # Add user message to conversation conversation.add_message("user", user_message) # Update memory with conversation context self.memory.update_context(conversation) # Generate response response = self._generate_response(user_message, conversation) # Add AI response to conversation conversation.add_message("assistant", response) # Update conversation context conversation.context = self.memory.get_relevant_context(user_message) return response def _generate_response(self, user_message: str, conversation: Conversation) -> str: """Generate intelligent response based on context and patterns""" # First try pattern matching pattern_response = self.pattern_matcher.match_pattern(user_message) if pattern_response: response = pattern_response else: # Contextual response generation response = self._generate_contextual_response(user_message, conversation) # Apply personality response = self.personality_engine.get_response_with_personality(response) # Add conversation continuity response = self._add_conversation_flow(response, conversation) return response def _generate_contextual_response(self, user_message: str, conversation: Conversation) -> str: """Generate response using conversation context""" recent_context = conversation.get_recent_context(3) # Check for questions that need follow-up if "?" in user_message: return "That's a great question! I'd love to explore that topic further with you." # Check for statements that could use elaboration if len(user_message.split()) > 10: return "I find that really interesting! Could you tell me more about your perspective on this?" # Check for emotional content emotional_words = ["feel", "sad", "happy", "excited", "worried", "angry"] if any(word in user_message.lower() for word in emotional_words): return "I appreciate you sharing that with me. Emotions make our conversations more meaningful!" # Default contextual response contextual_responses = [ "That's worth discussing further. What's your take on this?", "I see what you mean. How do you think this fits into the bigger picture?", "Interesting point! What aspects of this topic intrigue you most?", "That's a thoughtful observation. I'd love to hear more about your thoughts." ] return random.choice(contextual_responses) def _add_conversation_flow(self, response: str, conversation: Conversation) -> str: """Add natural conversation flow elements""" # Add follow-up questions occasionally if len(conversation.messages) > 2 and random.random() < 0.3: follow_ups = [ " What do you think about that?", " How does that resonate with you?", " What's your experience with this?", " What would you like to explore next?" ] response += random.choice(follow_ups) return response def get_conversation_summary(self, session_id: str) -> Dict[str, any]: """Get summary of conversation""" if session_id not in self.active_conversations: return {"error": "Conversation not found"} conversation = self.active_conversations[session_id] return { "session_id": session_id, "duration": str(datetime.datetime.now() - conversation.start_time), "message_count": len(conversation.messages), "topics_discussed": list(conversation.context.get("relevant_topics", [])), "user_interests": conversation.context.get("user_interests", []) } def list_conversations(self) -> List[str]: """List all active conversation sessions""" return list(self.active_conversations.keys()) def set_personality(self, personality: str): """Set conversational personality""" self.personality_engine.set_personality(personality) def get_available_personalities(self) -> List[str]: """Get list of available personalities""" return list(self.personality_engine.personalities.keys()) class CLIInterface: """Command-line interface for the conversational AI""" def __init__(self): self.ai = IntelligentConversationalAI() self.current_session = self.ai.create_conversation() self.running = True def display_welcome(self): """Display welcome message and instructions""" print("=" * 60) print("šŸ¤– INTELLIGENT CONVERSATIONAL AI SYSTEM") print("=" * 60) print("Welcome to your personal AI assistant!") print() print("Features:") print("• Intelligent pattern matching") print("• Contextual memory and learning") print("• Multiple personality modes") print("• Conversation continuity") print("• Natural dialogue flow") print() print("Available commands:") print(" /help - Show this help") print(" /personality - Change personality") print(" /summary - Show conversation summary") print(" /topics - Show discussed topics") print(" /clear - Start new conversation") print(" /quit - Exit program") print() print(f"Current personality: {self.ai.personality_engine.current_personality}") print("=" * 60) print() def handle_command(self, user_input: str) -> bool: """Handle special commands""" command = user_input.strip().lower() if command == "/help": self.display_help() return True elif command == "/personality": self.change_personality() return True elif command == "/summary": self.show_summary() return True elif command == "/topics": self.show_topics() return True elif command == "/clear": self.new_conversation() return True elif command == "/quit" or command == "/exit": self.running = False return True else: return False def display_help(self): """Display help information""" print("\n" + "=" * 40) print("HELP - Conversational AI Commands") print("=" * 40) print("This AI can:") print("• Understand natural language patterns") print("• Remember conversation context") print("• Adapt personality and style") print("• Generate thoughtful responses") print("• Maintain engaging dialogue") print() print("Tips for better conversations:") print("• Be natural and conversational") print("• Ask open-ended questions") print("• Share your thoughts and feelings") print("• Explore different topics") print() print("Type /quit to exit when finished.") print("=" * 40) print() def change_personality(self): """Change AI personality""" print("\nAvailable personalities:") personalities = self.ai.get_available_personalities() for i, personality in enumerate(personalities, 1): print(f" {i}. {personality.title()}") try: choice = input("\nSelect personality (1-4): ").strip() if choice.isdigit() and 1 <= int(choice) <= len(personalities): selected = personalities[int(choice) - 1] self.ai.set_personality(selected) print(f"\nPersonality changed to: {selected.title()}") else: print("\nInvalid selection.") except (ValueError, KeyboardInterrupt): print("\nCancelled personality change.") print() def show_summary(self): """Show conversation summary""" summary = self.ai.get_conversation_summary(self.current_session) print("\n" + "=" * 40) print("CONVERSATION SUMMARY") print("=" * 40) print(f"Session ID: {summary.get('session_id', 'N/A')}") print(f"Duration: {summary.get('duration', 'N/A')}") print(f"Messages: {summary.get('message_count', 0)}") print(f"Topics: {', '.join(summary.get('topics_discussed', ['None yet']))}") print(f"Interests: {', '.join(summary.get('user_interests', ['None detected']))}") print("=" * 40) print() def show_topics(self): """Show topics discussed""" conversation = self.ai.active_conversations.get(self.current_session) if conversation and conversation.context.get("relevant_topics"): topics = conversation.context["relevant_topics"] print("\n" + "=" * 30) print("TOPICS DISCUSSED") print("=" * 30) for topic in topics: print(f"• {topic.title()}") print("=" * 30) else: print("\nNo specific topics identified yet.") print() def new_conversation(self): """Start a new conversation""" self.current_session = self.ai.create_conversation() print("\n✨ New conversation started!") print("All previous context has been cleared.") print() def run(self): """Run the main conversation loop""" self.display_welcome() while self.running: try: user_input = input("You: ").strip() if not user_input: continue # Handle commands if user_input.startswith('/'): if self.handle_command(user_input): continue # Process with AI response = self.ai.process_message(self.current_session, user_input) print(f"AI: {response}") except KeyboardInterrupt: print("\n\nGoodbye! Thanks for chatting! šŸ‘‹") break except Exception as e: print(f"\nError: {e}") print("Please try again.") print("\nSession ended. Thank you for using the Conversational AI!") def demonstrate_ai_capabilities(): """Demonstrate AI capabilities without interactive mode""" print("šŸ¤– DEMONSTRATING CONVERSATIONAL AI CAPABILITIES") print("=" * 60) ai = IntelligentConversationalAI() session = ai.create_conversation() # Demo conversations demo_exchanges = [ "Hello! I'm excited to meet you today!", "What are you? Are you human or AI?", "I love learning about technology and programming.", "Can you help me understand artificial intelligence?", "I'm feeling curious about how you work.", "What time is it right now?", "This has been a fascinating conversation!", "Can you tell me about weather patterns?", "I'm interested in studying machine learning.", "How do you remember our conversation?" ] print("\nSimulated conversation:") print("-" * 30) for i, user_message in enumerate(demo_exchanges, 1): print(f"\nExchange {i}:") print(f"User: {user_message}") response = ai.process_message(session, user_message) print(f"AI: {response}") if i % 3 == 0: print("\n" + "=" * 50) # Show final summary summary = ai.get_conversation_summary(session) print("\n" + "=" * 60) print("CONVERSATION ANALYSIS") print("=" * 60) print(f"Total exchanges: {summary['message_count'] // 2}") print(f"Topics identified: {', '.join(summary['topics_discussed'])}") print(f"User interests: {', '.join(summary['user_interests'])}") print("=" * 60) def main(): """Main function with menu selection""" print("šŸ¤– INTELLIGENT CONVERSATIONAL AI SYSTEM") print("=" * 50) print("1. Interactive Chat Mode") print("2. Demo Mode (See AI capabilities)") print("3. Exit") print("=" * 50) while True: try: choice = input("\nSelect an option (1-3): ").strip() if choice == "1": cli = CLIInterface() cli.run() break elif choice == "2": demonstrate_ai_capabilities() break elif choice == "3": print("Goodbye! šŸ‘‹") break else: print("Invalid choice. Please select 1, 2, or 3.") except KeyboardInterrupt: print("\n\nGoodbye! šŸ‘‹") break except Exception as e: print(f"Error: {e}") print("Please try again.") if __name__ == "__main__": main()