Spaces:
Paused

File size: 3,047 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4405ca9
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import os
import sys
from datetime import datetime

# Add project root to sys.path
sys.path.append(os.getcwd())

# Ensure all models are registered and SQLAlchemy is ready
from sqlalchemy import select
from core.database import async_session_factory
from models.ai_interaction import AIInteraction
from core.config import get_settings

settings = get_settings()

GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"
YELLOW = "\033[93m"
RESET = "\033[0m"
BOLD = "\033[1m"

def format_time(dt: datetime):
    return dt.strftime("%H:%M:%S")

async def get_recent_ai_tasks(limit=10):
    async with async_session_factory() as db:
        stmt = select(AIInteraction).order_by(AIInteraction.created_at.desc()).limit(limit)
        result = await db.execute(stmt)
        return result.scalars().all()

async def monitor_loop():
    print(f"{BOLD}{CYAN}=== AI PROCESSING DASHBOARD (RESILIENT) ==={RESET}")
    print(f"Monitoring: {settings.REDIS_URL}")
    print("Schema status: Synchronized")
    print("Press Ctrl+C to stop.\n")
    
    seen_ids = set()
    
    while True:
        try:
            tasks = await get_recent_ai_tasks()
            
            # Print new tasks (newest last)
            for task in reversed(tasks):
                if task.id not in seen_ids:
                    # Robust status handling
                    status = (task.status or "success").upper()
                    status_color = GREEN if status == "SUCCESS" else RED
                    
                    # Robust duration handling
                    duration_data = task.duration_ms or {}
                    duration = duration_data.get("total", "??")
                    
                    print(f"[{format_time(task.created_at)}] "
                          f"{BOLD}{CYAN}{task.agent_name:<20}{RESET} | "
                          f"Ticket: {str(task.ticket_id)[:8]} | "
                          f"Status: {status_color}{status:<8}{RESET} | "
                          f"Duration: {duration}ms")
                    
                    if status == "ERROR":
                        error_detail = (task.output_data or {}).get("error", "Unknown Fault")
                        print(f"  {RED}FAULT DETAIL: {error_detail}{RESET}")
                    
                    seen_ids.add(task.id)
            
            # Keep seen_ids from growing too large
            if len(seen_ids) > 100:
                seen_ids = set(list(seen_ids)[-50:])
                
            await asyncio.sleep(2)
            
        except KeyboardInterrupt:
            print(f"\n{BOLD}{YELLOW}Dashboard stopped by user.{RESET}")
            break
        except Exception as e:
            # This handles cases where SQLAlchemy mappers are still initializing
            print(f"{YELLOW}Waiting for database synchronization... ({str(e)[:50]}){RESET}")
            await asyncio.sleep(5)

if __name__ == "__main__":
    try:
        asyncio.run(monitor_loop())
    except KeyboardInterrupt:
        pass
    finally:
        print(f"{RESET}")