Spaces:
Paused

File size: 3,446 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
6ce1162
5eb4857
6ce1162
 
 
 
 
5eb4857
 
e4d72a7
 
 
 
 
 
5eb4857
e4d72a7
 
5eb4857
 
 
 
 
6ce1162
5eb4857
 
 
6ce1162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
331f592
 
 
7724a94
331f592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4d72a7
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
from typing import Any, Dict, List
from langchain_core.prompts import ChatPromptTemplate
from core.llm import get_llm

ANALYTICS_PROMPT = """
You are a Senior Service Delivery Manager. Analyze the FOLLOWING metrics and recent ticket data (last 48h).
Generate a concise, high-impact "Executive Health Narrative" for the workspace lead.

Current Metrics:
- SLA Compliance: {sla_rate}%
- Breached Count: {breaches}
- Total Workload (48h): {ticket_count}

Granular Intelligence (Top 20 Recent):
{recent_data}

Operational Scale Summary (Remainder):
{summary_data}

REPORT RULES:
1. MAXIMUM 4-5 paragraphs/lines.
2. Structure: 
   - Heading: ## Operational Pulse
   - One sentence on Overall Health (Green/Amber/Red).
   - Heading: ## Tactical Vectors
   - One on the primary volume/breach driver and a tactical recommendation.
3. Use bolding to highlight critical metrics or actions. Professional Markdown format.
4. ZERO DATA HANDLING: If ticket_count is 0, report that the workspace is currently stable with no new incidents.
5. NO ASCII BOX ART.
"""

async def generate_service_insights(metrics: Dict[str, Any], tickets: List[Dict[str, Any]]) -> str:
    """
    Generates an executive summary of service performance using LLM analytics.
    Features Hybrid Aggregation: Top 20 detailed + Volume Summary for the rest.
    """
    llm = get_llm()
    
    # 1. Split for Hybrid Analysis
    recent = tickets[:20]
    remainder = tickets[20:]
    
    # 2. Format Granular Data
    recent_formatted = "\n".join([
        f"- [{t['priority']}] Category: {t.get('category') or 'General'} (Active for {t['duration_mins']:.1f}m)" 
        for t in recent
    ]) if recent else "No recent ticket data available."
    
    # 3. Aggregate Remainder Metrics
    summary_formatted = "Full 48h volume accounted for in granular view."
    if remainder:
        from collections import Counter
        cat_counts = Counter(t.get('category') or 'General' for t in remainder)
        prio_counts = Counter(t.get('priority') or 'Unknown' for t in remainder)
        
        cat_str = ", ".join([f"{c}: {n}" for c, n in cat_counts.most_common(3)])
        prio_str = ", ".join([f"{p}: {n}" for p, n in prio_counts.items()])
        
        summary_formatted = f"Total Remainder: {len(remainder)} tickets.\nTop Categories: {cat_str}\nPriority Mix: {prio_str}"
    
    # Single-Attempt Strategy for UI Responsiveness
    try:
        # Use a tight timeout to prevent parking backend threads during rate limits
        llm = get_llm(timeout=12) 
        
        prompt = ChatPromptTemplate.from_template(ANALYTICS_PROMPT)
        chain = prompt | llm
        
        response = await chain.ainvoke({
            "sla_rate": round(metrics.get("sla_compliance_rate", 0) * 100, 1),
            "breaches": metrics.get("breached_tickets", 0),
            "ticket_count": len(tickets),
            "recent_data": recent_formatted,
            "summary_data": summary_formatted
        })
        return response.content
    except Exception as e:
        from core.logging import get_logger
        logger = get_logger(__name__)
        logger.error(f"AI Insight Generation Failed: {str(e)}")
        # Graceful degradation logic
        return "### ✨ System Narrative\n\nService insights are currently being recalibrated following high telemetry intake.\n\n**Core metrics indicate stable flow.**\n\nCheck back in a few minutes for a fresh executive-level summary."