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
RSK World
conversational-ai-bot
Conversational AI Bot - Python + NLP + Flask + Machine Learning + Chatbot + AI
conversational-ai-bot
  • __pycache__
  • static
  • templates
  • .gitignore577 B
  • ADVANCED_FEATURES.md5.7 KB
  • CHANGELOG.md2.2 KB
  • INSTALLATION.md1.8 KB
  • LICENSE1.2 KB
  • PROJECT_INFO.md2.8 KB
  • PROJECT_STATUS.md3.4 KB
  • QUICKSTART.md2.5 KB
  • README.md4.8 KB
  • __init__.py448 B
  • api_integrations.py6 KB
  • app.py4.2 KB
  • chatbot.py14.8 KB
  • config.py1.1 KB
  • context_manager.py5.8 KB
  • conversation_analytics.py5.9 KB
  • conversation_history.json413 B
  • conversation_history.py4.9 KB
  • entity_extractor.py6.6 KB
  • example_usage.py4.3 KB
  • intent_recognizer.py6.6 KB
  • language_support.py5 KB
  • main.py4.7 KB
  • requirements.txt311 B
  • response_templates.py7.2 KB
  • sentiment_analyzer.py5.6 KB
  • setup.py1.6 KB
  • test_chatbot.py5 KB
  • validate_project.py4.1 KB
.env.examplecontext_manager.pyPROJECT_INFO.mdvalidate_project.py
context_manager.py
Raw Download
Find: Go to:
"""
Context Management Module
Manages conversation context for multi-turn dialogues.

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

from typing import Dict, List, Optional, Any
from datetime import datetime, timedelta
from config import MAX_CONTEXT_HISTORY, CONTEXT_TIMEOUT


class ContextManager:
    """
    Manages conversation context for maintaining state across multiple turns.
    """
    
    def __init__(self, session_id: str = "default"):
        """
        Initialize context manager.
        
        Args:
            session_id: Unique identifier for the conversation session
        """
        self.session_id = session_id
        self.context: Dict[str, Any] = {
            'user_name': None,
            'entities': {},
            'previous_intents': [],
            'conversation_history': [],
            'session_start': datetime.now(),
            'last_activity': datetime.now(),
        }
        self.max_history = MAX_CONTEXT_HISTORY
        self.timeout = CONTEXT_TIMEOUT
    
    def update_context(self, user_message: str, bot_response: str, 
                      intent: Optional[str] = None, entities: Optional[Dict] = None):
        """
        Update context with new conversation turn.
        
        Args:
            user_message: User's input message
            bot_response: Bot's response
            intent: Detected intent
            entities: Extracted entities
        """
        # Update last activity time
        self.context['last_activity'] = datetime.now()
        
        # Add to conversation history
        self.context['conversation_history'].append({
            'user_message': user_message,
            'bot_response': bot_response,
            'timestamp': datetime.now().isoformat(),
            'intent': intent,
            'entities': entities
        })
        
        # Limit history size
        if len(self.context['conversation_history']) > self.max_history:
            self.context['conversation_history'] = \
                self.context['conversation_history'][-self.max_history:]
        
        # Update entities
        if entities:
            self.context['entities'].update(entities)
        
        # Track previous intents
        if intent:
            self.context['previous_intents'].append(intent)
            if len(self.context['previous_intents']) > 5:
                self.context['previous_intents'] = \
                    self.context['previous_intents'][-5:]
        
        # Extract and store user name if mentioned
        if entities and 'PERSON' in entities:
            names = entities['PERSON']
            if names:
                self.context['user_name'] = names[0]
    
    def get_context(self) -> Dict[str, Any]:
        """
        Get current context.
        
        Returns:
            Current context dictionary
        """
        return self.context.copy()
    
    def get_user_name(self) -> Optional[str]:
        """
        Get stored user name from context.
        
        Returns:
            User name if available, None otherwise
        """
        return self.context.get('user_name')
    
    def get_entities(self) -> Dict[str, Any]:
        """
        Get stored entities from context.
        
        Returns:
            Dictionary of stored entities
        """
        return self.context.get('entities', {}).copy()
    
    def get_recent_history(self, count: int = 3) -> List[Dict]:
        """
        Get recent conversation history.
        
        Args:
            count: Number of recent messages to retrieve
            
        Returns:
            List of recent conversation entries
        """
        history = self.context.get('conversation_history', [])
        return history[-count:] if history else []
    
    def get_previous_intent(self) -> Optional[str]:
        """
        Get the most recent intent.
        
        Returns:
            Most recent intent if available, None otherwise
        """
        intents = self.context.get('previous_intents', [])
        return intents[-1] if intents else None
    
    def clear_context(self):
        """Clear all context data."""
        self.context = {
            'user_name': None,
            'entities': {},
            'previous_intents': [],
            'conversation_history': [],
            'session_start': datetime.now(),
            'last_activity': datetime.now(),
        }
    
    def is_context_expired(self) -> bool:
        """
        Check if context has expired based on timeout.
        
        Returns:
            True if context has expired, False otherwise
        """
        last_activity = self.context.get('last_activity')
        if not last_activity:
            return False
        
        if isinstance(last_activity, str):
            last_activity = datetime.fromisoformat(last_activity)
        
        elapsed = (datetime.now() - last_activity).total_seconds()
        return elapsed > self.timeout
    
    def get_context_summary(self) -> str:
        """
        Get a human-readable summary of the current context.
        
        Returns:
            Context summary string
        """
        summary_parts = []
        
        if self.context.get('user_name'):
            summary_parts.append(f"User name: {self.context['user_name']}")
        
        if self.context.get('entities'):
            summary_parts.append(f"Entities: {len(self.context['entities'])} stored")
        
        history_count = len(self.context.get('conversation_history', []))
        summary_parts.append(f"Conversation turns: {history_count}")
        
        return ", ".join(summary_parts) if summary_parts else "No context available"

184 lines•5.8 KB
python
PROJECT_INFO.md
Raw Download

PROJECT_INFO.md

# Project Information

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

## Project Overview

**Conversational AI Bot** is an advanced conversational chatbot with context management and multi-turn dialogue support.

## Project Details

- **ID**: 3
- **Title**: Conversational AI Bot
- **Category**: Conversational AI
- **Difficulty**: Intermediate
- **Version**: 1.0.0

## Description

This chatbot project implements advanced conversational AI with context awareness, multi-turn dialogue handling, and intelligent response generation. Features include conversation history, context management, and natural language understanding.

## Features

- ✅ Context-aware conversations
- ✅ Multi-turn dialogue support
- ✅ Intent recognition
- ✅ Entity extraction
- ✅ Conversation history

## Technologies

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

## Project Structure

```
conversational-ai-bot/
├── main.py # Main entry point
├── 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
├── config.py # Configuration settings
├── example_usage.py # Usage examples
├── test_chatbot.py # Test suite
├── setup.py # Installation script
├── requirements.txt # Python dependencies
├── README.md # Main documentation
├── QUICKSTART.md # Quick start guide
├── INSTALLATION.md # Installation guide
├── LICENSE # License file
└── .gitignore # Git ignore file
```

## Installation

See [INSTALLATION.md](INSTALLATION.md) for detailed installation instructions.

## Quick Start

See [QUICKSTART.md](QUICKSTART.md) for quick start guide.

## Usage

### Interactive Mode

```bash
python main.py
```

### Programmatic Usage

```python
from chatbot import ConversationalAIBot

bot = ConversationalAIBot()
response = bot.chat("Hello, my name is John")
print(response)
```

## Developer Information

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

## License

MIT License - See [LICENSE](LICENSE) for details.

## Support

For support, questions, or issues:
- Visit: https://rskworld.in
- Email: help@rskworld.in
- Phone: +91 93305 39277

---

© 2026 RSK World. All rights reserved.

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