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 LINES total. 2. Structure: One sentence on Overall Health (Green/Amber/Red), one on the primary volume/breach driver, and one on a specific tactical recommendation. 3. Use bolding to highlight critical metrics or actions. Professional Markdown format. """ 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}" prompt = ChatPromptTemplate.from_template(ANALYTICS_PROMPT) chain = prompt | llm try: 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**: Service insights are currently being recalibrated following high telemetry intake. **Core metrics indicate stable flow.** Check back in 15 minutes for a fresh executive-level summary."