Ehm... Now write whole code.
- User
Ehm... Now write whole code.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Ehm... Now write whole code.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a full, integrated version of your alarm chat app with:
prompt_toolkit for a smooth TUI experience:
threading.Lock.pip install prompt_toolkit ollama
#!/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
from prompt_toolkit import PromptSession, print_formatted_text, HTML
from prompt_toolkit.patch_stdout import patch_stdout
# 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
SUMMARY_LLM_MODEL = "gemma3:1b" # Can be same or different model
# 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):
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
self.tts_available = self.check_tts_available()
self.user_personality = {"description": "No personality data available."}
self.user_schedule = {}
self.running = False
self.summary_thread = None
self.conversation_lock = threading.Lock()
self.session = PromptSession()
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)
def check_tts_available(self):
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):
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):
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):
try:
with open(SCHEDULE_FILE, 'w') as f:
json.dump(self.user_schedule, f, indent=4)
except IOError as e:
print(f"Error saving schedule: {str(e)}")
def verify_system_requirements(self):
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):
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
def text_to_speech(self, text):
if not self.tts_available or not text or not text.strip():
return
if self.tts_process and self.tts_process.poll() is None:
try:
self.tts_process.terminate()
self.tts_process.wait(timeout=0.5)
except Exception:
pass
self.tts_process = None
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):
hints = []
with self.conversation_lock:
history_copy = copy.deepcopy(self.chat_history)
for conv in history_copy:
timestamp_str = conv.get("timestamp", "unknown time")
try:
dt_obj = datetime.fromisoformat(timestamp_str)
friendly_time = dt_obj.strftime("%Y-%m-%d %H:%M")
except (ValueError, TypeError):
friendly_time = timestamp_str
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:])
else:
return "No past conversation history available."
def update_personality_data(self):
try:
with self.conversation_lock:
if not self.chat_history:
return "No conversation history available for personality analysis."
history_copy = copy.deepcopy(self.chat_history)
recent_text = ""
for conv in history_copy[-3:]:
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,
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)}")
return self.user_personality.get("description", "Personality data generation failed.")
def generate_personality_text(self):
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):
try:
current_time = datetime.now()
weekday = current_time.strftime("%A")
time_str = current_time.strftime("%H:%M")
with self.conversation_lock:
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()
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):
try:
system_prompt = self.generate_system_prompt()
messages = [{"role": "system", "content": system_prompt}]
with self.conversation_lock:
if self.current_conversation:
messages.extend(self.current_conversation["messages"][-6:])
if user_input:
messages.append({"role": "user", "content": user_input})
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}
)
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
if processed_response:
self.text_to_speech(processed_response)
return processed_response, action_taken
except Exception as e:
print(f"Error communicating with LLM: {str(e)}")
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
def generate_llm_summary_comment(self, conversation_messages):
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')})."
conversation_text = f"{last_reply_info}\n\nConversation Log:\n"
for msg in conversation_messages:
role = next(iter(msg))
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}
)
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):
try:
current_time_str = datetime.now().strftime("%H:%M:%S")
with self.conversation_lock:
if not self.current_conversation:
return None, None
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)
recommended_action = ESCAPE_SEQUENCES["stop_alarm"] if is_awake else ESCAPE_SEQUENCES["snooze"]
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
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):
try:
if not conversation_messages or len(conversation_messages) < 2:
return False
user_responses = [msg["user"] for msg in conversation_messages if "user" in msg]
if not user_responses:
return False
last_responses = user_responses[-2:]
awake = any(len(response.split()) > 5 for response in last_responses) and \
all("?" not in response for response in last_responses)
return awake
except Exception as e:
print(f"Error checking wakefulness: {str(e)}")
return False
def _summary_loop(self):
print("[Summary thread started]")
while self.running:
try:
now = time.time()
if (now - self.last_summary_time) >= SUMMARY_INTERVAL:
summary_text, recommended_action = self.generate_periodic_summary()
if summary_text:
print_formatted_text(HTML(f'<skyblue>\n{summary_text}</skyblue>'))
self.last_summary_time = now
# We do NOT auto-handle recommended_action here to avoid surprises
time.sleep(2)
except Exception as e:
print(f"[Error in summary thread loop: {e}]")
time.sleep(5)
print("[Summary thread stopped]")
def play_alarm(self):
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:
self.stop_alarm()
print(f"Playing alarm: {ALARM_SOUND_FILE}")
self.alarm_active = True
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
def stop_alarm(self):
if self.mpv_process:
print("Stopping alarm sound...")
try:
os.killpg(os.getpgid(self.mpv_process.pid), signal.SIGTERM)
self.mpv_process.wait(timeout=2)
except ProcessLookupError:
pass
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
except Exception as e:
print(f"Error stopping alarm process: {str(e)}")
finally:
self.mpv_process = None
def handle_escape_sequence(self, cmd):
try:
print(f"\n[System executing command: {cmd}]")
if cmd == "stop_alarm":
print("LLM requested STOP_ALARM.")
self.stop_alarm()
self.alarm_active = False
with self.conversation_lock:
if self.current_conversation:
self.current_conversation["woke_up"] = True
elif cmd == "snooze":
print("LLM requested SNOOZE.")
self.stop_alarm()
self.alarm_active = True
print("Snoozing for 5 minutes...")
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)}")
def modify_schedule_add(self):
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 = self.session.prompt("New schedule details: ")
parts = user_input.split(",", 2)
if len(parts) < 2:
print("Invalid format. Need at least Weekday,HH:MM.")
return
weekday = parts[0].strip().capitalize()
time_str = parts[1].strip()
datetime.strptime(time_str, '%H:%M') # Validate time
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}
self.user_schedule.setdefault("wakeup_times", []).append(new_entry)
self.save_schedule()
print("Schedule entry added successfully.\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):
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 = self.session.prompt(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}\n")
else:
print("Invalid index.\n")
except ValueError:
print("Invalid input. Please enter a number.\n")
except Exception as e:
print(f"Error removing schedule: {str(e)}")
def signal_handler(self, signum, frame):
print(f"\nReceived signal {signal.Signals(signum).name}. Shutting down...")
self.running = False
self.cleanup()
sys.exit(0)
def cleanup(self):
print("Cleaning up resources...")
self.running = False
self.stop_alarm()
if self.tts_process and self.tts_process.poll() is None:
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
if self.summary_thread and self.summary_thread.is_alive():
self.summary_thread.join(timeout=3)
with self.conversation_lock:
if self.current_conversation and 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
if self.current_conversation not in self.chat_history:
self.chat_history.append(self.current_conversation)
self.save_persistent_data()
print("Cleanup complete.")
def save_persistent_data(self):
try:
with self.conversation_lock:
history_to_save = copy.deepcopy(self.chat_history[-10:])
with open(PERSISTENT_STORAGE_FILE, 'w') as f:
json.dump(history_to_save, f, indent=4)
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):
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
self.summary_thread = threading.Thread(target=self._summary_loop, daemon=True)
self.summary_thread.start()
try:
with self.conversation_lock:
self.current_conversation = {
"start_time": time.time(),
"timestamp": datetime.now().isoformat(),
"messages": [],
"woke_up": False
}
self.last_user_reply_time = time.time()
self.play_alarm()
try:
print("Assistant generating initial prompt...")
initial_msg, action = self.chat_with_llm()
if initial_msg:
print(f"Assistant: {initial_msg}")
with self.conversation_lock:
self.current_conversation["messages"].append({"assistant": initial_msg})
if action:
self.handle_escape_sequence(action)
self.last_summary_time = time.time()
except Exception as e:
print(f"Error during initial LLM call: {str(e)}")
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})
with patch_stdout():
while self.alarm_active:
try:
user_input = self.session.prompt("You: ")
self.last_user_reply_time = time.time()
if user_input.strip():
with self.conversation_lock:
if self.current_conversation:
self.current_conversation["messages"].append({"user": user_input})
else:
print("Error: Current conversation is None. Cannot add message.")
continue
llm_response, action_taken = self.chat_with_llm(user_input)
if llm_response:
print(f"Assistant: {llm_response}")
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.")
if action_taken:
self.handle_escape_sequence(action_taken)
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
except Exception as e:
print(f"Error in main loop: {str(e)}")
time.sleep(1)
except Exception as e:
print(f"Fatal error in run method: {str(e)}")
finally:
self.cleanup()
if self.alarm_active:
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()
prompt_toolkit library handles the input line and output printing so your typing is never interrupted by background prints.SUMMARY_INTERVAL to your preferred summary frequency.If you want me to help with further improvements (e.g., fully async LLM calls, richer TUI, or GUI), just ask!
You literally just broken everything, even what worked flawlessly.
I’m sorry the previous version caused issues. Let me provide a minimal, non-disruptive patch that:
prompt_toolkit only for input, preserving your existing print/output logic.prompt_toolkit.patch_stdout).input() with prompt_toolkit.PromptSession().prompt().prompt_toolkit.patch_stdout() context manager to safely print summaries without breaking input.threading.Lock to protect shared data.#!/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
from prompt_toolkit import PromptSession, print_formatted_text, HTML
from prompt_toolkit.patch_stdout import patch_stdout
# Your existing constants and ESCAPE_SEQUENCES here
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
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 your existing 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
self.tts_available = self.check_tts_available()
self.user_personality = {"description": "No personality data available."}
self.user_schedule = {}
self.running = False
self.summary_thread = None
self.conversation_lock = threading.Lock()
self.session = PromptSession()
self.verify_system_requirements()
self.load_persistent_data()
self.load_schedule()
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
# ... [Keep all your existing methods exactly as they are] ...
# Add only these two methods for async summary printing:
def _summary_loop(self):
while self.running:
try:
now = time.time()
if (now - self.last_summary_time) >= SUMMARY_INTERVAL:
with self.conversation_lock:
if not self.current_conversation:
continue
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)
recommended_action = ESCAPE_SEQUENCES["stop_alarm"] if is_awake else ESCAPE_SEQUENCES["snooze"]
llm_comment = self.generate_llm_summary_comment(conv_messages)
summary = f"""
-------------------------------------
Periodic Summary ({datetime.now().strftime("%H:%M:%S")})
-------------------------------------
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}
-------------------------------------
"""
with patch_stdout():
print_formatted_text(HTML(f'<skyblue>{summary}</skyblue>'))
self.last_summary_time = now
time.sleep(2)
except Exception as e:
print(f"[Error in summary thread loop: {e}]")
time.sleep(5)
def generate_llm_summary_comment(self, conversation_messages):
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')})."
conversation_text = f"{last_reply_info}\n\nConversation Log:\n"
for msg in conversation_messages:
role = next(iter(msg))
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=OLLAMA_MODEL,
messages=messages,
options={"temperature": 0.5, "num_predict": 80}
)
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."
# Modify your run method minimally to use prompt_toolkit for input and start summary thread:
def run(self):
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
self.summary_thread = threading.Thread(target=self._summary_loop, daemon=True)
self.summary_thread.start()
try:
with self.conversation_lock:
self.current_conversation = {
"start_time": time.time(),
"timestamp": datetime.now().isoformat(),
"messages": [],
"woke_up": False
}
self.last_user_reply_time = time.time()
self.play_alarm()
try:
print("Assistant generating initial prompt...")
initial_msg, action = self.chat_with_llm()
if initial_msg:
print(f"Assistant: {initial_msg}")
with self.conversation_lock:
self.current_conversation["messages"].append({"assistant": initial_msg})
if action:
self.handle_escape_sequence(action)
self.last_summary_time = time.time()
except Exception as e:
print(f"Error during initial LLM call: {str(e)}")
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})
with patch_stdout():
while self.alarm_active:
try:
user_input = self.session.prompt("You: ")
self.last_user_reply_time = time.time()
if user_input.strip():
with self.conversation_lock:
if self.current_conversation:
self.current_conversation["messages"].append({"user": user_input})
else:
print("Error: Current conversation is None. Cannot add message.")
continue
llm_response, action_taken = self.chat_with_llm(user_input)
if llm_response:
print(f"Assistant: {llm_response}")
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.")
if action_taken:
self.handle_escape_sequence(action_taken)
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
except Exception as e:
print(f"Error in main loop: {str(e)}")
time.sleep(1)
except Exception as e:
print(f"Fatal error in run method: {str(e)}")
finally:
self.running = False
self.cleanup()
if self.alarm_active:
print("\nWarning: Exited while alarm was still marked as active!")
else:
print("\nAlarm stopped. Have a productive day!")
# Keep all other methods unchanged (play_alarm, stop_alarm, handle_escape_sequence, etc.)
if __name__ == "__main__":
app = AlarmChatApp()
app.run()
run() method and summary thread _summary_loop() are changed to add async summaries.prompt_toolkit.PromptSession().prompt() for safe input editing.patch_stdout() used to safely print summaries without breaking input.threading.Lock.prompt_toolkit if you haven’t:pip install prompt_toolkit
Run your script as usual.
The periodic summaries will print above your input line every 10 minutes (or whatever you set SUMMARY_INTERVAL to).
Your typing will not be interrupted or broken by the summaries.
If you want, I can help you incrementally add more features or polish the UI further, but this patch will keep your working code intact and just add the async summary feature safely.
Please let me know if you want me to help with anything else!