#!/usr/bin/env python3 """ Integration Examples - How to use Chat Service in different scenarios. This file shows practical examples of integrating the chat service with various types of applications. """ from chat_service_client import ChatServiceClient, MultiUserChatManager import asyncio import time from typing import Dict, List # Example 1: Learning Management System (LMS) Integration class LearningPlatformIntegration: """ Example integration with a learning management system. This shows how to maintain separate chat sessions for different courses and students. """ def __init__(self, chat_service_url: str = "http://localhost:5000"): self.chat_manager = MultiUserChatManager(chat_service_url, "LearningPlatform") self.course_languages = { "python-101": "python", "js-fundamentals": "javascript", "java-oop": "java", "cpp-advanced": "cpp" } def enroll_student_in_course(self, student_id: str, course_id: str) -> str: """ Enroll a student in a course and start their chat session. Args: student_id: Unique student identifier course_id: Course identifier Returns: Session ID for the student's chat """ language = self.course_languages.get(course_id, "python") # Create unique user ID combining student and course user_id = f"{student_id}_{course_id}" metadata = { "student_id": student_id, "course_id": course_id, "enrollment_date": time.strftime("%Y-%m-%d") } session_id = self.chat_manager.start_chat_for_user(user_id, language, metadata) # Send welcome message welcome_msg = f"Welcome to {course_id}! I'm your programming assistant. What would you like to learn about {language}?" self.chat_manager.send_user_message(user_id, welcome_msg) return session_id def student_ask_question(self, student_id: str, course_id: str, question: str) -> str: """ Student asks a question in their course context. Args: student_id: Student identifier course_id: Course identifier question: Student's question Returns: AI assistant's response """ user_id = f"{student_id}_{course_id}" try: response = self.chat_manager.send_user_message(user_id, question) return response['response'] except Exception as e: return f"Sorry, I couldn't process your question right now: {e}" def get_student_progress(self, student_id: str, course_id: str) -> Dict: """ Get student's chat history and progress. Args: student_id: Student identifier course_id: Course identifier Returns: Dict containing progress information """ user_id = f"{student_id}_{course_id}" try: history = self.chat_manager.get_user_history(user_id) # Analyze progress questions_asked = len([msg for msg in history if msg['role'] == 'user']) topics_covered = set() # Simple topic extraction (in practice, you'd use NLP) for msg in history: if msg['role'] == 'user': content = msg['content'].lower() if 'loop' in content: topics_covered.add('loops') if 'function' in content: topics_covered.add('functions') if 'class' in content: topics_covered.add('classes') # Add more topic detection logic return { 'student_id': student_id, 'course_id': course_id, 'questions_asked': questions_asked, 'topics_covered': list(topics_covered), 'last_activity': history[-1]['timestamp'] if history else None } except Exception as e: return {'error': str(e)} # Example 2: Code Editor Plugin Integration class CodeEditorPlugin: """ Example integration with a code editor (like VS Code, Sublime, etc.). This shows how to provide contextual help based on the current file and programming language. """ def __init__(self, chat_service_url: str = "http://localhost:5000"): self.client = ChatServiceClient(chat_service_url, "CodeEditor") self.user_sessions = {} # user_id -> {language -> session_id} def get_or_create_session(self, user_id: str, language: str) -> str: """ Get existing session for user+language or create new one. Args: user_id: User identifier language: Programming language Returns: Session ID """ if user_id not in self.user_sessions: self.user_sessions[user_id] = {} if language not in self.user_sessions[user_id]: # Create new session for this language session_data = self.client.create_session( f"{user_id}_{language}", language, {"context": "code_editor", "user_id": user_id} ) self.user_sessions[user_id][language] = session_data['session_id'] return self.user_sessions[user_id][language] def ask_about_code(self, user_id: str, language: str, code_snippet: str, question: str) -> str: """ Ask a question about a specific code snippet. Args: user_id: User identifier language: Programming language code_snippet: The code in question question: User's question about the code Returns: AI assistant's response """ session_id = self.get_or_create_session(user_id, language) # Format the question with code context formatted_question = f""" I have this {language} code: ```{language} {code_snippet} ``` {question} """ try: response = self.client.send_message(session_id, formatted_question) return response['response'] except Exception as e: return f"Error getting help: {e}" def explain_error(self, user_id: str, language: str, error_message: str, code_context: str = "") -> str: """ Explain an error message in context. Args: user_id: User identifier language: Programming language error_message: The error message code_context: Optional code that caused the error Returns: Explanation of the error """ session_id = self.get_or_create_session(user_id, language) question = f"I got this error in {language}:\n\n{error_message}" if code_context: question += f"\n\nThe code that caused it:\n```{language}\n{code_context}\n```" question += "\n\nCan you explain what's wrong and how to fix it?" try: response = self.client.send_message(session_id, question) return response['response'] except Exception as e: return f"Error explaining error: {e}" # Example 3: Chatbot for Website Integration class WebsiteChatbot: """ Example integration for a website chatbot. This shows how to handle anonymous users and session persistence across page reloads. """ def __init__(self, chat_service_url: str = "http://localhost:5000"): self.client = ChatServiceClient(chat_service_url, "WebsiteChatbot") self.anonymous_sessions = {} # browser_id -> session_id def start_anonymous_chat(self, browser_id: str, preferred_language: str = "python") -> Dict: """ Start a chat session for an anonymous website visitor. Args: browser_id: Unique browser/session identifier preferred_language: User's preferred programming language Returns: Dict with session info and welcome message """ # Create session with anonymous user ID user_id = f"anonymous_{browser_id}" metadata = { "session_type": "anonymous", "browser_id": browser_id, "start_time": time.strftime("%Y-%m-%d %H:%M:%S") } session_data = self.client.create_session(user_id, preferred_language, metadata) session_id = session_data['session_id'] # Store mapping self.anonymous_sessions[browser_id] = session_id # Send welcome message welcome_response = self.client.send_message( session_id, f"Hello! I'm a programming assistant. I can help you with {preferred_language} and other programming languages. What would you like to learn?" ) return { 'session_id': session_id, 'welcome_message': welcome_response['response'], 'language': preferred_language } def continue_anonymous_chat(self, browser_id: str, message: str) -> Dict: """ Continue an existing anonymous chat session. Args: browser_id: Browser identifier message: User's message Returns: Dict with response and session info """ if browser_id not in self.anonymous_sessions: # Session expired or doesn't exist, start new one return self.start_anonymous_chat(browser_id) session_id = self.anonymous_sessions[browser_id] try: response = self.client.send_message(session_id, message) return { 'response': response['response'], 'session_id': session_id, 'message_id': response.get('message_id') } except Exception as e: # Session might have expired, start new one return self.start_anonymous_chat(browser_id) def get_chat_widget_data(self, browser_id: str) -> Dict: """ Get data needed for the chat widget on the website. Args: browser_id: Browser identifier Returns: Dict with chat widget configuration """ has_active_session = browser_id in self.anonymous_sessions return { 'has_active_session': has_active_session, 'supported_languages': ['python', 'javascript', 'java', 'cpp', 'csharp'], 'welcome_message': "Hi! I'm here to help you with programming questions.", 'placeholder_text': "Ask me anything about programming...", 'session_id': self.anonymous_sessions.get(browser_id) } # Example 4: Mobile App Integration class MobileAppIntegration: """ Example integration for a mobile learning app. This shows how to handle user authentication and offline scenarios. """ def __init__(self, chat_service_url: str = "http://localhost:5000"): self.chat_manager = MultiUserChatManager(chat_service_url, "MobileLearningApp") self.offline_messages = {} # user_id -> List[messages] def login_user(self, user_id: str, user_profile: Dict) -> str: """ Handle user login and restore their chat session. Args: user_id: User identifier user_profile: User profile information Returns: Session ID """ # Determine preferred language from profile preferred_language = user_profile.get('preferred_language', 'python') metadata = { 'user_profile': user_profile, 'platform': 'mobile', 'login_time': time.strftime("%Y-%m-%d %H:%M:%S") } session_id = self.chat_manager.start_chat_for_user(user_id, preferred_language, metadata) # Process any offline messages if user_id in self.offline_messages: for message in self.offline_messages[user_id]: try: self.chat_manager.send_user_message(user_id, message) except Exception as e: print(f"Failed to send offline message: {e}") # Clear offline messages del self.offline_messages[user_id] return session_id def send_message_with_offline_support(self, user_id: str, message: str) -> Dict: """ Send message with offline support. Args: user_id: User identifier message: User's message Returns: Response dict or offline confirmation """ try: # Try to send message response = self.chat_manager.send_user_message(user_id, message) return { 'status': 'sent', 'response': response['response'], 'timestamp': response.get('timestamp') } except Exception as e: # Store message for later (offline mode) if user_id not in self.offline_messages: self.offline_messages[user_id] = [] self.offline_messages[user_id].append(message) return { 'status': 'offline', 'message': 'Message saved. Will be sent when connection is restored.', 'queued_messages': len(self.offline_messages[user_id]) } def sync_offline_messages(self, user_id: str) -> Dict: """ Sync offline messages when connection is restored. Args: user_id: User identifier Returns: Sync status """ if user_id not in self.offline_messages: return {'status': 'no_messages', 'synced': 0} messages = self.offline_messages[user_id] synced = 0 failed = 0 for message in messages: try: self.chat_manager.send_user_message(user_id, message) synced += 1 except Exception: failed += 1 # Clear successfully synced messages if failed == 0: del self.offline_messages[user_id] else: self.offline_messages[user_id] = self.offline_messages[user_id][-failed:] return { 'status': 'synced', 'synced': synced, 'failed': failed, 'remaining': len(self.offline_messages.get(user_id, [])) } if __name__ == "__main__": print("๐Ÿงช Testing Integration Examples") # Test Learning Platform Integration print("\n1. Testing Learning Platform Integration...") lms = LearningPlatformIntegration() try: # Enroll student session_id = lms.enroll_student_in_course("student123", "python-101") print(f"โœ… Student enrolled, session: {session_id}") # Student asks question response = lms.student_ask_question("student123", "python-101", "How do I create a list?") print(f"โœ… Response: {response[:100]}...") # Get progress progress = lms.get_student_progress("student123", "python-101") print(f"โœ… Progress: {progress}") except Exception as e: print(f"โŒ LMS test failed: {e}") # Test Code Editor Plugin print("\n2. Testing Code Editor Plugin...") editor = CodeEditorPlugin() try: code = "def hello():\n print('Hello World')" response = editor.ask_about_code("dev123", "python", code, "How can I improve this function?") print(f"โœ… Code help: {response[:100]}...") error_help = editor.explain_error("dev123", "python", "NameError: name 'x' is not defined") print(f"โœ… Error help: {error_help[:100]}...") except Exception as e: print(f"โŒ Editor test failed: {e}") print("\nโœ… Integration examples completed!")