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
RELEASE_NOTES_v1.0.0.mdpersonas.pyconversation_history.pyrequirements.txtCHANGELOG.md
conversation_history.py
Raw Download
Find: Go to:
"""
Conversation History Management
Manages storage and retrieval of conversation history for the chatbot.

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

import json
import os
from datetime import datetime
from typing import List, Dict, Optional
from config import HISTORY_FILE, MAX_HISTORY_ENTRIES, ENABLE_HISTORY


class ConversationHistory:
    """
    Manages conversation history storage and retrieval.
    """
    
    def __init__(self, session_id: str = "default"):
        """
        Initialize conversation history manager.
        
        Args:
            session_id: Unique identifier for the conversation session
        """
        self.session_id = session_id
        self.history_file = HISTORY_FILE
        self.history: List[Dict] = []
        self.enabled = ENABLE_HISTORY
        
        if self.enabled:
            self.load_history()
    
    def add_message(self, user_message: str, bot_response: str, 
                   intent: Optional[str] = None, entities: Optional[Dict] = None):
        """
        Add a message exchange to the conversation history.
        
        Args:
            user_message: The user's input message
            bot_response: The bot's response
            intent: Detected intent (optional)
            entities: Extracted entities (optional)
        """
        if not self.enabled:
            return
        
        entry = {
            'timestamp': datetime.now().isoformat(),
            'session_id': self.session_id,
            'user_message': user_message,
            'bot_response': bot_response,
            'intent': intent,
            'entities': entities
        }
        
        self.history.append(entry)
        
        # Limit history size
        if len(self.history) > MAX_HISTORY_ENTRIES:
            self.history = self.history[-MAX_HISTORY_ENTRIES:]
        
        self.save_history()
    
    def get_history(self, limit: Optional[int] = None) -> List[Dict]:
        """
        Get conversation history.
        
        Args:
            limit: Maximum number of entries to return
            
        Returns:
            List of conversation entries
        """
        if limit:
            return self.history[-limit:]
        return self.history.copy()
    
    def get_recent_messages(self, count: int = 5) -> List[Dict]:
        """
        Get recent conversation messages.
        
        Args:
            count: Number of recent messages to retrieve
            
        Returns:
            List of recent conversation entries
        """
        return self.history[-count:] if self.history else []
    
    def clear_history(self):
        """Clear conversation history."""
        self.history = []
        if os.path.exists(self.history_file):
            os.remove(self.history_file)
    
    def save_history(self):
        """Save conversation history to file."""
        if not self.enabled:
            return
        
        try:
            # Load existing history from file
            all_history = []
            if os.path.exists(self.history_file):
                with open(self.history_file, 'r', encoding='utf-8') as f:
                    all_history = json.load(f)
            
            # Update or add session history
            session_found = False
            for i, session in enumerate(all_history):
                if session.get('session_id') == self.session_id:
                    all_history[i] = {
                        'session_id': self.session_id,
                        'messages': self.history
                    }
                    session_found = True
                    break
            
            if not session_found:
                all_history.append({
                    'session_id': self.session_id,
                    'messages': self.history
                })
            
            # Save to file
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(all_history, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"Error saving history: {e}")
    
    def load_history(self):
        """Load conversation history from file."""
        if not self.enabled:
            return
        
        try:
            if os.path.exists(self.history_file):
                with open(self.history_file, 'r', encoding='utf-8') as f:
                    all_history = json.load(f)
                    
                # Find this session's history
                for session in all_history:
                    if session.get('session_id') == self.session_id:
                        self.history = session.get('messages', [])
                        break
        except Exception as e:
            print(f"Error loading history: {e}")
            self.history = []

156 lines•4.9 KB
python
requirements.txt
Raw Download
Find: Go to:
# Conversational AI Bot - Requirements
# Developer: RSK World (https://rskworld.in)
# Email: help@rskworld.in
# Phone: +91 93305 39277
# Year: 2026

numpy>=1.21.0
scikit-learn>=1.0.0
nltk>=3.6
spacy>=3.4.0
python-dateutil>=2.8.2
colorama>=0.4.4
setuptools>=65.0.0
flask>=2.3.0
requests>=2.28.0

17 lines•311 B
text
CHANGELOG.md
Raw Download

CHANGELOG.md

# Changelog

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

All notable changes to the Conversational AI Bot project will be documented in this file.

## [1.0.0] - 2026-01-01

### Added
- Initial release of Conversational AI Bot
- Core chatbot functionality with context management
- Multi-turn dialogue support
- Intent recognition system
- Entity extraction (names, dates, locations, emails, phones)
- Conversation history management
- CLI interface with colorama support

### Advanced Features Added
- **Sentiment Analysis**: Analyze user sentiment for better responses
- **Multi-Language Support**: Support for 8 languages (English, Spanish, French, German, Hindi, Chinese, Japanese, Arabic)
- **API Integrations**: Weather, jokes, quotes, calculations, and news
- **Conversation Analytics**: Track metrics, intents, entities, and session statistics
- **Response Templates**: Template-based response system for consistent interactions
- **Web Interface**: Beautiful Flask-based web interface
- **Project Validation**: Validation script to check project integrity

### Files Created
- Core modules: `chatbot.py`, `context_manager.py`, `intent_recognizer.py`, `entity_extractor.py`, `conversation_history.py`
- Advanced modules: `sentiment_analyzer.py`, `language_support.py`, `api_integrations.py`, `conversation_analytics.py`, `response_templates.py`
- Interface: `main.py` (CLI), `app.py` (Web), `templates/index.html`
- Documentation: `README.md`, `QUICKSTART.md`, `INSTALLATION.md`, `ADVANCED_FEATURES.md`, `PROJECT_INFO.md`
- Configuration: `config.py`, `requirements.txt`, `setup.py`, `.gitignore`
- Utilities: `example_usage.py`, `test_chatbot.py`, `validate_project.py`
- Package: `__init__.py`

### Documentation
- Comprehensive README with usage examples
- Quick start guide
- Installation instructions
- Advanced features documentation
- Project information

### Developer Information
All files include developer information:
- Developer: RSK World
- Website: https://rskworld.in
- Email: help@rskworld.in
- Phone: +91 93305 39277
- Year: 2026

---

© 2026 RSK World. All rights reserved.

🚀 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