This commit is contained in:
Slipstream 2025-04-27 17:33:11 -06:00
parent e664f43511
commit cbb0c6d607
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD
2 changed files with 119 additions and 2 deletions

View File

@ -13,7 +13,9 @@ from .config import (
LEARNING_UPDATE_INTERVAL, EVOLUTION_UPDATE_INTERVAL, INTEREST_UPDATE_INTERVAL,
INTEREST_DECAY_INTERVAL_HOURS, INTEREST_PARTICIPATION_BOOST,
INTEREST_POSITIVE_REACTION_BOOST, INTEREST_NEGATIVE_REACTION_PENALTY,
INTEREST_FACT_BOOST, STATS_PUSH_INTERVAL # Added stats interval
INTEREST_FACT_BOOST, STATS_PUSH_INTERVAL, # Added stats interval
MOOD_OPTIONS, MOOD_CATEGORIES, MOOD_CHANGE_INTERVAL_MIN, MOOD_CHANGE_INTERVAL_MAX, # Mood change imports
BASELINE_PERSONALITY # For default traits
)
# Assuming analysis functions are moved
from .analysis import (
@ -26,7 +28,7 @@ if TYPE_CHECKING:
# --- Background Task ---
async def background_processing_task(cog: 'GurtCog'):
"""Background task that periodically analyzes conversations, evolves personality, updates interests, and pushes stats."""
"""Background task that periodically analyzes conversations, evolves personality, updates interests, changes mood, and pushes stats."""
# Get API details from environment for stats pushing
api_internal_url = os.getenv("API_INTERNAL_URL")
gurt_stats_push_secret = os.getenv("GURT_STATS_PUSH_SECRET")
@ -108,6 +110,9 @@ async def background_processing_task(cog: 'GurtCog'):
cog.last_interest_update = now # Reset timer after update and decay check
print("Interest update and decay check complete.")
# --- Automatic Mood Change (Runs based on its own interval check) ---
await maybe_change_mood(cog) # Call the mood change logic
except asyncio.CancelledError:
print("Background processing task cancelled")
except Exception as e:
@ -115,6 +120,111 @@ async def background_processing_task(cog: 'GurtCog'):
traceback.print_exc()
await asyncio.sleep(300) # Wait 5 minutes before retrying after an error
# --- Automatic Mood Change Logic ---
async def maybe_change_mood(cog: 'GurtCog'):
"""Checks if enough time has passed and changes mood based on context."""
now = time.time()
time_since_last_change = now - cog.last_mood_change
next_change_interval = random.uniform(MOOD_CHANGE_INTERVAL_MIN, MOOD_CHANGE_INTERVAL_MAX)
if time_since_last_change > next_change_interval:
print(f"Time for a mood change (interval: {next_change_interval:.0f}s). Analyzing context...")
try:
# 1. Analyze Sentiment
positive_sentiment_score = 0
negative_sentiment_score = 0
neutral_sentiment_score = 0
sentiment_channels_count = 0
for channel_id, sentiment_data in cog.conversation_sentiment.items():
# Consider only channels active recently (e.g., within the last hour)
if now - cog.channel_activity.get(channel_id, 0) < 3600:
if sentiment_data["overall"] == "positive":
positive_sentiment_score += sentiment_data["intensity"]
elif sentiment_data["overall"] == "negative":
negative_sentiment_score += sentiment_data["intensity"]
else:
neutral_sentiment_score += sentiment_data["intensity"]
sentiment_channels_count += 1
avg_pos_intensity = positive_sentiment_score / sentiment_channels_count if sentiment_channels_count > 0 else 0
avg_neg_intensity = negative_sentiment_score / sentiment_channels_count if sentiment_channels_count > 0 else 0
avg_neu_intensity = neutral_sentiment_score / sentiment_channels_count if sentiment_channels_count > 0 else 0
print(f" - Sentiment Analysis: Pos={avg_pos_intensity:.2f}, Neg={avg_neg_intensity:.2f}, Neu={avg_neu_intensity:.2f}")
# Determine dominant sentiment category
dominant_sentiment = "neutral"
if avg_pos_intensity > avg_neg_intensity and avg_pos_intensity > avg_neu_intensity:
dominant_sentiment = "positive"
elif avg_neg_intensity > avg_pos_intensity and avg_neg_intensity > avg_neu_intensity:
dominant_sentiment = "negative"
# 2. Get Personality Traits
personality_traits = await cog.memory_manager.get_all_personality_traits()
if not personality_traits:
personality_traits = BASELINE_PERSONALITY.copy()
print(" - Warning: Using baseline personality traits for mood change.")
else:
print(f" - Personality Traits: Mischief={personality_traits.get('mischief', 0):.2f}, Sarcasm={personality_traits.get('sarcasm_level', 0):.2f}, Optimism={personality_traits.get('optimism', 0.5):.2f}")
# 3. Calculate Mood Weights
mood_weights = {mood: 1.0 for mood in MOOD_OPTIONS} # Start with base weight
# Apply Sentiment Bias (e.g., boost factor of 2)
sentiment_boost = 2.0
if dominant_sentiment == "positive":
for mood in MOOD_CATEGORIES.get("positive", []):
mood_weights[mood] *= sentiment_boost
elif dominant_sentiment == "negative":
for mood in MOOD_CATEGORIES.get("negative", []):
mood_weights[mood] *= sentiment_boost
else: # Neutral sentiment
for mood in MOOD_CATEGORIES.get("neutral", []):
mood_weights[mood] *= (sentiment_boost * 0.75) # Slightly boost neutral too
# Apply Personality Bias
mischief_trait = personality_traits.get('mischief', 0.5)
sarcasm_trait = personality_traits.get('sarcasm_level', 0.3)
optimism_trait = personality_traits.get('optimism', 0.5)
if mischief_trait > 0.6: # If high mischief
mood_weights["mischievous"] *= (1.0 + mischief_trait) # Boost mischievous based on trait level
if sarcasm_trait > 0.5: # If high sarcasm
mood_weights["sarcastic"] *= (1.0 + sarcasm_trait)
mood_weights["sassy"] *= (1.0 + sarcasm_trait * 0.5) # Also boost sassy a bit
if optimism_trait > 0.7: # If very optimistic
for mood in MOOD_CATEGORIES.get("positive", []):
mood_weights[mood] *= (1.0 + (optimism_trait - 0.5)) # Boost positive moods
elif optimism_trait < 0.3: # If pessimistic
for mood in MOOD_CATEGORIES.get("negative", []):
mood_weights[mood] *= (1.0 + (0.5 - optimism_trait)) # Boost negative moods
# Ensure current mood has very low weight to avoid picking it again
mood_weights[cog.current_mood] = 0.01
# Filter out moods with zero weight before choices
valid_moods = [mood for mood, weight in mood_weights.items() if weight > 0]
valid_weights = [mood_weights[mood] for mood in valid_moods]
if not valid_moods:
print(" - Error: No valid moods with positive weight found. Skipping mood change.")
return # Skip change if something went wrong
# 4. Select New Mood
new_mood = random.choices(valid_moods, weights=valid_weights, k=1)[0]
# 5. Update State & Log
old_mood = cog.current_mood
cog.current_mood = new_mood
cog.last_mood_change = now
print(f"Mood automatically changed: {old_mood} -> {new_mood} (Influenced by: Sentiment={dominant_sentiment}, Traits)")
except Exception as e:
print(f"Error during automatic mood change: {e}")
traceback.print_exc()
# Still update timestamp to avoid retrying immediately on error
cog.last_mood_change = now
# --- Interest Update Logic ---
async def update_interests(cog: 'GurtCog'):

View File

@ -48,6 +48,13 @@ MOOD_OPTIONS = [
"nostalgic", "confused", "impressed", "skeptical", "enthusiastic",
"distracted", "focused", "creative", "sarcastic", "wholesome"
]
# Categorize moods for weighted selection
MOOD_CATEGORIES = {
"positive": ["excited", "enthusiastic", "playful", "wholesome", "creative", "impressed"],
"negative": ["tired", "a bit bored", "sassy", "sarcastic", "skeptical", "dramatic", "distracted"],
"neutral": ["chill", "neutral", "curious", "philosophical", "focused", "confused", "nostalgic"],
"mischievous": ["mischievous"] # Special category for trait link
}
BASELINE_PERSONALITY = {
"chattiness": 0.7, "emoji_usage": 0.5, "slang_level": 0.5, "randomness": 0.5,
"verbosity": 0.4, "optimism": 0.5, "curiosity": 0.6, "sarcasm_level": 0.3,