File size: 8,835 Bytes
99b8067 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
#!/usr/bin/env python3
"""
Test script for ATLES Autonomous Learning Daemon
This script demonstrates the complete learning pipeline:
1. Start daemon
2. Simulate chat sessions
3. Process sessions
4. View learning results
"""
import time
import json
from pathlib import Path
from datetime import datetime
from atles.autonomous_learning_daemon import (
start_daemon,
stop_daemon,
get_daemon,
mark_session_complete
)
from atles.daemon_integration import SessionTracker
def print_header(text):
"""Print formatted header"""
print("\n" + "="*60)
print(f" {text}")
print("="*60 + "\n")
def simulate_chat_session(session_num: int, message_count: int = 6):
"""Simulate a chat session"""
print(f"π Simulating chat session {session_num}...")
tracker = SessionTracker(auto_start_daemon=False)
session_id = tracker.start_session(f"test_session_{session_num:03d}")
# Simulate conversation
conversations = [
("What is Python?", "Python is a high-level programming language known for its simplicity..."),
("Show me an example", "Here's a simple example: print('Hello, World!')"),
("How do I create a function?", "To create a function in Python, use the 'def' keyword..."),
("What about classes?", "Classes in Python are defined using the 'class' keyword..."),
("Can you explain decorators?", "Decorators are a way to modify function behavior..."),
("What's the difference between list and tuple?", "Lists are mutable while tuples are immutable..."),
]
for i, (question, answer) in enumerate(conversations[:message_count]):
print(f" User: {question[:50]}...")
tracker.log_message("user", question)
print(f" ATLES: {answer[:50]}...")
tracker.log_message("assistant", answer)
if i < message_count - 1:
time.sleep(0.5) # Simulate typing delay
# Add metadata
tracker.set_metadata("platform", "test_script")
tracker.set_metadata("quality_rating", 5)
print(f"β
Session {session_id} complete ({tracker.get_message_count()} messages)\n")
# End session (triggers learning)
tracker.end_session()
return session_id
def wait_for_processing(max_wait: int = 30):
"""Wait for daemon to process sessions"""
print("β³ Waiting for daemon to process sessions...")
start_time = time.time()
daemon = get_daemon()
while time.time() - start_time < max_wait:
status = daemon.get_status()
queue_size = status['sessions_in_queue']
if queue_size == 0:
print("β
All sessions processed!\n")
return True
print(f" Queue: {queue_size} sessions remaining...")
time.sleep(2)
print("β οΈ Timeout waiting for processing\n")
return False
def show_daemon_status():
"""Show current daemon status"""
daemon = get_daemon()
status = daemon.get_status()
print("π Daemon Status:")
print(f" Running: {'β
Yes' if status['is_running'] else 'β No'}")
print(f" Uptime: {status['uptime_hours']:.2f} hours")
print(f" Queue: {status['sessions_in_queue']} sessions")
print()
stats = status['stats']
print("π Learning Statistics:")
print(f" Sessions Processed: {stats['sessions_processed']}")
print(f" Total Messages: {stats['total_messages']}")
print(f" Memory Items: {stats['total_memory_items']}")
print(f" Fine-Tunes: {stats['total_fine_tunes']}")
print()
def show_session_logs():
"""Show recent session logs"""
logs_dir = Path("atles_memory/learning_daemon/logs")
if not logs_dir.exists():
print("β οΈ No logs directory found\n")
return
# Find session logs
session_logs = sorted(logs_dir.glob("session_log_*.json"))
if not session_logs:
print("β οΈ No session logs found\n")
return
print(f"π Recent Session Logs ({len(session_logs)} total):\n")
# Show last 3 logs
for log_file in session_logs[-3:]:
try:
with open(log_file, 'r') as f:
log_data = json.load(f)
print(f" Session: {log_data['session_id']}")
print(f" Messages: {log_data['messages_count']}")
print(f" Memory Items: {log_data['memory_items_created']}")
print(f" Fine-Tuned: {'β
Yes' if log_data['fine_tune_applied'] else 'β No'}")
if log_data['fine_tune_loss']:
print(f" Loss: {log_data['fine_tune_loss']:.3f}")
if log_data['improvements']:
print(f" Improvements:")
for improvement in log_data['improvements'][:3]:
print(f" β’ {improvement}")
print()
except Exception as e:
print(f" β οΈ Error reading {log_file.name}: {e}\n")
def show_master_log():
"""Show master log summary"""
master_log = Path("atles_memory/learning_daemon/logs/master_log.jsonl")
if not master_log.exists():
print("β οΈ No master log found\n")
return
sessions = []
with open(master_log, 'r') as f:
for line in f:
try:
sessions.append(json.loads(line))
except:
pass
if not sessions:
print("β οΈ No sessions in master log\n")
return
print("π Master Log Summary:\n")
print(f" Total Sessions: {len(sessions)}")
total_messages = sum(s.get('messages_count', 0) for s in sessions)
print(f" Total Messages: {total_messages}")
avg_messages = total_messages / len(sessions) if sessions else 0
print(f" Avg Messages/Session: {avg_messages:.1f}")
fine_tuned = sum(1 for s in sessions if s.get('fine_tune_applied', False))
print(f" Fine-Tuned Sessions: {fine_tuned}")
if fine_tuned > 0:
fine_tune_rate = (fine_tuned / len(sessions)) * 100
print(f" Fine-Tune Rate: {fine_tune_rate:.1f}%")
total_memory = sum(s.get('memory_items_created', 0) for s in sessions)
print(f" Total Memory Items: {total_memory}")
print()
def main():
"""Main test execution"""
print("\n" + "="*60)
print(" π§ͺ ATLES Learning Daemon - Test Suite")
print("="*60)
print("\nThis test will:")
print(" 1. Start the learning daemon")
print(" 2. Simulate 3 chat sessions")
print(" 3. Process sessions automatically")
print(" 4. Show learning results")
print()
input("Press Enter to start...")
# Step 1: Start daemon
print_header("Step 1: Starting Learning Daemon")
daemon = start_daemon()
time.sleep(2)
show_daemon_status()
# Step 2: Simulate sessions
print_header("Step 2: Simulating Chat Sessions")
session_ids = []
for i in range(1, 4):
session_id = simulate_chat_session(i, message_count=6)
session_ids.append(session_id)
time.sleep(1)
print(f"β
Created {len(session_ids)} test sessions\n")
# Step 3: Wait for processing
print_header("Step 3: Processing Sessions")
wait_for_processing(max_wait=30)
# Give extra time for file writing
time.sleep(2)
# Step 4: Show results
print_header("Step 4: Learning Results")
# Show daemon status
show_daemon_status()
# Show session logs
show_session_logs()
# Show master log
show_master_log()
# Final summary
print_header("β
Test Complete!")
print("Check these locations for detailed logs:")
print(f" β’ Daemon log: atles_memory/learning_daemon/daemon.log")
print(f" β’ Session logs: atles_memory/learning_daemon/logs/")
print(f" β’ Statistics: atles_memory/learning_daemon/logs/daemon_stats.json")
print()
# Ask to stop daemon
choice = input("Stop daemon? (y/N): ").strip().lower()
if choice == 'y':
print("\nπ Stopping daemon...")
stop_daemon()
print("β
Daemon stopped\n")
else:
print("\nπ Daemon continues running in background")
print(" Stop it with: python -c \"from atles.autonomous_learning_daemon import stop_daemon; stop_daemon()\"")
print()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nβ οΈ Test interrupted by user")
print("π Stopping daemon...")
stop_daemon()
print("β
Cleanup complete\n")
except Exception as e:
print(f"\nβ Error: {e}")
print("π Stopping daemon...")
stop_daemon()
print("β
Cleanup complete\n")
raise
|