Next required modification is that summaries must be async and additionally to what exists, include comment from LLM that has different system prompt, in a way that would write generall summary so far. Prompt to that summariser should include how long ago a user replied(time and calculated difference with current time).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's modify the code to make the summary generation asynchronous and include an LLM-generated comment based on a different prompt, incorporating the time since the user's last reply.
Here's the plan:
Asynchronous Summary: We'll use a separate threading.Thread to run a loop that checks the time and generates the summary periodically without blocking the main input loop.
Track Last Reply Time: Add an attribute self.last_user_reply_time and update it whenever user input is received.
New LLM Call for Summary Comment: Create a new function generate_llm_summary_comment that takes the conversation history and last reply time, constructs a specific prompt for summarization (including the time difference), calls the LLM, and returns the comment.
Modify Periodic Summary: Update generate_periodic_summary to call the new LLM comment function and incorporate its output into the summary string.
Integrate Thread: Start the summary thread in run() and signal it to stop during cleanup().
python
#!/bin/python
import os
import json
import subprocess
import threading
from datetime import datetime, timedelta
import ollama
import time
import sys
import signal
import copy # Needed for deep copying conversation history for the thread
# Configuration
ALARM_SOUND_FILE = os.path.expanduser("~/Music/166467_rocket_race.mp3")
PERSISTENT_STORAGE_FILE = "alarm_chat_history.json"
SCHEDULE_FILE = "user_schedule.json"
OLLAMA_MODEL = "gemma3:1b"
SUMMARY_INTERVAL = 30 # Reduced for easier testing (was 600)
SUMMARY_LLM_MODEL = "gemma3:1b" # Can be the same or different model for summary comments
# Escape sequences
ESCAPE_SEQUENCES = {
"stop_alarm": "<<STOP_ALARM>>",
"snooze": "<<SNOOZE>>",
"add_to_schedule": "<<ADD_TO_SCHEDULE>>",
"remove_from_schedule": "<<REMOVE_FROM_SCHEDULE>>",
}
class AlarmChatApp:
def __init__(self):
# Initialize attributes
self.alarm_active = False
self.mpv_process = None
self.tts_process = None
self.chat_history = []
self.current_conversation = None
self.last_summary_time = time.time()
self.last_user_reply_time = None # Track last user input time
self.tts_available = self.check_tts_available()
self.user_personality = {"description": "No personality data available."}
self.user_schedule = {}
self.running = False # Flag to control summary thread
self.summary_thread = None
self.conversation_lock = threading.Lock() # Lock for accessing shared conversation data
# Verify requirements and load stored data
self.verify_system_requirements()
self.load_persistent_data()
self.load_schedule()
# Setup signal handlers
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
# Add other signals as needed
# signal.signal(signal.SIGHUP, self.signal_handler)
# signal.signal(signal.SIGQUIT, self.signal_handler)
# signal.signal(signal.SIGTRAP, self.signal_handler)
# signal.signal(signal.SIGSYS, self.signal_handler)
# --- Initialization and Setup ---
def check_tts_available(self):
"""Check if spd-say is available"""
try:
subprocess.run(['spd-say', '--version'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return True
except (FileNotFoundError, subprocess.SubprocessError):
print("Warning: spd-say not found. Falling back to text-only mode.")
return False
def load_persistent_data(self):
"""Load chat history from file"""
try:
with open(PERSISTENT_STORAGE_FILE, 'r') as f:
self.chat_history = json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Warning: Could not load chat history - {str(e)}")
self.chat_history = []
def load_schedule(self):
"""Load the user schedule from file"""
try:
with open(SCHEDULE_FILE, 'r') as f:
self.user_schedule = json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Warning: Could not load schedule - {str(e)}")
self.user_schedule = {
"wakeup_times": [],
"preferred_wakeup_questions": [],
"emergency_contacts": []
}
def save_schedule(self):
"""Save the updated user schedule"""
try:
with open(SCHEDULE_FILE, 'w') as f:
json.dump(self.user_schedule, f, indent=4) # Added indent for readability
except IOError as e:
print(f"Error saving schedule: {str(e)}")
def verify_system_requirements(self):
"""Check required components"""
try:
subprocess.run(['ollama', '--version'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except (FileNotFoundError, subprocess.SubprocessError):
print("Error: Ollama is required but not found. Please install Ollama.")
sys.exit(1)
if not self.verify_model(OLLAMA_MODEL):
print(f"Error: Main model '{OLLAMA_MODEL}' is not available.")
print(f"Please install it with: ollama pull {OLLAMA_MODEL}")
sys.exit(1)
if not self.verify_model(SUMMARY_LLM_MODEL):
print(f"Error: Summary model '{SUMMARY_LLM_MODEL}' is not available.")
print(f"Please install it with: ollama pull {SUMMARY_LLM_MODEL}")
sys.exit(1)
def verify_model(self, model_name):
"""Check if a specific Ollama model is available"""
try:
models = ollama.list()
return any(m['model'] == model_name for m in models.get('models', []))
except Exception as e:
print(f"Error checking for model '{model_name}': {str(e)}")
return False
# --- Core LLM Interaction ---
def text_to_speech(self, text):
"""Convert text to speech using spd-say"""
if not self.tts_available or not text or not text.strip():
return
# Stop previous TTS if still running
if self.tts_process and self.tts_process.poll() is None:
try:
self.tts_process.terminate()
self.tts_process.wait(timeout=0.5) # Give it a moment to terminate
except (ProcessLookupError, subprocess.TimeoutExpired, Exception):
pass # Ignore errors during termination
self.tts_process = None
try:
# Use '-w' to wait for speech completion before returning
self.tts_process = subprocess.Popen(
['spd-say', '-w', text],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
# Note: Popen with -w might block if TTS fails internally.
# Consider running TTS in its own thread if it causes issues.
except Exception as e:
print(f"Error in TTS: {str(e)}")
self.tts_available = False # Disable TTS if it fails
def generate_hint_prompt(self):
"""Create a short hint from past conversation history."""
hints = []
# Use a copy of chat history to avoid issues if it's modified elsewhere
history_copy = copy.deepcopy(self.chat_history)
for conv in history_copy:
timestamp_str = conv.get("timestamp", "unknown time")
try:
# Attempt to parse the timestamp for more readable output if needed
dt_obj = datetime.fromisoformat(timestamp_str)
friendly_time = dt_obj.strftime("%Y-%m-%d %H:%M")
except (ValueError, TypeError):
friendly_time = timestamp_str # Fallback to original string
if not conv.get("woke_up", False):
hints.append(f"On {friendly_time}, the attempt was unsuccessful.")
else:
hints.append(f"On {friendly_time}, you woke up successfully.")
if hints:
return "Past conversation summary: " + " ".join(hints[-3:]) # Limit hints
else:
return "No past conversation history available."
def update_personality_data(self):
"""Call the LLM to generate a personality summary from past user messages."""
try:
# Safely access chat history
with self.conversation_lock:
if not self.chat_history:
return "No conversation history available for personality analysis."
# Use a deep copy for analysis
history_copy = copy.deepcopy(self.chat_history)
recent_text = ""
for conv in history_copy[-3:]: # Analyze last 3 conversations
for msg in conv.get("messages", []):
if "user" in msg:
recent_text += f"User: {msg['user']}\n"
if not recent_text:
return "No recent user messages to analyze."
prompt_text = (
"Based *only* on the following user messages from recent interactions, "
"provide a *very concise* (1-2 sentence) summary of the user's likely personality traits, communication style, or attitude observed *during these wake-up attempts*. "
"Focus on aspects relevant to waking them up (e.g., cooperative, groggy, argumentative, concise, verbose). Do not invent information not present in the text.\n\n"
f"Messages:\n{recent_text}\n"
"Concise Summary:"
)
messages = [
{"role": "system", "content": "You are an expert analyst summarizing user personality traits from conversation snippets for an alarm clock assistant."},
{"role": "user", "content": prompt_text}
]
response = ollama.chat(
model=OLLAMA_MODEL, # Use main model for consistency? Or a specialized one?
messages=messages,
options={"temperature": 0.3}
)
personality_summary = response["message"]["content"]
return personality_summary.strip()
except Exception as e:
print(f"Error generating personality data: {str(e)}")
# Fallback to previous description if generation fails
return self.user_personality.get("description", "Personality data generation failed.")
def generate_personality_text(self):
"""Obtain/update personality summary dynamically from the LLM."""
# This might be computationally expensive to run every time.
# Consider caching or running less frequently.
generated_desc = self.update_personality_data()
self.user_personality["description"] = generated_desc
return f"Guessed User Traits (from past interactions): {self.user_personality['description']}"
def generate_system_prompt(self):
"""Generate the system prompt for the main LLM interaction."""
try:
current_time = datetime.now()
weekday = current_time.strftime("%A")
time_str = current_time.strftime("%H:%M")
today_schedule_item = next(
(day for day in self.user_schedule.get("wakeup_times", [])
if day.get("weekday", "").lower() == weekday.lower()), None)
schedule_info = f"Today is {weekday}. "
if today_schedule_item:
schedule_info += f"Scheduled wake-up time: {today_schedule_item.get('time', 'N/A')}. "
important_events = today_schedule_item.get("important_events")
if important_events:
schedule_info += "Important events: " + ", ".join(important_events)
else:
schedule_info += "No specific wake-up time scheduled for today."
hint_prompt = self.generate_hint_prompt()
personality_text = self.generate_personality_text() # Regenerate each time
return f"""You are an intelligent alarm clock helping the user wake up. Your primary goal is to determine if the user is truly awake and alert.
Adopt the persona of a stern but fair police officer or military drill instructor interrogating a recruit. Be direct, ask probing questions, demand clarity.
Current time: {time_str}
{schedule_info}
Context from past attempts: {hint_prompt}
{personality_text}
Your objective: Confirm the user is fully conscious and ready to start their day. Do not stop the alarm easily.
Special commands YOU can use in your response:
{ESCAPE_SEQUENCES["stop_alarm"]} - Use ONLY when 100% convinced the user is awake, alert, and coherent. Requires strong evidence.
{ESCAPE_SEQUENCES["snooze"]} - Use if the user is responsive but clearly groggy, incoherent, or asking for more time. Offers a 5-minute reprieve.
{ESCAPE_SEQUENCES["add_to_schedule"]} - If the conversation naturally leads to schedule changes, you can include this.
{ESCAPE_SEQUENCES["remove_from_schedule"]} - If the conversation naturally leads to schedule changes, you can include this.
Assessment criteria for wakefulness (Be strict!):
1. Coherent, specific, and relevant answers. Vague or one-word answers are suspicious.
2. Demonstration of awareness of current time, day, or surroundings.
3. Clear indication of intent to get up and start the day (e.g., mentioning plans, acknowledging tasks).
Interaction Flow:
1. Start with a pointed question requiring more than a 'yes'/'no' answer (e.g., "State your readiness level for today's objectives," or "What is the first task on your agenda?").
2. Analyze the response critically based on the criteria.
3. Ask follow-up questions to probe deeper if unsure.
4. Use commands ({ESCAPE_SEQUENCES["stop_alarm"]}, {ESCAPE_SEQUENCES["snooze"]}) decisively based on your assessment.
Do NOT apologize or be overly polite. Maintain your persona.
"""
except Exception as e:
print(f"Error generating system prompt: {str(e)}")
return ("You are an alarm clock assistant. Determine if the user is awake by "
"asking thoughtful questions. Use <<STOP_ALARM>> when convinced they're awake, "
"or <<SNOOZE>> if more time is needed.")
def chat_with_llm(self, user_input=None):
"""Send input to LLM and process response"""
try:
# Generate the dynamic system prompt
system_prompt = self.generate_system_prompt()
messages = [{"role": "system", "content": system_prompt}]
# Add current conversation history (limit length?)
with self.conversation_lock:
if self.current_conversation:
# Send recent messages for context, excluding system prompt
messages.extend(self.current_conversation["messages"][-6:]) # Send last 3 rounds
# Add the latest user input if provided
if user_input:
messages.append({"role": "user", "content": user_input})
# Filter out any potential None messages just in case
messages = [msg for msg in messages if msg is not None]
response = ollama.chat(
model=OLLAMA_MODEL,
messages=messages,
options={"temperature": 0.7, "num_predict": 150} # Adjust generation length if needed
)
llm_response = response['message']['content']
action_taken = None
processed_response = llm_response
for cmd, seq in ESCAPE_SEQUENCES.items():
if seq in processed_response:
processed_response = processed_response.replace(seq, "").strip()
action_taken = cmd
# Handle the action immediately *after* getting the response
# self.handle_escape_sequence(cmd) # Moved handling outside this func
# Speak the response *without* the escape sequences
if processed_response:
self.text_to_speech(processed_response)
return processed_response, action_taken # Return processed text and action
except Exception as e:
print(f"Error communicating with LLM: {str(e)}")
# Provide a fallback response
fallback_response = "I seem to be having trouble thinking. Just tell me clearly if you are getting up now."
self.text_to_speech(fallback_response)
return fallback_response, None
# --- Periodic Summary (Asynchronous) ---
def generate_llm_summary_comment(self, conversation_messages):
"""Generate a high-level summary comment from the LLM."""
try:
last_reply_info = "User has not replied yet."
if self.last_user_reply_time:
now = time.time()
time_diff = now - self.last_user_reply_time
time_diff_str = str(timedelta(seconds=int(time_diff)))
last_reply_info = f"User last replied {time_diff_str} ago (at {datetime.fromtimestamp(self.last_user_reply_time).strftime('%H:%M:%S')})."
# Prepare conversation text for the summary LLM
conversation_text = f"{last_reply_info}\n\nConversation Log:\n"
for msg in conversation_messages:
role = next(iter(msg)) # Gets 'assistant' or 'user'
conversation_text += f"{role.capitalize()}: {msg[role]}\n"
summary_prompt = f"""
You are an observational assistant analyzing an ongoing wake-up conversation for an alarm clock app.
Your task is to provide a *brief*, high-level comment on the current state of the interaction.
{last_reply_info}
Consider these points:
- Is the user engaging? How recently?
- Does the user seem to be getting more awake or remaining groggy?
- Is the interaction progressing towards stopping the alarm?
- Mention any notable patterns or difficulties.
Based on the log below, provide a 1-2 sentence comment summarizing the situation.
{conversation_text}
Comment:
"""
messages = [
{"role": "system", "content": "You are providing brief analytical comments on an ongoing wake-up chat."},
{"role": "user", "content": summary_prompt}
]
response = ollama.chat(
model=SUMMARY_LLM_MODEL,
messages=messages,
options={"temperature": 0.5, "num_predict": 80} # Shorter summary
)
comment = response['message']['content'].strip()
return f"LLM Observation: {comment}"
except Exception as e:
print(f"Error generating LLM summary comment: {str(e)}")
return "LLM Observation: Error generating comment."
def generate_periodic_summary(self):
"""Generate the full periodic summary including LLM comment."""
try:
current_time_str = datetime.now().strftime("%H:%M:%S")
# Need conversation messages. Use lock and deepcopy for safety.
with self.conversation_lock:
if not self.current_conversation:
return None # No conversation to summarize
conv_messages = copy.deepcopy(self.current_conversation["messages"])
start_time = self.current_conversation["start_time"]
conv_duration = int(time.time() - start_time)
is_awake = self.check_wakefulness(conv_messages) # Pass messages to checker
recommended_action = ESCAPE_SEQUENCES["stop_alarm"] if is_awake else ESCAPE_SEQUENCES["snooze"]
# Generate the LLM's comment based on the current state
llm_comment = self.generate_llm_summary_comment(conv_messages)
summary = f"""
-------------------------------------
Periodic Summary ({current_time_str})
-------------------------------------
Conversation Duration: {timedelta(seconds=conv_duration)}
Messages Exchanged: {len(conv_messages) // 2 if conv_messages else 0} rounds
Wakefulness Assessment: {'User appears awake' if is_awake else 'User still seems sleepy/unconvinced'}
Recommended Action: {recommended_action}
{llm_comment}
-------------------------------------
"""
return summary, recommended_action # Return summary and the action
except Exception as e:
print(f"Error generating periodic summary: {str(e)}")
return f"<<PERIODIC_SUMMARY>>\nError generating summary: {e}\n", None
def check_wakefulness(self, conversation_messages):
"""Analyze conversation messages to determine if user is awake."""
# This now takes messages as input to be thread-safe
try:
if not conversation_messages or len(conversation_messages) < 2: # Need at least one user response
return False
user_responses = [msg["user"] for msg in conversation_messages if "user" in msg]
if not user_responses:
return False
# Check the last 1 or 2 responses for coherence
last_responses = user_responses[-2:]
# Example criteria: at least one recent response has > 5 words and is not just repeating prompts. More sophisticated checks needed.
awake = any(len(response.split()) > 5 for response in last_responses) and \
all("?" not in response for response in last_responses) # Simple check: not just asking questions back
# You could add LLM-based wakefulness check here too for more accuracy
return awake
except Exception as e:
print(f"Error checking wakefulness: {str(e)}")
return False
def _summary_loop(self):
"""The function run by the summary thread."""
print("[Summary thread started]")
while self.running:
try:
now = time.time()
# Check if interval has passed
# Use a small buffer (0.1s) to avoid race condition with update
if (now - self.last_summary_time) >= (SUMMARY_INTERVAL - 0.1):
summary_text, recommended_action = self.generate_periodic_summary()
if summary_text:
print(f"\n{summary_text}") # Print summary to console
self.last_summary_time = now # Update time *after* generation
# Check if the *recommended action* needs handling (e.g., auto-snooze?)
# Currently, only LLM responses trigger actions, not the summary itself.
# If you want the summary recommendation to trigger actions, add logic here:
# if recommended_action == ESCAPE_SEQUENCES["snooze"]:
# print("[Summary recommends snooze - auto-snoozing? (Not implemented)]")
# elif recommended_action == ESCAPE_SEQUENCES["stop_alarm"]:
# print("[Summary recommends stop - auto-stopping? (Not implemented)]")
# Sleep for a short duration to avoid busy-waiting
time.sleep(2)
except Exception as e:
print(f"[Error in summary thread loop: {e}]")
time.sleep(5) # Wait longer after an error
print("[Summary thread stopped]")
# --- Alarm and Process Management ---
def play_alarm(self):
"""Play alarm sound using mpv."""
if not os.path.exists(ALARM_SOUND_FILE):
print(f"Warning: Alarm sound file not found at {ALARM_SOUND_FILE}. Continuing without audio.")
self.alarm_active = True
return
try:
# Ensure previous process is dead
self.stop_alarm()
print(f"Playing alarm: {ALARM_SOUND_FILE}")
self.alarm_active = True
# Use setsid to create a new process group
self.mpv_process = subprocess.Popen(
['mpv', '--no-video', '--loop=inf', ALARM_SOUND_FILE],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setsid
)
except Exception as e:
print(f"Error starting alarm sound: {str(e)}")
self.alarm_active = True # Still active conceptually
def stop_alarm(self):
"""Stop the alarm sound process."""
if self.mpv_process:
print("Stopping alarm sound...")
try:
# Kill the entire process group created by setsid
os.killpg(os.getpgid(self.mpv_process.pid), signal.SIGTERM)
self.mpv_process.wait(timeout=2)
except ProcessLookupError:
pass # Process already gone
except subprocess.TimeoutExpired:
print("Alarm process did not terminate gracefully, sending SIGKILL.")
try:
os.killpg(os.getpgid(self.mpv_process.pid), signal.SIGKILL)
except ProcessLookupError:
pass # Already gone
except Exception as e:
print(f"Error stopping alarm process: {str(e)}")
finally:
self.mpv_process = None
# Set alarm_active False *only* if the alarm is truly meant to be off
# This is handled by handle_escape_sequence or cleanup
def handle_escape_sequence(self, cmd):
"""Handle detected escape sequences from LLM response."""
try:
print(f"\n[System executing command: {cmd}]")
if cmd == "stop_alarm":
print("LLM requested STOP_ALARM.")
self.stop_alarm() # Stop the sound
self.alarm_active = False # Mark alarm as conceptually stopped
if self.current_conversation:
with self.conversation_lock:
self.current_conversation["woke_up"] = True
elif cmd == "snooze":
print("LLM requested SNOOZE.")
self.stop_alarm() # Stop sound for snooze period
self.alarm_active = True # Still conceptually active, just paused
print("Snoozing for 5 minutes...")
# Start alarm again after 5 mins (300 seconds) in a new thread
threading.Timer(300, self.play_alarm).start()
elif cmd == "add_to_schedule":
self.modify_schedule_add()
elif cmd == "remove_from_schedule":
self.modify_schedule_remove()
except Exception as e:
print(f"Error handling command {cmd}: {str(e)}")
# --- Schedule Modification ---
def modify_schedule_add(self):
"""Guide user to add a schedule entry."""
try:
print("\n--- Add Schedule Entry ---")
print("Enter details in format: Weekday,HH:MM,Event1;Event2 (e.g., Friday,07:00,Meeting;Gym)")
user_input = input("New schedule details: ")
parts = user_input.split(",", 2) # Split max 3 times
if len(parts) < 2:
raise ValueError("Invalid format. Need at least Weekday,HH:MM.")
weekday = parts[0].strip().capitalize()
time_str = parts[1].strip()
# Validate time format
datetime.strptime(time_str, '%H:%M')
events = []
if len(parts) > 2 and parts[2].strip():
events = [e.strip() for e in parts[2].split(";") if e.strip()]
new_entry = {"weekday": weekday, "time": time_str, "important_events": events}
# Avoid duplicates (optional check)
# if new_entry in self.user_schedule["wakeup_times"]:
# print("This entry already exists.")
# return
self.user_schedule.setdefault("wakeup_times", []).append(new_entry)
self.save_schedule()
print("Schedule entry added successfully.")
print("--------------------------\n")
except ValueError as ve:
print(f"Invalid input: {ve}")
except Exception as e:
print(f"Error adding schedule: {str(e)}")
def modify_schedule_remove(self):
"""Guide user to remove a schedule entry."""
try:
print("\n--- Remove Schedule Entry ---")
entries = self.user_schedule.get("wakeup_times", [])
if not entries:
print("No schedule entries to remove.")
return
print("Current wakeup schedules:")
for idx, sched in enumerate(entries):
events_str = "; ".join(sched.get("important_events", []))
print(f"{idx}: {sched.get('weekday')} at {sched.get('time')} (Events: {events_str or 'None'})")
idx_input = input(f"Enter the number (0 to {len(entries)-1}) of the entry to remove: ")
index = int(idx_input)
if 0 <= index < len(entries):
removed = entries.pop(index)
self.save_schedule()
print(f"Removed schedule entry: {removed}")
else:
print("Invalid index.")
print("---------------------------\n")
except ValueError:
print("Invalid input. Please enter a number.")
except Exception as e:
print(f"Error removing schedule: {str(e)}")
# --- Main Loop and Cleanup ---
def signal_handler(self, signum, frame):
"""Handle termination signals gracefully."""
print(f"\nReceived signal {signal.Signals(signum).name}. Shutting down...")
self.running = False # Signal summary thread to stop
self.cleanup()
sys.exit(0) # Exit cleanly
def cleanup(self):
"""Clean up resources."""
print("Cleaning up resources...")
self.running = False # Ensure flag is set
# Stop alarm sound process
self.stop_alarm()
# Stop TTS process
if self.tts_process and self.tts_process.poll() is None:
print("Terminating TTS process...")
try:
self.tts_process.terminate()
self.tts_process.wait(timeout=1)
except Exception as e:
print(f"Error terminating TTS: {e}")
self.tts_process = None
# Wait for summary thread to finish
if self.summary_thread and self.summary_thread.is_alive():
print("Waiting for summary thread to finish...")
self.summary_thread.join(timeout=3) # Wait up to 3 seconds
if self.summary_thread.is_alive():
print("Summary thread did not finish gracefully.")
# Save final state if conversation didn't result in wake-up
if self.current_conversation:
with self.conversation_lock:
if not self.current_conversation.get("woke_up", False):
print("Saving final conversation state (user did not confirm wake-up).")
self.current_conversation["woke_up"] = False # Explicitly mark as not woken up
# Avoid appending if already saved somehow, though unlikely here
if self.current_conversation not in self.chat_history:
self.chat_history.append(self.current_conversation)
self.save_persistent_data() # Save history
print("Cleanup complete.")
def save_persistent_data(self):
"""Save recent chat history to file."""
try:
with self.conversation_lock: # Access history safely
history_to_save = copy.deepcopy(self.chat_history[-10:]) # Save last 10
with open(PERSISTENT_STORAGE_FILE, 'w') as f:
json.dump(history_to_save, f, indent=4) # Added indent
except IOError as e:
print(f"Error saving chat history: {str(e)}")
except Exception as e:
print(f"Unexpected error saving chat history: {e}")
def run(self):
"""Main application loop."""
print("\n=== Alarm Chat App ===")
print("The alarm will sound until you demonstrate you're fully awake.")
print("Press Ctrl+C to exit cleanly.\n")
self.running = True
# Start the summary thread
self.summary_thread = threading.Thread(target=self._summary_loop, daemon=True) # Daemon ensures it exits if main thread exits unexpectedly
self.summary_thread.start()
try:
# Initialize conversation safely
with self.conversation_lock:
self.current_conversation = {
"start_time": time.time(),
"timestamp": datetime.now().isoformat(),
"messages": [], # Store as list of {"role": content}
"woke_up": False
}
self.last_user_reply_time = time.time() # Initialize reply time
self.play_alarm() # Start alarm sound
# Initial message from Assistant
try:
print("Assistant generating initial prompt...")
initial_msg, action = self.chat_with_llm() # No user input initially
if initial_msg:
print(f"Assistant: {initial_msg}")
with self.conversation_lock:
self.current_conversation["messages"].append({"assistant": initial_msg})
if action: # Handle action if LLM immediately decides (e.g., snooze)
self.handle_escape_sequence(action)
self.last_summary_time = time.time() # Reset summary timer after init
except Exception as e:
print(f"Error during initial LLM call: {str(e)}")
# Fallback initial message
fallback_initial_msg = "This is your wake-up call. Are you ready to report?"
print(f"Assistant: {fallback_initial_msg}")
with self.conversation_lock:
self.current_conversation["messages"].append({"assistant": fallback_initial_msg})
# Main interaction loop
while self.alarm_active:
try:
user_input = input("You: ")
self.last_user_reply_time = time.time() # Update last reply time
if user_input.strip(): # Ignore empty input
# Add user message to conversation history
with self.conversation_lock:
if self.current_conversation: # Check if conversation exists
self.current_conversation["messages"].append({"user": user_input})
else:
print("Error: Current conversation is None. Cannot add message.")
continue # Skip processing if conversation is missing
# Get LLM response and potential action
llm_response, action_taken = self.chat_with_llm(user_input)
if llm_response:
print(f"Assistant: {llm_response}")
# Add assistant message to history
with self.conversation_lock:
if self.current_conversation:
self.current_conversation["messages"].append({"assistant": llm_response})
else:
print("Error: Current conversation is None. Cannot add assistant message.")
# Handle action *after* response is processed and added
if action_taken:
self.handle_escape_sequence(action_taken)
# If alarm was stopped, break the loop
if not self.alarm_active:
break
else:
print("(Empty input ignored)")
except EOFError:
print("\nEOF received. Shutting down...")
self.running = False
break
except KeyboardInterrupt:
print("\nKeyboardInterrupt received. Shutting down...")
self.running = False
break # Exit loop, finally block will call cleanup
except Exception as e:
print(f"Error in main loop: {str(e)}")
time.sleep(1) # Prevent tight loop on error
except Exception as e:
print(f"Fatal error in run method: {str(e)}")
finally:
# Ensure cleanup runs even if loop breaks unexpectedly
self.cleanup()
if self.alarm_active: # Check final state
print("\nWarning: Exited while alarm was still marked as active!")
else:
print("\nAlarm stopped. Have a productive day!")
if __name__ == "__main__":
app = AlarmChatApp()
app.run()
Key Changes and Explanations:
last_user_reply_time: Added to __init__, initialized, and updated after each input("You: ").
conversation_lock: A threading.Lock is introduced to protect access to self.current_conversation and self.chat_history from both the main thread and the summary thread. Access to these shared resources is wrapped in with self.conversation_lock:.
copy.deepcopy: Used when passing conversation data to threads or analysis functions (generate_hint_prompt, update_personality_data, generate_llm_summary_comment, check_wakefulness, save_persistent_data) to prevent modification race conditions and ensure the analysis uses a consistent snapshot.
_summary_loop(self): This method runs in a separate thread.
It uses a while self.running: loop controlled by a flag.
Constructs a specific system prompt for the summarizer LLM.
Formats the conversation log, including the last reply time info.
Calls ollama.chat using SUMMARY_LLM_MODEL.
Returns the formatted comment.
generate_periodic_summary(self):
Now calls generate_llm_summary_comment.
Includes the LLM comment in the final summary string.
Takes conversation messages via lock/copy for thread safety.
Returns the summary text and the recommended action (though the action isn't automatically executed by the summary thread currently).
check_wakefulness(self, conversation_messages): Modified to accept conversation_messages as an argument so it can be called safely from the summary thread with a snapshot of the data.
Threading Integration:
Now, the periodic summary will be generated and printed in the background without halting the user's ability to type, and it will include the LLM's observation based on the conversation progress and timing.
self.running flag added.
self.summary_thread attribute added.
Thread is created and started in run().
self.running is set to False in cleanup() and signal_handler.
self.summary_thread.join() is called in cleanup() to wait for the thread to finish.
Cleanup and Signals:
signal_handler now sets self.running = False before calling cleanup.
cleanup ensures the summary thread is joined.
More robust process killing for mpv using os.killpg and preexec_fn=os.setsid.
Error Handling & Refinements: Added more try...except blocks, improved formatting, added checks for None conversation, and made TTS termination slightly more robust. Message history passing to LLM is refined.