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:
parent
a1f30c31c6
commit
2b15ceeaa1
3 changed files with 22 additions and 12 deletions
|
|
@ -5,13 +5,14 @@ Handles communication with Perplexity Sonar API
|
||||||
import httpx
|
import httpx
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
import logging
|
||||||
from typing import List, Dict, Optional
|
from typing import List, Dict, Optional
|
||||||
|
|
||||||
|
|
||||||
class PerplexityProvider:
|
class PerplexityProvider:
|
||||||
"""Communicates with Perplexity API for AI responses"""
|
"""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
|
Initialize Perplexity API provider
|
||||||
|
|
||||||
|
|
@ -20,12 +21,14 @@ class PerplexityProvider:
|
||||||
model (str): Model to use (default: sonar-pro)
|
model (str): Model to use (default: sonar-pro)
|
||||||
max_tokens (int): Maximum tokens in response
|
max_tokens (int): Maximum tokens in response
|
||||||
temperature (float): Sampling temperature
|
temperature (float): Sampling temperature
|
||||||
|
logger: Optional logger instance for error reporting
|
||||||
"""
|
"""
|
||||||
self.api_key = api_key
|
self.api_key = api_key
|
||||||
self.model = model
|
self.model = model
|
||||||
self.max_tokens = max_tokens
|
self.max_tokens = max_tokens
|
||||||
self.temperature = temperature
|
self.temperature = temperature
|
||||||
self.base_url = "https://api.perplexity.ai"
|
self.base_url = "https://api.perplexity.ai"
|
||||||
|
self.logger = logger or logging.getLogger(__name__)
|
||||||
|
|
||||||
# Statistics
|
# Statistics
|
||||||
self.total_requests = 0
|
self.total_requests = 0
|
||||||
|
|
@ -85,16 +88,16 @@ class PerplexityProvider:
|
||||||
else:
|
else:
|
||||||
self.total_errors += 1
|
self.total_errors += 1
|
||||||
error_msg = f"API Error {response.status_code}: {response.text}"
|
error_msg = f"API Error {response.status_code}: {response.text}"
|
||||||
print(error_msg)
|
self.logger.error(error_msg)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
except httpx.TimeoutException:
|
except httpx.TimeoutException:
|
||||||
self.total_errors += 1
|
self.total_errors += 1
|
||||||
print("API Timeout: Request took too long")
|
self.logger.error("API Timeout: Request took too long")
|
||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.total_errors += 1
|
self.total_errors += 1
|
||||||
print(f"API Error: {str(e)}")
|
self.logger.error(f"API Error: {str(e)}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def validate_api_key(self):
|
async def validate_api_key(self):
|
||||||
|
|
|
||||||
10
chatbot.py
10
chatbot.py
|
|
@ -30,18 +30,22 @@ class EugenBot(irc.bot.SingleServerIRCBot):
|
||||||
self.bot_name = config.bot_name
|
self.bot_name = config.bot_name
|
||||||
self.channel = config.twitch_channel
|
self.channel = config.twitch_channel
|
||||||
|
|
||||||
|
# Initialize logger first
|
||||||
|
self.logger = Logger(log_dir=config.log_dir, debug_mode=config.debug_mode)
|
||||||
|
|
||||||
# Initialize components
|
# Initialize components
|
||||||
self.memory = ConversationMemory(
|
self.memory = ConversationMemory(
|
||||||
data_dir=config.data_dir,
|
data_dir=config.data_dir,
|
||||||
retention_hours=config.context_retention_hours
|
retention_hours=config.context_retention_hours,
|
||||||
|
logger=self.logger
|
||||||
)
|
)
|
||||||
self.ai = PerplexityProvider(
|
self.ai = PerplexityProvider(
|
||||||
api_key=config.perplexity_key,
|
api_key=config.perplexity_key,
|
||||||
model=config.model,
|
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.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)
|
# Dashboard (will be initialized in GUI thread)
|
||||||
self.dashboard = None
|
self.dashboard = None
|
||||||
|
|
|
||||||
13
memory.py
13
memory.py
|
|
@ -3,6 +3,7 @@ Conversation Memory for Eugen Bot
|
||||||
Stores and retrieves chat history per user with time-based filtering
|
Stores and retrieves chat history per user with time-based filtering
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from typing import List, Dict, Optional
|
from typing import List, Dict, Optional
|
||||||
|
|
@ -11,7 +12,7 @@ from typing import List, Dict, Optional
|
||||||
class ConversationMemory:
|
class ConversationMemory:
|
||||||
"""Manages persistent conversation history for each user"""
|
"""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
|
Initialize conversation memory
|
||||||
|
|
||||||
|
|
@ -19,11 +20,13 @@ class ConversationMemory:
|
||||||
data_dir (str): Directory to store conversation JSON files
|
data_dir (str): Directory to store conversation JSON files
|
||||||
max_messages (int): Maximum messages to store per user
|
max_messages (int): Maximum messages to store per user
|
||||||
retention_hours (int): How long to keep messages in context
|
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 = Path(data_dir)
|
||||||
self.data_dir.mkdir(parents=True, exist_ok=True)
|
self.data_dir.mkdir(parents=True, exist_ok=True)
|
||||||
self.max_messages = max_messages
|
self.max_messages = max_messages
|
||||||
self.retention_hours = retention_hours
|
self.retention_hours = retention_hours
|
||||||
|
self.logger = logger or logging.getLogger(__name__)
|
||||||
|
|
||||||
def _get_user_file(self, username):
|
def _get_user_file(self, username):
|
||||||
"""Get the file path for a user's conversation history"""
|
"""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:
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
history = json.load(f)
|
history = json.load(f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error loading history for {username}: {e}")
|
self.logger.error(f"Error loading history for {username}: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
# Filter by retention time
|
# Filter by retention time
|
||||||
|
|
@ -87,7 +90,7 @@ class ConversationMemory:
|
||||||
with open(file_path, 'r', encoding='utf-8') as f:
|
with open(file_path, 'r', encoding='utf-8') as f:
|
||||||
history = json.load(f)
|
history = json.load(f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error loading history for {username}: {e}")
|
self.logger.error(f"Error loading history for {username}: {e}")
|
||||||
history = []
|
history = []
|
||||||
|
|
||||||
# Add new message
|
# Add new message
|
||||||
|
|
@ -106,7 +109,7 @@ class ConversationMemory:
|
||||||
with open(file_path, 'w', encoding='utf-8') as f:
|
with open(file_path, 'w', encoding='utf-8') as f:
|
||||||
json.dump(history, f, ensure_ascii=False, indent=2)
|
json.dump(history, f, ensure_ascii=False, indent=2)
|
||||||
except Exception as e:
|
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):
|
def format_for_prompt(self, history):
|
||||||
"""
|
"""
|
||||||
|
|
@ -138,7 +141,7 @@ class ConversationMemory:
|
||||||
try:
|
try:
|
||||||
file_path.unlink()
|
file_path.unlink()
|
||||||
except Exception as e:
|
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):
|
def get_all_users(self):
|
||||||
"""
|
"""
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue