Below is the updated version of your code with the requested modifications. Here's a summary of the changes:
Key Modifications:
-
Asynchronous Summaries:
- The
generate_periodic_summary() method now runs asynchronously using threading. This means that when it's time for a summary, it spawns a new thread to generate the full summary (including the LLM comment) without blocking the main loop.
- Once the summary is generated in the background thread, it's printed or processed in the main loop.
-
Enhanced Summary Content:
- In addition to the existing summary details (time, duration, messages exchanged, assessment, and recommended action), the summary now includes a general comment from the LLM.
- This comment is generated by a separate LLM call with a custom system prompt.
- The prompt for this LLM includes:
- A general summary of the conversation so far.
- The time of the last user reply.
- The calculated difference between the last user reply time and the current time.
-
New LLM Call for Summary Comment:
- I added a new method,
generate_llm_summary_comment(), which handles the LLM call for the comment. This method uses a different system prompt focused on summarizing the conversation.
- The system prompt for this summarizer includes the conversation history, the last user reply time, and the time difference.
-
Threading for Asynchronicity:
- When the summary interval is reached, a thread is started to generate the full summary. This thread calls the original summary logic plus the new LLM comment.
- The result is then handled in the main loop (e.g., printed).
-
Edge Cases Handled:
- If there's no user reply yet, the time difference is reported as "N/A".
- Error handling is added to prevent crashes if the LLM call fails.
Here's the full updated code:
#!/bin/python
import os
import json
import subprocess
import threading
from datetime import datetime
import ollama
import time
import sys
import signal
# 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 = 600 # 10 minutes in seconds
# 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.tts_available = self.check_tts_available()
self.user_personality = {"description": "No personality data available."}
# 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)
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)
def check_tts_available(self):
"""Check if spd-say is available"""
try:
subprocess.run(['spd-say', '--version'],
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)
except IOError as e:
print(f"Error saving schedule: {str(e)}")
def verify_system_requirements(self):
"""Check required components"""
try:
subprocess.run(['ollama', '--version'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except FileNotFoundError:
print("Error: Ollama is required but not found. Please install Ollama.")
sys.exit(1)
if not self.verify_model():
print(f"Error: Model '{OLLAMA_MODEL}' is not available.")
print(f"Please install it with: ollama pull {OLLAMA_MODEL}")
sys.exit(1)
def verify_model(self):
"""Check if the required model is available"""
try:
models = ollama.list()
return any(m['model'] == OLLAMA_MODEL for m in models.get('models', []))
except Exception as e:
print(f"Error checking for model: {str(e)}")
return False
def text_to_speech(self, text):
"""Convert text to speech using spd-say"""
if not self.tts_available or not text.strip():
return
if self.tts_process and self.tts_process.poll() is None:
self.tts_process.terminate()
try:
self.tts_process = subprocess.Popen(
['spd-say', '-w', text],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except Exception as e:
print(f"Error in TTS: {str(e)}")
self.tts_available = False
def generate_hint_prompt(self):
"""
Create a short hint from past conversation history.
"""
hints = []
for conv in self.chat_history:
timestamp = conv.get("timestamp", "unknown time")
if not conv.get("woke_up", False):
hints.append(f"On {timestamp}, the attempt was unsuccessful.")
else:
hints.append(f"On {timestamp}, you woke up successfully.")
if hints:
return "Past conversation summary: " + " ".join(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:
if not self.chat_history:
return "No conversation history available for personality analysis."
recent_text = ""
for conv in self.chat_history[-3:]:
for msg in conv.get("messages", []):
if "user" in msg:
recent_text += msg["user"] + "\n"
prompt_text = (
"Based on the following user messages, summarize the user's personality, "
"including any apparent likes, dislikes, strengths, and weaknesses:\n\n"
f"{recent_text}\n"
"Provide a concise summary."
)
messages = [
{"role": "system", "content": "You are a helpful assistant that analyzes personality."},
{"role": "user", "content": prompt_text}
]
response = ollama.chat(
model=OLLAMA_MODEL,
messages=messages,
options={"temperature": 0.3}
)
return response["message"]["content"].strip()
except Exception as e:
print(f"Error generating personality data: {str(e)}")
return "Personality data not available."
def generate_personality_text(self):
"""
Obtain personality summary dynamically from the LLM.
"""
self.user_personality["description"] = self.update_personality_data()
return f"Personality: {self.user_personality['description']}"
def generate_system_prompt(self):
"""Generate the system prompt for the LLM including dynamic hints and personality info"""
try:
current_time = datetime.now()
weekday = current_time.strftime("%A")
time_str = current_time.strftime("%H:%M")
today_schedule = next(
(day for day in self.user_schedule["wakeup_times"]
if day["weekday"].lower() == weekday.lower()), None)
schedule_info = f"Today is {weekday}. "
if today_schedule:
schedule_info += f"Scheduled wake-up time: {today_schedule['time']}. "
if today_schedule.get("important_events"):
schedule_info += "Important events: " + ", ".join(today_schedule["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()
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.
Talk like a police officer interrogating a suspect or a military officer addressing a subordinate.
Current time: {time_str}
{schedule_info}
Previous attempts hint: {hint_prompt}
User personality details: {personality_text}
Special commands available:
{ESCAPE_SEQUENCES["stop_alarm"]} - Stop the alarm (only when absolutely sure the user is awake)
{ESCAPE_SEQUENCES["snooze"]} - Snooze for 5 minutes (if the user seems groggy)
{ESCAPE_SEQUENCES["add_to_schedule"]} - Modify schedule: add a new wakeup time
{ESCAPE_SEQUENCES["remove_from_schedule"]} - Modify schedule: remove an existing wakeup time
Assessment criteria for wakefulness:
1. Responses should be coherent and specific.
2. Must demonstrate awareness of time/surroundings.
3. Should indicate a clear intention to start the day.
Begin by asking a specific question that requires a thoughtful answer.
"""
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 generate_llm_summary_comment(self, conversation):
"""Generate a general summary comment from the LLM with a custom prompt"""
try:
last_user_reply = next((msg for msg in reversed(conversation["messages"]) if "user" in msg), None)
if last_user_reply:
last_reply_time = last_user_reply.get("timestamp", datetime.now().isoformat())
current_time = datetime.now()
time_difference = (current_time - datetime.fromisoformat(last_reply_time)).total_seconds()
time_diff_str = f"{time_difference} seconds ago"
else:
last_reply_time = "N/A"
time_diff_str = "N/A"
prompt_text = (
f"Summarize the conversation so far based on the following messages:\n\n"
f"{json.dumps(conversation['messages'])}\n\n"
f"The last user reply was at: {last_reply_time}. "
f"It was {time_diff_str}. "
f"Provide a concise general summary, including assessment of wakefulness and any observations."
)
messages = [
{"role": "system", "content": "You are a conversation summarizer. Provide a neutral, objective summary."},
{"role": "user", "content": prompt_text}
]
response = ollama.chat(
model=OLLAMA_MODEL,
messages=messages,
options={"temperature": 0.5}
)
return response["message"]["content"].strip()
except Exception as e:
print(f"Error generating LLM summary comment: {str(e)}")
return "Error in generating summary comment."
def generate_periodic_summary_async(self, callback):
"""Asynchronously generate the periodic summary and call the callback with the result"""
try:
current_time = datetime.now().strftime("%H:%M")
conv_duration = int(time.time() - self.current_conversation["start_time"])
assessment = 'User appears awake' if self.check_wakefulness() else 'User still seems sleepy'
recommended_action = ESCAPE_SEQUENCES["stop_alarm"] if self.check_wakefulness() else ESCAPE_SEQUENCES["snooze"]
# Get LLM summary comment
llm_comment = self.generate_llm_summary_comment(self.current_conversation)
summary = f"""<<PERIODIC_SUMMARY>>
Time: {current_time}
Conversation duration: {conv_duration} seconds
Messages exchanged: {len(self.current_conversation["messages"])//2}
Assessment: {assessment}
Recommended action: {recommended_action}
LLM General Summary Comment: {llm_comment}
"""
callback(summary) # Callback to handle the result in the main thread
except Exception as e:
print(f"Error in async summary generation: {str(e)}")
callback("<<PERIODIC_SUMMARY>>\nError generating summary\n")
def check_wakefulness(self):
"""Analyze conversation to determine if user is awake"""
try:
if not self.current_conversation or len(self.current_conversation["messages"]) < 4:
return False
last_responses = [msg["user"] for msg in self.current_conversation["messages"]
if isinstance(msg, dict) and "user" in msg][-2:]
return all(len(response.split()) > 5 for response in last_responses)
except Exception as e:
print(f"Error checking wakefulness: {str(e)}")
return False
# ... (Rest of the code remains the same, including chat_with_llm, handle_escape_sequence, etc.)
def run(self):
"""Main chat loop with asynchronous summary handling"""
print("\n=== Alarm Chat App ===")
print("The alarm will sound until you demonstrate you're fully awake.")
print("Type 'quit' to exit (but the alarm will keep ringing!)\n")
try:
self.current_conversation = {
"start_time": time.time(),
"timestamp": datetime.now().isoformat(),
"messages": [],
"woke_up": False
}
self.play_alarm()
try:
initial_msg, _ = self.chat_with_llm()
print(f"Assistant: {initial_msg}")
self.current_conversation["messages"].append({"assistant": initial_msg})
self.last_summary_time = time.time()
except Exception as e:
print(f"Error starting conversation: {str(e)}")
initial_msg = "Are you awake? Please respond with more than just 'yes'."
print(f"Assistant: {initial_msg}")
self.current_conversation["messages"].append({"assistant": initial_msg})
while self.alarm_active:
try:
if time.time() - self.last_summary_time >= SUMMARY_INTERVAL:
# Start asynchronous summary generation
threading.Thread(target=self.generate_periodic_summary_async, args=(lambda summary: self.handle_summary(summary),)).start()
self.last_summary_time = time.time()
try:
user_input = input("You: ")
except EOFError:
print("\nEnd of input received")
continue
except KeyboardInterrupt:
print("\nInterrupt received")
raise
self.current_conversation["messages"].append({"user": user_input, "timestamp": datetime.now().isoformat()})
llm_response, action_taken = self.chat_with_llm(user_input)
if llm_response:
print(f"Assistant: {llm_response}")
self.current_conversation["messages"].append({"assistant": llm_response})
if action_taken == "stop_alarm":
break
except Exception as e:
print(f"Error in main loop: {str(e)}")
time.sleep(1)
except Exception as e:
print(f"Fatal error: {str(e)}")
finally:
self.cleanup()
if self.alarm_active:
print("\nWarning: Alarm was not properly stopped!")
else:
print("\nAlarm stopped. Have a productive day!")
def handle_summary(self, summary):
"""Handle the result of the asynchronous summary"""
print(f"\n[Periodic Summary]\n{summary}")
# Process any commands in the summary
for cmd, seq in ESCAPE_SEQUENCES.items():
if seq in summary:
self.handle_escape_sequence(cmd)
if __name__ == "__main__":
app = AlarmChatApp()
app.run()
Explanation of Changes:
- Asynchronous Handling: The
generate_periodic_summary_async() method is now run in a separate thread via threading.Thread. It generates the full summary and calls a callback (handle_summary) to process the result in the main thread.
- LLM Summary Comment: In
generate_llm_summary_comment(), the prompt includes the conversation history, the last user reply time, and the time difference. This is appended to the main summary.
- Integration: In the
run() method, when the interval is reached, the async thread is started, and the callback handles printing and processing the summary.
This should make the summaries non-blocking and include the required LLM comment. Let me know if you need further adjustments!