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
test_chatbot.pyREADME.mdconfig.cpython-313.pycintent_recognizer.py
test_chatbot.py
Raw Download
Find: Go to:
"""
Test script for Conversational AI Bot
Developer: RSK World
Website: https://rskworld.in
Email: help@rskworld.in
Phone: +91 93305 39277
Year: 2026
"""

import unittest
from chatbot import ConversationalAIBot
from intent_recognizer import IntentRecognizer
from entity_extractor import EntityExtractor
from context_manager import ContextManager


class TestIntentRecognizer(unittest.TestCase):
    """Test intent recognition functionality."""
    
    def setUp(self):
        """Set up test fixtures."""
        self.recognizer = IntentRecognizer()
    
    def test_greeting_intent(self):
        """Test greeting intent recognition."""
        intent, confidence = self.recognizer.recognize("Hello")
        self.assertEqual(intent, "greeting")
        self.assertGreater(confidence, 0.5)
    
    def test_question_intent(self):
        """Test question intent recognition."""
        intent, confidence = self.recognizer.recognize("What is this?")
        self.assertEqual(intent, "question")
        self.assertGreater(confidence, 0.5)
    
    def test_name_introduction(self):
        """Test name introduction intent."""
        intent, confidence = self.recognizer.recognize("My name is John")
        self.assertEqual(intent, "name_introduction")
        self.assertGreater(confidence, 0.5)


class TestEntityExtractor(unittest.TestCase):
    """Test entity extraction functionality."""
    
    def setUp(self):
        """Set up test fixtures."""
        self.extractor = EntityExtractor()
    
    def test_person_extraction(self):
        """Test person name extraction."""
        entities = self.extractor.extract("My name is John Doe")
        self.assertIn("PERSON", entities)
        self.assertGreater(len(entities["PERSON"]), 0)
    
    def test_email_extraction(self):
        """Test email extraction."""
        entities = self.extractor.extract("My email is test@example.com")
        self.assertIn("EMAIL", entities)
        self.assertIn("test@example.com", entities["EMAIL"])


class TestContextManager(unittest.TestCase):
    """Test context management functionality."""
    
    def setUp(self):
        """Set up test fixtures."""
        self.context_manager = ContextManager("test_session")
    
    def test_context_update(self):
        """Test context update."""
        self.context_manager.update_context(
            "My name is Alice",
            "Nice to meet you, Alice!",
            "name_introduction",
            {"PERSON": ["Alice"]}
        )
        
        self.assertEqual(self.context_manager.get_user_name(), "Alice")
    
    def test_context_persistence(self):
        """Test context persistence across updates."""
        self.context_manager.update_context(
            "Hello",
            "Hi there!",
            "greeting",
            {}
        )
        
        history = self.context_manager.get_recent_history(1)
        self.assertEqual(len(history), 1)
        self.assertEqual(history[0]["user_message"], "Hello")


class TestChatbot(unittest.TestCase):
    """Test main chatbot functionality."""
    
    def setUp(self):
        """Set up test fixtures."""
        self.bot = ConversationalAIBot("test_session")
    
    def test_basic_greeting(self):
        """Test basic greeting."""
        response = self.bot.chat("Hello")
        self.assertIsInstance(response, str)
        self.assertGreater(len(response), 0)
    
    def test_name_remembering(self):
        """Test name remembering functionality."""
        self.bot.chat("My name is Bob")
        response = self.bot.chat("What's my name?")
        self.assertIn("Bob", response)
    
    def test_context_awareness(self):
        """Test context awareness."""
        self.bot.chat("Hello")
        self.bot.chat("My name is Charlie")
        
        context_summary = self.bot.get_context_summary()
        self.assertIsInstance(context_summary, str)
        self.assertGreater(len(context_summary), 0)


def run_tests():
    """Run all tests."""
    print("=" * 60)
    print("Running Conversational AI Bot Tests")
    print("Developer: RSK World (https://rskworld.in)")
    print("=" * 60 + "\n")
    
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    
    # Add test classes
    suite.addTests(loader.loadTestsFromTestCase(TestIntentRecognizer))
    suite.addTests(loader.loadTestsFromTestCase(TestEntityExtractor))
    suite.addTests(loader.loadTestsFromTestCase(TestContextManager))
    suite.addTests(loader.loadTestsFromTestCase(TestChatbot))
    
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    print("\n" + "=" * 60)
    if result.wasSuccessful():
        print("All tests passed!")
    else:
        print(f"Tests completed with {len(result.failures)} failures and {len(result.errors)} errors")
    print("=" * 60)
    
    return result.wasSuccessful()


if __name__ == "__main__":
    run_tests()

