Skip to content

4.2 Interests Module

Lumi Bunny edited this page Aug 12, 2025 · 1 revision

interest_tracker.py is a module designed to track and analyze user interests over time through conversation analysis. The goal is to build dynamic interest profiles that help the chatbot understand what topics users are passionate about, enabling more engaging and personalized conversations.

Overview of interest_tracker.py

This file implements an InterestTracker system that analyzes conversations to detect interest signals, calculates interest scores with decay over time, and provides conversation suggestions based on user interests. It's designed to work seamlessly with the memory management system to build comprehensive user profiles.

1. Imports and Setup

The module uses several key libraries:

  • datetime: For timestamp handling and time-based calculations
  • typing: For type hints (Dict, List)
  • logging: For debugging and monitoring interest tracking

2. InterestTracker Class

The Main Interest Analysis Engine

This class manages all aspects of interest tracking and analysis.

Key Configuration Parameters:

  • interest_decay_days: 30 - How long before interests start fading
  • mention_threshold: 3 - How many mentions to consider "strong interest"
  • memory_manager: Integration with MemoryManager for persistent storage

Sentiment Analysis Components:

  • positive_indicators: ['love', 'like', 'enjoy', 'adore', 'prefer', 'favorite', 'fond of']
  • negative_indicators: ['hate', 'dislike', 'boring', 'annoying', 'terrible', 'awful', 'worst']
  • negation_words: ['not', 'never', 'dont', "don't", 'doesnt', "doesn't"]

3. Core Methods Breakdown

track_conversation_interests()

The Main Entry Point

This is the primary method for analyzing conversations and updating interest scores.

What it does:

  • Analyzes conversation text for topic mentions
  • Calculates interest scores based on frequency, sentiment, and history
  • Updates persistent storage via MemoryManager
  • Returns dictionary of {topic: interest_score}

Parameters:

  • user_id: User identifier
  • conversation_text: Text to analyze
  • timestamp: When the conversation occurred (defaults to now)

_extract_topics_from_text()

Topic Detection Engine

Uses keyword-based detection across 10 major interest categories:

Categories and Keywords:

  • Gaming: ['game', 'gaming', 'play', 'minecraft', 'zelda', 'steam', 'xbox', 'playstation']
  • Cooking: ['cook', 'recipe', 'food', 'kitchen', 'bake', 'meal', 'chef', 'ingredient', 'pasta']
  • Art: ['art', 'draw', 'paint', 'sketch', 'creative', 'design', 'canvas', 'brush']
  • Music: ['music', 'song', 'band', 'listen', 'album', 'concert', 'guitar', 'piano']
  • Fitness: ['workout', 'gym', 'exercise', 'run', 'fitness', 'health', 'training', 'cardio']
  • Travel: ['travel', 'trip', 'vacation', 'visit', 'explore', 'country', 'flight', 'hotel']
  • Technology: ['tech', 'computer', 'programming', 'code', 'software', 'app', 'website']
  • Movies: ['movie', 'film', 'cinema', 'series', 'show', 'episode', 'netflix']
  • Reading: ['book', 'read', 'novel', 'author', 'chapter', 'library', 'story', 'literature']
  • Pets: ['dog', 'cat', 'pet', 'puppy', 'kitten', 'animal', 'vet', 'walk']

_detect_sentiment()

Sentiment Analysis for Topics

Analyzes how the user feels about detected topics using a sophisticated approach:

Sentiment Scoring:

  • Positive indicators: +0.3 per mention
  • Negative indicators: -0.3 per mention
  • Negation handling: Reverses sentiment (±0.2)
  • Range: -1.0 (very negative) to +1.0 (very positive)

Examples:

"I love gaming"+0.3 sentiment
"I don't like horror movies"-0.2 sentiment (negated positive)
"Gaming is not boring"+0.2 sentiment (negated negative)

_calculate_interest_score()

Advanced Interest Scoring Algorithm

This is the heart of the interest tracking system, using a sophisticated scoring algorithm:

Scoring Components:

  1. Base score: mentions * 0.15 (max 0.4)
  2. Sentiment boost: sentiment * 0.25
  3. Minimum guarantee: 0.1 for any detected interest
  4. Existing interest handling: Decay factor of 0.85 + accumulation bonus of 0.08

Scoring Examples:

# New interest: "I really enjoy cooking"
# Base: 1 mention * 0.15 = 0.15
# Sentiment: +0.3 * 0.25 = 0.075
# Total: 0.225

# Existing interest (score 0.4): "Cooking is fun"
# Decay: 0.4 * 0.85 = 0.34
# New: 0.15 + 0.075 = 0.225
# Bonus: 0.08
# Total: 0.645

get_top_interests()

Interest Retrieval and Ranking

Retrieves user's top interests from persistent storage:

