help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
multi-language-chatbot
/
modules
RSK World
multi-language-chatbot
Multi-language Chatbot - Python + Flask + OpenAI API + NLP + Translation + Language Detection + Cultural Adaptation
modules
  • __pycache__
  • __init__.py194 B
  • analytics_engine.py28.6 KB
  • chatbot_core.py10.8 KB
  • collaboration_manager.py22.3 KB
  • conversation_memory.py25.2 KB
  • cultural_adapter.py12.3 KB
  • document_analyzer.py21.5 KB
  • language_detector.py5.8 KB
  • multimodal_processor.py32.7 KB
  • personality_engine.py33.6 KB
  • sentiment_analyzer.py16.9 KB
  • translator.py7.5 KB
  • voice_processor.py13.2 KB
chatbot_core.py
modules/chatbot_core.py
Raw Download
Find: Go to:
"""
Chatbot Core Module
Author: RSK World (https://rskworld.in)
Founder: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
Description: Core chatbot logic with OpenAI integration
"""

import openai
import os
import logging
import json
import re
from datetime import datetime
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

class ChatbotCore:
    def __init__(self):
        self.openai_api_key = os.getenv('OPENAI_API_KEY')
        self.conversation_history = {}
        self.max_history_length = 10
        self.default_responses = self._load_default_responses()
        
        # Chatbot personality and capabilities
        self.system_prompt = """You are a helpful, friendly, and intelligent multi-language chatbot assistant. 
        You can communicate in multiple languages and help users with various tasks.
        Always be polite, respectful, and provide accurate information.
        If you don't know something, admit it honestly.
        Adapt your communication style to be culturally appropriate."""
        
        self.capabilities = [
            "Answering questions",
            "Providing information",
            "Translation assistance",
            "Cultural guidance",
            "General conversation",
            "Help with various topics"
        ]
    
    def generate_response(self, message: str, user_id: str = 'default') -> str:
        """
        Generate response to user message
        """
        try:
            # Initialize conversation history for new user
            if user_id not in self.conversation_history:
                self.conversation_history[user_id] = []
            
            # Add user message to history
            self.conversation_history[user_id].append({
                'role': 'user',
                'content': message,
                'timestamp': datetime.now().isoformat()
            })
            
            # Try OpenAI first
            if self.openai_api_key:
                response = self._generate_openai_response(user_id)
                if response:
                    return response
            
            # Fallback to rule-based responses
            response = self._generate_rule_based_response(message)
            
            # Add response to history
            self.conversation_history[user_id].append({
                'role': 'assistant',
                'content': response,
                'timestamp': datetime.now().isoformat()
            })
            
            # Trim history if too long
            if len(self.conversation_history[user_id]) > self.max_history_length * 2:
                self.conversation_history[user_id] = self.conversation_history[user_id][-self.max_history_length * 2:]
            
            return response
            
        except Exception as e:
            logger.error(f"Response generation error: {str(e)}")
            return self._get_fallback_response()
    
    def _generate_openai_response(self, user_id: str) -> Optional[str]:
        """Generate response using OpenAI"""
        try:
            messages = [
                {"role": "system", "content": self.system_prompt}
            ]
            
            # Add conversation history
            for msg in self.conversation_history[user_id][-self.max_history_length:]:
                messages.append({
                    "role": msg['role'],
                    "content": msg['content']
                })
            
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=messages,
                max_tokens=500,
                temperature=0.7,
                top_p=1,
                frequency_penalty=0,
                presence_penalty=0
            )
            
            return response.choices[0].message.content.strip()
            
        except Exception as e:
            logger.error(f"OpenAI response error: {str(e)}")
            return None
    
    def _generate_rule_based_response(self, message: str) -> str:
        """Generate response using rule-based approach"""
        message_lower = message.lower().strip()
        
        # Check for greetings
        greetings = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening']
        if any(greeting in message_lower for greeting in greetings):
            return self._get_greeting_response()
        
        # Check for questions about capabilities
        capability_keywords = ['what can you do', 'help me with', 'your capabilities', 'what are you']
        if any(keyword in message_lower for keyword in capability_keywords):
            return self._get_capabilities_response()
        
        # Check for questions about identity
        identity_keywords = ['who are you', 'what are you', 'what is your name']
        if any(keyword in message_lower for keyword in identity_keywords):
            return self._get_identity_response()
        
        # Check for thank you
        thanks_keywords = ['thank', 'thanks', 'appreciate', 'grateful']
        if any(keyword in message_lower for keyword in thanks_keywords):
            return self._get_thanks_response()
        
        # Check for goodbye
        goodbye_keywords = ['goodbye', 'bye', 'see you', 'farewell']
        if any(keyword in message_lower for keyword in goodbye_keywords):
            return self._get_goodbye_response()
        
        # Check for help requests
        help_keywords = ['help', 'assist', 'support', 'guidance']
        if any(keyword in message_lower for keyword in help_keywords):
            return self._get_help_response()
        
        # Default response
        return self._get_default_response()
    
    def _get_greeting_response(self) -> str:
        """Get greeting response"""
        import random
        responses = [
            "Hello! How can I assist you today?",
            "Hi there! I'm here to help. What would you like to know?",
            "Greetings! How may I help you today?",
            "Good day! I'm ready to assist you with any questions."
        ]
        return random.choice(responses)
    
    def _get_capabilities_response(self) -> str:
        """Get capabilities response"""
        capabilities_text = ", ".join(self.capabilities[:-1]) + f", and {self.capabilities[-1]}"
        return f"I'm a multi-language chatbot that can help you with {capabilities_text}. I can communicate in multiple languages and adapt to different cultural contexts. What would you like help with?"
    
    def _get_identity_response(self) -> str:
        """Get identity response"""
        return "I'm an advanced multi-language chatbot created by RSK World. I can communicate in multiple languages, provide information, and assist with various tasks while being culturally sensitive. I'm here to help you!"
    
    def _get_thanks_response(self) -> str:
        """Get thanks response"""
        import random
        responses = [
            "You're welcome! I'm happy to help.",
            "My pleasure! Is there anything else I can assist you with?",
            "You're very welcome! Feel free to ask if you need more help.",
            "It's my pleasure to assist you! What else can I help with?"
        ]
        return random.choice(responses)
    
    def _get_goodbye_response(self) -> str:
        """Get goodbye response"""
        import random
        responses = [
            "Goodbye! Have a wonderful day!",
            "Farewell! It was great talking with you.",
            "See you later! Don't hesitate to come back if you need help.",
            "Bye! Take care and have a great day!"
        ]
        return random.choice(responses)
    
    def _get_help_response(self) -> str:
        """Get help response"""
        return "I'm here to help! You can ask me questions, request information, seek translation assistance, or simply have a conversation. I can communicate in multiple languages and adapt to your cultural context. What specific help do you need?"
    
    def _get_default_response(self) -> str:
        """Get default response"""
        import random
        responses = [
            "That's interesting! Could you tell me more about that?",
            "I understand. How can I help you with this topic?",
            "Thank you for sharing that. What would you like to know or discuss?",
            "I see. Is there something specific you'd like me to help you with regarding this?"
        ]
        return random.choice(responses)
    
    def _get_fallback_response(self) -> str:
        """Get fallback response for errors"""
        return "I apologize, but I'm experiencing some technical difficulties. Please try again in a moment. If the problem persists, feel free to rephrase your question."
    
    def _load_default_responses(self) -> Dict:
        """Load default responses from configuration"""
        return {
            'greetings': [
                "Hello! How can I help you today?",
                "Hi there! What can I do for you?",
                "Greetings! How may I assist you?"
            ],
            'capabilities': [
                "I can help you with various tasks including answering questions, providing information, translation, and cultural guidance.",
                "My capabilities include conversation, information retrieval, translation assistance, and culturally-appropriate communication."
            ],
            'errors': [
                "I apologize, but I encountered an error. Please try again.",
                "Something went wrong. Could you please rephrase your message?"
            ]
        }
    
    def clear_history(self, user_id: str = 'default'):
        """Clear conversation history for user"""
        if user_id in self.conversation_history:
            del self.conversation_history[user_id]
    
    def get_conversation_history(self, user_id: str = 'default') -> List[Dict]:
        """Get conversation history for user"""
        return self.conversation_history.get(user_id, [])
    
    def set_system_prompt(self, prompt: str):
        """Set custom system prompt"""
        self.system_prompt = prompt
    
    def add_capability(self, capability: str):
        """Add new capability"""
        if capability not in self.capabilities:
            self.capabilities.append(capability)
    
    def get_stats(self) -> Dict:
        """Get chatbot statistics"""
        return {
            'total_conversations': len(self.conversation_history),
            'total_messages': sum(len(history) for history in self.conversation_history.values()),
            'capabilities_count': len(self.capabilities),
            'openai_enabled': bool(self.openai_api_key)
        }
258 lines•10.8 KB
python
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer