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
conversational-ai-bot
/
__pycache__
RSK World
conversational-ai-bot
Conversational AI Bot - Python + NLP + Flask + Machine Learning + Chatbot + AI
__pycache__
  • api_integrations.cpython-313.pyc5.4 KB
  • app.cpython-313.pyc5.7 KB
  • chatbot.cpython-313.pyc18.1 KB
  • config.cpython-313.pyc1.1 KB
  • context_manager.cpython-313.pyc7.1 KB
  • conversation_analytics.cpython-313.pyc6.6 KB
  • conversation_history.cpython-313.pyc6.5 KB
  • entity_extractor.cpython-313.pyc7 KB
  • intent_recognizer.cpython-313.pyc5.8 KB
  • language_support.cpython-313.pyc5.2 KB
  • response_templates.cpython-313.pyc6.6 KB
  • sentiment_analyzer.cpython-313.pyc5.4 KB
chatbot.pyvalidate_project.pylanguage_detection.pyapp.cpython-313.pycREADME.mdconfig.cpython-313.pyc
chatbot.py
Raw Download
Find: Go to:
"""
Conversational AI Bot - Main Chatbot Class
Advanced conversational chatbot with context management and multi-turn dialogue support.

Developer: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026
"""

from typing import Optional, Dict
import re
from datetime import datetime
import uuid

from context_manager import ContextManager
from intent_recognizer import IntentRecognizer
from entity_extractor import EntityExtractor
from conversation_history import ConversationHistory
from sentiment_analyzer import SentimentAnalyzer
from language_support import LanguageSupport
from api_integrations import APIIntegrations
from conversation_analytics import ConversationAnalytics
from response_templates import ResponseTemplates
from config import (
    BOT_NAME, DEFAULT_RESPONSE, INTENT_CONFIDENCE_THRESHOLD,
    DEVELOPER_NAME, DEVELOPER_WEBSITE, DEVELOPER_EMAIL, DEVELOPER_PHONE, YEAR
)


class ConversationalAIBot:
    """
    Main conversational AI bot class with context awareness and multi-turn dialogue support.
    """
    
    def __init__(self, session_id: Optional[str] = None):
        """
        Initialize the conversational AI bot.
        
        Args:
            session_id: Optional session identifier for conversation tracking
        """
        self.session_id = session_id or str(uuid.uuid4())
        self.context_manager = ContextManager(self.session_id)
        self.intent_recognizer = IntentRecognizer()
        self.entity_extractor = EntityExtractor()
        self.conversation_history = ConversationHistory(self.session_id)
        
        # Advanced features
        self.sentiment_analyzer = SentimentAnalyzer()
        self.language_support = LanguageSupport()
        self.api_integrations = APIIntegrations()
        self.analytics = ConversationAnalytics()
        self.response_templates = ResponseTemplates()
        
        # Initialize analytics
        self.analytics.start_session(self.session_id)
        
        # Initialize bot with greeting
        self._initialize_bot()
    
    def _initialize_bot(self):
        """Initialize the bot with default settings."""
        print(f"Initializing {BOT_NAME}...")
        print(f"Session ID: {self.session_id}")
        print(f"Developer: {DEVELOPER_NAME} ({DEVELOPER_WEBSITE})")
        print("-" * 50)
    
    def chat(self, user_message: str) -> str:
        """
        Process user message and generate response.
        
        Args:
            user_message: User's input message
            
        Returns:
            Bot's response
        """
        if not user_message or not user_message.strip():
            return "I didn't receive any message. Please try again."
        
        # Check if context has expired
        if self.context_manager.is_context_expired():
            self.context_manager.clear_context()
            self.conversation_history.clear_history()
        
        # Detect language
        detected_language = self.language_support.detect_language(user_message)
        self.language_support.set_language(detected_language)
        
        # Analyze sentiment
        sentiment_analysis = self.sentiment_analyzer.analyze(user_message)
        sentiment = sentiment_analysis['sentiment']
        
        # Recognize intent
        intent, confidence = self.intent_recognizer.recognize(user_message)
        
        # Extract entities
        entities = self.entity_extractor.extract(user_message)
        
        # Generate response based on intent and context
        response = self._generate_response(user_message, intent, confidence, entities, sentiment_analysis)
        
        # Update context
        self.context_manager.update_context(user_message, response, intent, entities)
        
        # Save to conversation history
        self.conversation_history.add_message(user_message, response, intent, entities)
        
        # Track analytics
        self.analytics.track_message(
            self.session_id, intent, entities, sentiment, detected_language
        )
        
        return response
    
    def _generate_response(self, user_message: str, intent: str, 
                          confidence: float, entities: Dict, sentiment_analysis: Dict = None) -> str:
        """
        Generate response based on intent, context, and entities.
        
        Args:
            user_message: User's message
            intent: Detected intent
            confidence: Intent confidence score
            entities: Extracted entities
            
        Returns:
            Generated response
        """
        user_message_lower = user_message.lower()
        
        # Handle low confidence intents
        if confidence < INTENT_CONFIDENCE_THRESHOLD:
            return self._handle_unknown_intent(user_message)
        
        # Check for API-related queries
        if 'joke' in user_message_lower or 'tell me a joke' in user_message_lower:
            joke_result = self.api_integrations.get_joke()
            if joke_result.get('success'):
                joke = joke_result.get('joke', {})
                return f"{joke.get('setup', '')}\n{joke.get('punchline', '')}"
        
        if 'quote' in user_message_lower or 'inspiration' in user_message_lower:
            quote_result = self.api_integrations.get_quote()
            if quote_result.get('success'):
                quote = quote_result.get('quote', {})
                return f'"{quote.get("text", "")}" - {quote.get("author", "")}'
        
        # Check for calculation requests
        if any(op in user_message for op in ['+', '-', '*', '/', '=']):
            calc_match = self._extract_calculation(user_message)
            if calc_match:
                calc_result = self.api_integrations.calculate(calc_match)
                if calc_result.get('success'):
                    return f"The answer is {calc_result.get('result')}"
        
        # Handle specific intents
        if intent == 'greeting':
            return self._handle_greeting(entities)
        
        elif intent == 'goodbye':
            return self._handle_goodbye()
        
        elif intent == 'name_introduction':
            return self._handle_name_introduction(entities)
        
        elif intent == 'name_query':
            return self._handle_name_query()
        
        elif intent == 'question':
            return self._handle_question(user_message, entities)
        
        elif intent == 'help':
            return self._handle_help()
        
        elif intent == 'weather':
            return self._handle_weather(entities)
        
        elif intent == 'time':
            return self._handle_time()
        
        elif intent == 'date':
            return self._handle_date()
        
        elif intent == 'compliment':
            return self._handle_compliment()
        
        else:
            return self._handle_unknown_intent(user_message, sentiment_analysis)
    
    def _handle_greeting(self, entities: Dict) -> str:
        """Handle greeting intent."""
        user_name = self.context_manager.get_user_name()
        
        if user_name:
            return self.response_templates.get_response('greeting_with_name', name=user_name)
        else:
            return self.response_templates.get_response('greeting')
    
    def _handle_goodbye(self) -> str:
        """Handle goodbye intent."""
        user_name = self.context_manager.get_user_name()
        
        if user_name:
            return self.response_templates.get_response('goodbye_with_name', name=user_name)
        else:
            return self.response_templates.get_response('goodbye')
    
    def _handle_name_introduction(self, entities: Dict) -> str:
        """Handle name introduction intent."""
        if 'PERSON' in entities and entities['PERSON']:
            name = entities['PERSON'][0]
            return self.response_templates.get_response('name_introduction', name=name)
        else:
            return self.response_templates.get_response('name_not_found')
    
    def _handle_name_query(self) -> str:
        """Handle name query intent."""
        user_name = self.context_manager.get_user_name()
        
        if user_name:
            return self.response_templates.get_response('name_query', name=user_name)
        else:
            return self.response_templates.get_response('name_not_found')
    
    def _handle_question(self, user_message: str, entities: Dict) -> str:
        """Handle question intent."""
        user_message_lower = user_message.lower()
        
        # Check for specific question types
        if 'what can you do' in user_message_lower or 'what do you do' in user_message_lower:
            return self._handle_help()
        
        if 'how are you' in user_message_lower:
            return "I'm doing well, thank you for asking! I'm here to help you with conversations. How can I assist you?"
        
        if 'who are you' in user_message_lower or 'what are you' in user_message_lower:
            return f"I'm {BOT_NAME}, an advanced conversational AI bot. I can help you with various tasks and have natural conversations. I'm developed by {DEVELOPER_NAME}."
        
        # Generic question response
        return "That's an interesting question! I'm still learning, but I'll do my best to help. Could you provide more details?"
    
    def _handle_help(self) -> str:
        """Handle help intent."""
        return self.response_templates.get_response('help')
    
    def _handle_weather(self, entities: Dict) -> str:
        """Handle weather intent."""
        location = None
        if 'LOCATION' in entities and entities['LOCATION']:
            location = entities['LOCATION'][0]
        
        if location:
            weather_data = self.api_integrations.get_weather(location)
            if weather_data.get('success'):
                return f"Weather for {location}: {weather_data.get('temperature')}, {weather_data.get('condition')}"
            return self.response_templates.get_response('weather', location=location)
        else:
            return "I'd be happy to help with weather information! Could you tell me which location you're interested in?"
    
    def _handle_time(self) -> str:
        """Handle time query intent."""
        current_time = datetime.now().strftime("%I:%M %p")
        return self.response_templates.get_response('time', time=current_time)
    
    def _handle_date(self) -> str:
        """Handle date query intent."""
        current_date = datetime.now().strftime("%B %d, %Y")
        return self.response_templates.get_response('date', date=current_date)
    
    def _handle_compliment(self) -> str:
        """Handle compliment intent."""
        return self.response_templates.get_response('compliment')
    
    def _handle_unknown_intent(self, user_message: str, sentiment_analysis: Dict = None) -> str:
        """Handle unknown or low-confidence intents."""
        # Try to use context to provide a better response
        recent_history = self.context_manager.get_recent_history(1)
        
        # Adjust response based on sentiment
        if sentiment_analysis and sentiment_analysis.get('sentiment') == 'negative':
            return "I sense you might be frustrated. I'm here to help! Could you rephrase your question or tell me what you need?"
        
        if recent_history:
            # Reference previous conversation
            return self.response_templates.get_response('unknown')
        else:
            return self.response_templates.get_response('unknown')
    
    def _extract_calculation(self, text: str) -> Optional[str]:
        """Extract mathematical expression from text."""
        # Simple pattern for basic calculations
        pattern = r'(\d+(?:\.\d+)?)\s*([+\-*/])\s*(\d+(?:\.\d+)?)'
        match = re.search(pattern, text)
        if match:
            return f"{match.group(1)}{match.group(2)}{match.group(3)}"
        return None
    
    def get_context_summary(self) -> str:
        """
        Get a summary of the current conversation context.
        
        Returns:
            Context summary string
        """
        return self.context_manager.get_context_summary()
    
    def get_conversation_history(self, limit: Optional[int] = None):
        """
        Get conversation history.
        
        Args:
            limit: Maximum number of entries to return
            
        Returns:
            List of conversation entries
        """
        return self.conversation_history.get_history(limit)
    
    def clear_session(self):
        """Clear current session context and history."""
        self.context_manager.clear_context()
        self.conversation_history.clear_history()
        self.analytics.end_session(self.session_id)
        print("Session cleared. Starting fresh conversation.")
    
    def get_analytics(self) -> Dict:
        """
        Get conversation analytics.
        
        Returns:
            Dictionary with analytics data
        """
        return self.analytics.get_metrics()
    
    def get_analytics_summary(self) -> str:
        """
        Get human-readable analytics summary.
        
        Returns:
            Formatted analytics summary
        """
        return self.analytics.get_summary()
    
    def get_sentiment_analysis(self, text: str) -> Dict:
        """
        Analyze sentiment of text.
        
        Args:
            text: Text to analyze
            
        Returns:
            Sentiment analysis results
        """
        return self.sentiment_analyzer.analyze(text)
    
    def set_language(self, language_code: str) -> bool:
        """
        Set conversation language.
        
        Args:
            language_code: Language code (e.g., 'en', 'es', 'hi')
            
        Returns:
            True if language is supported, False otherwise
        """
        return self.language_support.set_language(language_code)
    
    def get_current_language(self) -> str:
        """Get current language code."""
        return self.language_support.get_language()


if __name__ == "__main__":
    # Example usage
    bot = ConversationalAIBot()
    
    print("\n" + "="*50)
    print("Conversational AI Bot - Interactive Mode")
    print("Type 'quit' or 'exit' to end the conversation")
    print("="*50 + "\n")
    
    while True:
        user_input = input("You: ").strip()
        
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print(f"\nBot: {bot.chat(user_input)}")
            break
        
        if user_input:
            response = bot.chat(user_input)
            print(f"Bot: {response}\n")

396 lines•14.8 KB
python
validate_project.py
Raw Download
Find: Go to:
"""
Project Validation Script
Validates all project files and checks for errors.

Developer: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026
"""

import os
import sys
import importlib.util
from pathlib import Path


def check_file_exists(filepath):
    """Check if file exists."""
    if os.path.exists(filepath):
        print(f"[OK] {filepath}")
        return True
    else:
        print(f"[MISSING] {filepath}")
        return False


def check_import(module_name):
    """Check if module can be imported."""
    try:
        spec = importlib.util.find_spec(module_name)
        if spec is None:
            print(f"[FAIL] Cannot import {module_name}")
            return False
        print(f"[OK] {module_name} - Import successful")
        return True
    except Exception as e:
        print(f"[FAIL] {module_name} - Import failed: {e}")
        return False


def check_syntax(filepath):
    """Check Python file syntax."""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            compile(f.read(), filepath, 'exec')
        print(f"[OK] {filepath} - Syntax OK")
        return True
    except SyntaxError as e:
        print(f"[ERROR] {filepath} - Syntax Error: {e}")
        return False
    except Exception as e:
        print(f"[ERROR] {filepath} - Error: {e}")
        return False


def main():
    """Main validation function."""
    print("=" * 60)
    print("Conversational AI Bot - Project Validation")
    print("Developer: RSK World (https://rskworld.in)")
    print("=" * 60)
    print()
    
    errors = []
    
    # Required Python files
    print("Checking Required Files:")
    print("-" * 60)
    required_files = [
        'chatbot.py',
        'main.py',
        'app.py',
        'config.py',
        'context_manager.py',
        'intent_recognizer.py',
        'entity_extractor.py',
        'conversation_history.py',
        'sentiment_analyzer.py',
        'language_support.py',
        'api_integrations.py',
        'conversation_analytics.py',
        'response_templates.py',
        'requirements.txt',
        'README.md',
        'setup.py',
        '__init__.py'
    ]
    
    for file in required_files:
        if not check_file_exists(file):
            errors.append(f"Missing file: {file}")
    
    print()
    
    # Check directories
    print("Checking Required Directories:")
    print("-" * 60)
    required_dirs = ['templates', 'static']
    for dir_name in required_dirs:
        if os.path.exists(dir_name) and os.path.isdir(dir_name):
            print(f"[OK] {dir_name}/")
        else:
            print(f"[MISSING] {dir_name}/")
            errors.append(f"Missing directory: {dir_name}")
    
    print()
    
    # Check Python syntax
    print("Checking Python Syntax:")
    print("-" * 60)
    python_files = [f for f in required_files if f.endswith('.py')]
    for file in python_files:
        if os.path.exists(file):
            if not check_syntax(file):
                errors.append(f"Syntax error in: {file}")
    
    print()
    
    # Check imports
    print("Checking Module Imports:")
    print("-" * 60)
    modules_to_check = [
        'chatbot',
        'context_manager',
        'intent_recognizer',
        'entity_extractor',
        'conversation_history',
        'sentiment_analyzer',
        'language_support',
        'api_integrations',
        'conversation_analytics',
        'response_templates',
        'config'
    ]
    
    for module in modules_to_check:
        if not check_import(module):
            errors.append(f"Import error: {module}")
    
    print()
    
    # Summary
    print("=" * 60)
    if errors:
        print(f"[FAILED] Validation FAILED - {len(errors)} error(s) found:")
        for error in errors:
            print(f"  - {error}")
        return False
    else:
        print("[PASSED] Validation PASSED - All checks successful!")
        return True
    print("=" * 60)


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)

