You're right on several points. Let me address them:
-
Preserving Features: Yes, we should keep all existing features while adding the new ones.
-
Thread Communication: The current implementation doesn't properly handle thread communication. We need a proper thread-safe queue or event system to communicate between the summary thread and main thread.
-
Input Interruption: Good catch. We need a proper TUI (Text User Interface) to handle:
- Non-interrupting async messages
- Multi-line input
- Cursor movement
- History navigation
Here's a suggestion using prompt_toolkit for the TUI part and proper thread communication:
from prompt_toolkit import PromptSession
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.layout import Layout
from prompt_toolkit.widgets import TextArea
from prompt_toolkit.application import Application
from queue import Queue
import threading
# Add these to your imports
# Rest of the imports remain the same...
class AlarmChatApp:
def __init__(self):
# Existing initialization...
# Add these new attributes
self.message_queue = Queue()
self.summary_thread = None
self.prompt_session = PromptSession()
self.summary_running = False
# ... (existing methods remain the same)
def start_summary_thread(self):
"""Start the periodic summary thread"""
if self.summary_thread is None or not self.summary_thread.is_alive():
self.summary_running = True
self.summary_thread = threading.Thread(target=self.summary_loop)
self.summary_thread.daemon = True
self.summary_thread.start()
def summary_loop(self):
"""Continuous loop for generating summaries"""
while self.summary_running:
try:
if time.time() - self.last_summary_time >= SUMMARY_INTERVAL:
summary = self.generate_periodic_summary()
llm_comment = self.generate_llm_summary_comment(self.current_conversation)
full_summary = f"{summary}\n\nLLM Analysis:\n{llm_comment}"
# Queue the summary for display
self.message_queue.put(("summary", full_summary))
self.last_summary_time = time.time()
time.sleep(1) # Prevent tight loop
except Exception as e:
print(f"Error in summary loop: {str(e)}")
def display_message(self, message, preserve_input=True):
"""Display a message while preserving user input"""
with patch_stdout():
# Clear the current input line
print("\033[2K\r", end="")
# Print the message
print(message)
# If there's current input, redisplay it
if preserve_input and self.current_input:
print(f"You: {self.current_input}", end="", flush=True)
def run(self):
"""Main chat loop with TUI support"""
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")
# Initialize TUI
self.current_input = ""
session = self.prompt_session
try:
# Start the summary thread
self.start_summary_thread()
# Initialize conversation
self.current_conversation = {
"start_time": time.time(),
"timestamp": datetime.now().isoformat(),
"messages": [],
"woke_up": False
}
self.play_alarm()
# Initial message
try:
initial_msg, _ = self.chat_with_llm()
self.display_message(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'."
self.display_message(f"Assistant: {initial_msg}")
self.current_conversation["messages"].append({"assistant": initial_msg})
while self.alarm_active:
try:
# Check for queued messages
while not self.message_queue.empty():
msg_type, message = self.message_queue.get_nowait()
if msg_type == "summary":
self.display_message(f"\n[Periodic Summary]\n{message}")
# Get user input with prompt_toolkit
with patch_stdout():
user_input = session.prompt(
"You: ",
multiline=True, # Enable multi-line input
enable_history_search=True, # Enable history navigation
enable_suspend=True, # Allow Ctrl+Z
enable_open_in_editor=True, # Allow opening in external editor
wrap_lines=True # Wrap long lines
)
# Process the input
if user_input.strip():
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:
self.display_message(f"Assistant: {llm_response}")
self.current_conversation["messages"].append({"assistant": llm_response})
if action_taken == "stop_alarm":
break
except EOFError:
print("\nEnd of input received")
continue
except KeyboardInterrupt:
print("\nInterrupt received")
raise
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:
# Cleanup
self.summary_running = False
if self.summary_thread:
self.summary_thread.join(timeout=1)
self.cleanup()
if self.alarm_active:
print("\nWarning: Alarm was not properly stopped!")
else:
print("\nAlarm stopped. Have a productive day!")
This updated version:
-
Uses prompt_toolkit for TUI:
- Proper multi-line input support
- History navigation
- Cursor movement
- Non-interrupting messages
-
Implements proper thread communication:
- Uses a Queue for thread-safe message passing
- Summary thread runs continuously and queues updates
- Main thread checks queue and displays messages without interrupting input
-
Preserves all existing features:
- All previous functionality remains intact
- Adds new features on top of existing ones
-
Handles async messages properly:
- Messages are queued and displayed at appropriate times
- Input is preserved when async messages appear
To use this, you'll need to install prompt_toolkit:
pip install prompt_toolkit
This is a basic implementation and could be enhanced further with:
- Better TUI layout (split windows for chat/summary)
- Color support
- Better input handling
- More sophisticated thread communication
- Better error handling
Would you like me to elaborate on any of these aspects or make further adjustments?