156 lines•5 KB
python
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
intent_recognizer.py
Raw Download
Find: Go to:
"""
Intent Recognition Module
Recognizes user intentions from natural language input.

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

from typing import Dict, List, Tuple, Optional
from collections import Counter
import re


class IntentRecognizer:
    """
    Recognizes user intentions from natural language text.
    """
    
    def __init__(self):
        """Initialize the intent recognizer with predefined patterns."""
        # Intent patterns with keywords and confidence scores
        self.intent_patterns = {
            'greeting': {
                'keywords': ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 
                           'good evening', 'greetings', 'howdy'],
                'patterns': [
                    r'\b(hello|hi|hey|greetings)\b',
                    r'good\s+(morning|afternoon|evening)',
                ],
                'confidence': 0.9
            },
            'goodbye': {
                'keywords': ['bye', 'goodbye', 'see you', 'farewell', 'later', 
                           'take care', 'adios'],
                'patterns': [
                    r'\b(bye|goodbye|see you|farewell)\b',
                    r'take\s+care',
                ],
                'confidence': 0.9
            },
            'question': {
                'keywords': ['what', 'when', 'where', 'who', 'why', 'how', 'which', 
                           'can you', 'could you', 'would you'],
                'patterns': [
                    r'^(what|when|where|who|why|how|which)',
                    r'\?',
                    r'can\s+you|could\s+you|would\s+you',
                ],
                'confidence': 0.8
            },
            'name_introduction': {
                'keywords': ['my name is', 'i am', 'i\'m', 'call me', 'name\'s'],
                'patterns': [
                    r'my\s+name\s+is',
                    r'i\s+am\s+[A-Z]',
                    r'i\'m\s+[A-Z]',
                    r'call\s+me',
                ],
                'confidence': 0.85
            },
            'name_query': {
                'keywords': ['what is my name', 'what\'s my name', 'do you know my name', 
                            'remember my name'],
                'patterns': [
                    r'what(\'s|\s+is)\s+my\s+name',
                    r'do\s+you\s+know\s+my\s+name',
                ],
                'confidence': 0.9
            },
            'help': {
                'keywords': ['help', 'assist', 'support', 'guide', 'how to', 'what can you'],
                'patterns': [
                    r'\bhelp\b',
                    r'what\s+can\s+you\s+do',
                    r'how\s+can\s+you\s+help',
                ],
                'confidence': 0.8
            },
            'weather': {
                'keywords': ['weather', 'temperature', 'rain', 'sunny', 'cloudy', 'forecast'],
                'patterns': [
                    r'weather',
                    r'temperature',
                    r'forecast',
                ],
                'confidence': 0.75
            },
            'time': {
                'keywords': ['time', 'what time', 'current time', 'clock'],
                'patterns': [
                    r'what\s+time',
                    r'current\s+time',
                    r'time\s+is',
                ],
                'confidence': 0.8
            },
            'date': {
                'keywords': ['date', 'what date', 'today\'s date', 'current date'],
                'patterns': [
                    r'what\s+date',
                    r'today\'s\s+date',
                    r'current\s+date',
                ],
                'confidence': 0.8
            },
            'compliment': {
                'keywords': ['thank', 'thanks', 'appreciate', 'great', 'awesome', 'good job'],
                'patterns': [
                    r'thank\s+you',
                    r'thanks',
                    r'great\s+job',
                ],
                'confidence': 0.7
            },
            'unknown': {
                'keywords': [],
                'patterns': [],
                'confidence': 0.0
            }
        }
    
    def recognize(self, text: str) -> Tuple[str, float]:
        """
        Recognize intent from text.
        
        Args:
            text: Input text to analyze
            
        Returns:
            Tuple of (intent_name, confidence_score)
        """
        if not text or not text.strip():
            return 'unknown', 0.0
        
        text_lower = text.lower().strip()
        intent_scores = {}
        
        # Calculate scores for each intent
        for intent_name, intent_data in self.intent_patterns.items():
            if intent_name == 'unknown':
                continue
            
            score = 0.0
            keywords = intent_data.get('keywords', [])
            patterns = intent_data.get('patterns', [])
            base_confidence = intent_data.get('confidence', 0.5)
            
            # Check keyword matches
            keyword_matches = sum(1 for keyword in keywords if keyword in text_lower)
            if keyword_matches > 0:
                score += (keyword_matches / len(keywords)) * base_confidence
            
            # Check pattern matches
            pattern_matches = sum(1 for pattern in patterns 
                                if re.search(pattern, text_lower, re.IGNORECASE))
            if pattern_matches > 0:
                score += (pattern_matches / len(patterns)) * base_confidence
            
            # Normalize score
            if keyword_matches > 0 or pattern_matches > 0:
                intent_scores[intent_name] = min(score, 1.0)
        
        # Return the intent with highest score
        if intent_scores:
            best_intent = max(intent_scores.items(), key=lambda x: x[1])
            return best_intent[0], best_intent[1]
        
        return 'unknown', 0.0
    
    def get_intent_confidence(self, intent: str) -> float:
        """
        Get base confidence score for an intent.
        
        Args:
            intent: Intent name
            
        Returns:
            Confidence score
        """
        return self.intent_patterns.get(intent, {}).get('confidence', 0.0)
    
    def get_all_intents(self) -> List[str]:
        """
        Get list of all supported intents.
        
        Returns:
            List of intent names
        """
        return [intent for intent in self.intent_patterns.keys() if intent != 'unknown']

194 lines•6.6 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