Spaces:
3SCError404
/
Paused

File size: 4,153 Bytes
5eb4857
4405ca9
5eb4857
4405ca9
5eb4857
 
6130eba
5eb4857
 
 
4405ca9
5eb4857
 
 
 
 
 
f3a0c24
 
a27a4ab
5eb4857
 
 
 
 
 
1c89e32
5eb4857
f3a0c24
 
 
5eb4857
1c89e32
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4405ca9
5eb4857
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
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
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
from typing import Any, List, Dict
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from datetime import datetime, timedelta
import time
from core.deps import get_db, get_current_staff_user, get_current_super_admin, get_arq_pool
from core.config import get_settings
from models.ai_workflow import AIWorkflow
from models.ai_interaction import AIInteraction
from models.meta_infra_health import MetaInfraHealth
from schemas.system import AIWorkflowRead, AIInteractionRead, MetaInfraHealthRead
from arq.connections import ArqRedis

router = APIRouter()
settings = get_settings()

from core.observability import check_infra_health

@router.get("/status/", dependencies=[Depends(get_current_super_admin)])
async def get_system_status(
    db: AsyncSession = Depends(get_db),
    arq_pool: ArqRedis = Depends(get_arq_pool)
) -> Dict[str, Any]:
    """
    Aggregates real-time health metrics for the core infrastructure nodes.
    Calculates latency on-demand for accurate dashboard reporting.
    """
    # Use the unified health helper for DB and Redis
    infra_health = await check_infra_health(db, arq_pool)
    
    results = {
        "database": {
            "status": infra_health["database"], 
            "latency_ms": infra_health.get("database_latency", 0.0)
        },
        "redis": {
            "status": infra_health["redis"], 
            "latency_ms": infra_health.get("redis_latency", 0.0), 
            "pending_jobs": infra_health.get("pending_jobs", 0)
        },
        "ollama": {"status": "DOWN", "latency_ms": 0.0},
        "timestamp": datetime.utcnow()
    }

    # 3. Ollama Check
    start_time = time.perf_counter()
    try:
        import httpx
        async with httpx.AsyncClient(timeout=2.0) as client:
            resp = await client.get(f"{settings.OLLAMA_BASE_URL}/api/tags")
            if resp.status_code == 200:
                results["ollama"]["status"] = "UP"
                results["ollama"]["latency_ms"] = round((time.perf_counter() - start_time) * 1000, 2)
    except Exception:
        results["ollama"]["status"] = "DOWN"

    return results

from uuid import UUID
from typing import Any, Dict, Optional

@router.get("/workflows/", response_model=List[AIWorkflowRead], dependencies=[Depends(get_current_staff_user)])
async def get_recent_workflows(
    db: AsyncSession = Depends(get_db),
    ticket_id: Optional[UUID] = None,
    offset: int = 0,
    limit: int = 20
) -> List[AIWorkflow]:
    """
    Retrieves AI workflows with optional ticket filtering and pagination.
    """
    stmt = select(AIWorkflow)
    
    if ticket_id:
        stmt = stmt.where(AIWorkflow.entity_id == ticket_id)
        
    stmt = stmt.order_by(AIWorkflow.updated_at.desc()).offset(offset).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()

@router.get("/interactions/", response_model=List[AIInteractionRead], dependencies=[Depends(get_current_staff_user)])
async def get_recent_interactions(
    db: AsyncSession = Depends(get_db),
    ticket_id: Optional[UUID] = None,
    offset: int = 0,
    limit: int = 25
) -> List[AIInteraction]:
    """
    Retrieves granular AI interaction traces with optional ticket filtering and pagination.
    """
    stmt = select(AIInteraction)
    
    if ticket_id:
        stmt = stmt.where(AIInteraction.ticket_id == ticket_id)
        
    stmt = stmt.order_by(AIInteraction.created_at.desc()).offset(offset).limit(limit)
    
    result = await db.execute(stmt)
    return result.scalars().all()

@router.get("/history/", response_model=List[MetaInfraHealthRead], dependencies=[Depends(get_current_staff_user)])
async def get_performance_history(
    db: AsyncSession = Depends(get_db)
) -> List[MetaInfraHealth]:
    """
    Retrieves the last 24 hours of infrastructure health data.
    """
    since = datetime.utcnow() - timedelta(hours=24)
    stmt = (
        select(MetaInfraHealth)
        .where(MetaInfraHealth.created_at >= since)
        .order_by(MetaInfraHealth.created_at.asc())
    )
    result = await db.execute(stmt)
    return result.scalars().all()