Replace print statements with proper logging

Fixed inconsistent error handling in ai_provider.py and memory.py by:
- Adding optional logger parameter to PerplexityProvider and ConversationMemory classes
- Replacing all print() statements with proper logger.error() calls
- Updating chatbot.py to pass logger instance to both components
- Ensuring consistent logging architecture across the codebase

This improves error visibility and integrates with the existing logging infrastructure.
This commit is contained in:
Claude 2026-01-02 20:58:49 +00:00
parent a1f30c31c6
commit 2b15ceeaa1
No known key found for this signature in database
3 changed files with 22 additions and 12 deletions

View file

@ -5,13 +5,14 @@ Handles communication with Perplexity Sonar API
import httpx
import json
import time
import logging
from typing import List, Dict, Optional
class PerplexityProvider:
"""Communicates with Perplexity API for AI responses"""
def __init__(self, api_key, model="sonar-pro", max_tokens=450, temperature=0.7):
def __init__(self, api_key, model="sonar-pro", max_tokens=450, temperature=0.7, logger=None):
"""
Initialize Perplexity API provider
@ -20,12 +21,14 @@ class PerplexityProvider:
model (str): Model to use (default: sonar-pro)
max_tokens (int): Maximum tokens in response
temperature (float): Sampling temperature
logger: Optional logger instance for error reporting
"""
self.api_key = api_key
self.model = model
self.max_tokens = max_tokens
self.temperature = temperature
self.base_url = "https://api.perplexity.ai"
self.logger = logger or logging.getLogger(__name__)
# Statistics
self.total_requests = 0
@ -85,16 +88,16 @@ class PerplexityProvider:
else:
self.total_errors += 1
error_msg = f"API Error {response.status_code}: {response.text}"
print(error_msg)
self.logger.error(error_msg)
return None
except httpx.TimeoutException:
self.total_errors += 1
print("API Timeout: Request took too long")
self.logger.error("API Timeout: Request took too long")
return None
except Exception as e:
self.total_errors += 1
print(f"API Error: {str(e)}")
self.logger.error(f"API Error: {str(e)}")
return None
async def validate_api_key(self):

View file

@ -30,18 +30,22 @@ class EugenBot(irc.bot.SingleServerIRCBot):
self.bot_name = config.bot_name
self.channel = config.twitch_channel
# Initialize logger first
self.logger = Logger(log_dir=config.log_dir, debug_mode=config.debug_mode)
# Initialize components
self.memory = ConversationMemory(
data_dir=config.data_dir,
retention_hours=config.context_retention_hours
retention_hours=config.context_retention_hours,
logger=self.logger
)
self.ai = PerplexityProvider(
api_key=config.perplexity_key,
model=config.model,
max_tokens=config.max_tokens
max_tokens=config.max_tokens,
logger=self.logger
)
self.detector = MentionDetector(bot_name=self.bot_name)
self.logger = Logger(log_dir=config.log_dir, debug_mode=config.debug_mode)
# Dashboard (will be initialized in GUI thread)
self.dashboard = None

View file

@ -3,6 +3,7 @@ Conversation Memory for Eugen Bot
Stores and retrieves chat history per user with time-based filtering
"""
import json
import logging
from pathlib import Path
from datetime import datetime, timedelta
from typing import List, Dict, Optional
@ -11,7 +12,7 @@ from typing import List, Dict, Optional
class ConversationMemory:
"""Manages persistent conversation history for each user"""
def __init__(self, data_dir="data/conversations", max_messages=25, retention_hours=1):
def __init__(self, data_dir="data/conversations", max_messages=25, retention_hours=1, logger=None):
"""
Initialize conversation memory
@ -19,11 +20,13 @@ class ConversationMemory:
data_dir (str): Directory to store conversation JSON files
max_messages (int): Maximum messages to store per user
retention_hours (int): How long to keep messages in context
logger: Optional logger instance for error reporting
"""
self.data_dir = Path(data_dir)
self.data_dir.mkdir(parents=True, exist_ok=True)
self.max_messages = max_messages
self.retention_hours = retention_hours
self.logger = logger or logging.getLogger(__name__)
def _get_user_file(self, username):
"""Get the file path for a user's conversation history"""
@ -51,7 +54,7 @@ class ConversationMemory:
with open(file_path, 'r', encoding='utf-8') as f:
history = json.load(f)
except Exception as e:
print(f"Error loading history for {username}: {e}")
self.logger.error(f"Error loading history for {username}: {e}")
return []
# Filter by retention time
@ -87,7 +90,7 @@ class ConversationMemory:
with open(file_path, 'r', encoding='utf-8') as f:
history = json.load(f)
except Exception as e:
print(f"Error loading history for {username}: {e}")
self.logger.error(f"Error loading history for {username}: {e}")
history = []
# Add new message
@ -106,7 +109,7 @@ class ConversationMemory:
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(history, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Error saving history for {username}: {e}")
self.logger.error(f"Error saving history for {username}: {e}")
def format_for_prompt(self, history):
"""
@ -138,7 +141,7 @@ class ConversationMemory:
try:
file_path.unlink()
except Exception as e:
print(f"Error clearing history for {username}: {e}")
self.logger.error(f"Error clearing history for {username}: {e}")
def get_all_users(self):
"""