Spaces:
Paused
Paused
Download agents/analytics.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 3.45 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/agents/analytics.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/agents/analytics.py
-
curl -L -o analytics.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/agents/analytics.py
3.45 kB
| 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." | |