Features:

  • Filters interests with score > 0.01
  • Sorts by score (descending)
  • Returns structured data with topic, score, and last_updated
  • Configurable limit (default: 5)

suggest_conversation_topics()

Personalized Conversation Starters

Generates natural conversation starters based on user interests:

Topic-Specific Suggestions:

  • Gaming: "How's your gaming going lately? Still playing?"
  • Cooking: "Have you tried any new recipes recently?"
  • Art: "Working on any art projects these days?"
  • Music: "Discovered any good music lately?"
  • Fitness: "How's your workout routine going?"

Fallback Suggestions:

  • "What have you been up to lately?"
  • "Any new hobbies or interests?"
  • "How was your day?"

detect_interest_changes()

Interest Trend Analysis

Analyzes how user interests change over time:

Change Detection:

  • Compares recent vs. older mention frequencies
  • "Increasing": Recent mentions > older * 1.5
  • "Decreasing": Older mentions > recent * 1.5
  • "Stable": Neither condition met

4. Integration with MemoryManager

The InterestTracker integrates seamlessly with the memory system:

Storage Integration:

  • Uses memory_manager.add_interest() to store interest scores
  • Uses memory_manager.get_interests() to retrieve existing scores
  • Stores conversation context snippets for reference

Memory vs. Interest Storage:

  • Interests: Stored in interests.json with scores and timestamps
  • Memories: Important interest-related events stored in important_memories.json
  • Separation: Keeps dynamic interest tracking separate from permanent memories

5. How It All Works Together

Here's an example flow when analyzing: "I've been really enjoying cooking lately, trying new pasta recipes"

  1. Topic extraction: Detects "cooking" (keywords: cook, recipe, pasta)
  2. Sentiment analysis: Positive sentiment (+0.3 for "enjoying")
  3. Score calculation:
    • Base: 3 mentions * 0.15 = 0.45 (capped at 0.4)
    • Sentiment: +0.3 * 0.25 = 0.075
    • Total: 0.475
  4. Storage: Updates cooking interest score in MemoryManager
  5. Context: Saves conversation snippet for future reference

6. Interest Decay System

The system implements intelligent interest decay to keep profiles current:

Decay Mechanism:

  • 30-day decay period: Interests naturally fade without reinforcement
  • Decay factor: 0.85 applied to existing scores when new mentions occur
  • Prevents stagnation: Old interests don't dominate forever
  • Encourages fresh interests: New topics can quickly gain prominence

Why Decay Matters:

  • Reflects reality: People's interests change over time
  • Prevents bloat: Keeps interest profiles manageable
  • Maintains relevance: Recent interests get priority in conversations
  • Allows evolution: Users can develop new passions

7. Advanced Features

Sentiment-Aware Scoring:

Unlike simple keyword counting, the system understands context:

  • "I love gaming but hate mobile games" → Positive gaming score, negative mobile gaming
  • "Cooking is not boring anymore" → Positive cooking score (negation handled)

Accumulation Intelligence:

  • New interests: Start with base scores
  • Existing interests: Get decay + accumulation + bonus
  • Prevents runaway growth: Caps and decay factors maintain balance

Conversation Enhancement:

  • Personalized starters: Based on actual user interests
  • Trend awareness: Knows if interests are growing or fading
  • Context preservation: Remembers why interests were detected

8. Integration Architecture

The InterestTracker fits into the broader system architecture:

User Input → BunnyChat → InterestTracker → MemoryManager
                              ↓              ↓
                    Interest Analysis → interests.json
                              ↓              ↓
                    Conversation Context ← get_interests()

Module Dependencies:

  • Requires: MemoryManager for persistent storage
  • Used by: BunnyChat for conversation enhancement
  • Integrates with: PreferenceExtractor for comprehensive user profiling

9. Future Enhancements

Potential Improvements:

  1. spaCy Integration: More sophisticated NLP for topic detection
  2. Category Expansion: Add more interest categories based on usage patterns
  3. Seasonal Awareness: Adjust interest relevance based on time of year
  4. Social Context: Consider interests in group conversations
  5. Cross-Reference: Link interests with preferences for deeper insights

Scalability Considerations:

  • Keyword Expansion: Easy to add new topics and keywords
  • Performance: Lightweight keyword matching scales well
  • Storage Efficiency: JSON-based storage keeps overhead minimal
  • Memory Integration: Leverages existing MemoryManager infrastructure

10. Why This Design is Effective

  • Hybrid Approach: Combines keyword detection with sentiment analysis
  • Temporal Awareness: Understands that interests change over time
  • Context Preservation: Remembers not just what, but why interests were detected
  • Integration Ready: Designed to work seamlessly with existing memory and preference systems
  • Conversation Enhancement: Directly improves chat quality through personalized topics

This module transforms static chatbot interactions into dynamic, interest-aware conversations that evolve with the user's changing passions and hobbies.

Clone this wiki locally