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
conversation_history.py
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

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