160 lines•4.1 KB
python
app.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
README.md
Raw Download

README.md

# Conversational AI Bot

<!--
Project: Conversational AI Bot
Developer: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026
-->

Advanced conversational chatbot with context management and multi-turn dialogue support.

## Features

### Core Features
- **Context-aware conversations**: Maintains context across multiple turns
- **Multi-turn dialogue support**: Handles complex conversation flows
- **Intent recognition**: Identifies user intentions from natural language
- **Entity extraction**: Extracts important information from user messages
- **Conversation history**: Stores and retrieves past conversations

### Advanced Features
- **Sentiment Analysis**: Analyzes user sentiment to provide better responses
- **Multi-language Support**: Detects and supports multiple languages (English, Spanish, French, German, Hindi, Chinese, Japanese, Arabic)
- **API Integrations**: Weather, news, jokes, quotes, and calculations
- **Conversation Analytics**: Tracks metrics, intent distribution, and session statistics
- **Response Templates**: Template-based response system for consistent interactions
- **Web Interface**: Beautiful Flask-based web interface for easy interaction
- **Real-time Analytics**: Track conversation patterns and user engagement

## Technologies

- Python 3.8+
- Natural Language Processing (NLP)
- Machine Learning
- Rasa (optional integration)
- Dialogflow (optional integration)

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd conversational-ai-bot
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Run the chatbot:
```bash
python main.py
```

## Usage

### Basic Usage

```python
from chatbot import ConversationalAIBot

bot = ConversationalAIBot()
response = bot.chat("Hello, how are you?")
print(response)
```

### Advanced Usage with Context

```python
from chatbot import ConversationalAIBot

bot = ConversationalAIBot()
bot.chat("My name is John")
response = bot.chat("What's my name?")
print(response) # The bot remembers your name
```

### Using Advanced Features

```python
from chatbot import ConversationalAIBot

bot = ConversationalAIBot()

# Sentiment Analysis
sentiment = bot.get_sentiment_analysis("I'm feeling great today!")
print(sentiment['sentiment']) # 'positive'

# Language Support
bot.set_language('es') # Set to Spanish
current_lang = bot.get_current_language()

# Analytics
analytics = bot.get_analytics()
summary = bot.get_analytics_summary()
print(summary)

# API Integrations
response = bot.chat("Tell me a joke")
response = bot.chat("What's 25 + 17?")
response = bot.chat("Weather in New York")
```

### Web Interface

Start the web interface:

```bash
python app.py
```

Then open your browser to `http://localhost:5000`

## Project Structure

```
conversational-ai-bot/
├── main.py # Main CLI entry point
├── app.py # Flask web interface
├── chatbot.py # Core chatbot class
├── context_manager.py # Context management
├── intent_recognizer.py # Intent recognition
├── entity_extractor.py # Entity extraction
├── conversation_history.py # Conversation history management
├── sentiment_analyzer.py # Sentiment analysis
├── language_support.py # Multi-language support
├── api_integrations.py # External API integrations
├── conversation_analytics.py # Analytics and metrics
├── response_templates.py # Response templates
├── config.py # Configuration settings
├── example_usage.py # Usage examples
├── test_chatbot.py # Test suite
├── templates/ # Web interface templates
│ └── index.html # Main web interface
├── requirements.txt # Python dependencies
└── README.md # This file
```

## Features

### Context Management
The bot maintains conversation context, allowing it to reference previous messages and maintain coherent multi-turn dialogues.

### Intent Recognition
Uses pattern matching and machine learning techniques to identify user intentions from natural language input.

### Entity Extraction
Extracts entities such as names, dates, locations, and other important information from user messages.

### Conversation History
Stores conversation history for each session, enabling the bot to reference past interactions.

## License

This project is provided by RSK World (https://rskworld.in) for educational and development purposes.

## Contact

- **Website**: https://rskworld.in
- **Email**: help@rskworld.in
- **Phone**: +91 93305 39277

---

© 2026 RSK World. All rights reserved.

config.cpython-313.pyc

This file cannot be displayed in the browser.

Download File
🚀 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