Spaces:
Sleeping
Sleeping
Download api/weekly.py from CloudPulse/ML_classifier: direct link, hf CLI and curl.
- Browser
- Download file 7.54 kB
-
https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/weekly.py
- Command line
-
hf download hf://spaces/CloudPulse/ML_classifier/api/weekly.py
-
curl -L -o weekly.py https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/weekly.py
7.54 kB
| """ | |
| CloudPulse — Weekly Intelligence Pass | |
| Aggregates classified incidents over a date range and produces a natural-language | |
| intelligence report. Powers the `POST /weekly` endpoint. | |
| Two input modes: | |
| 1. JSON list of classified incidents (provided by the caller) | |
| 2. SQL query against Mădălina's TimescaleDB (when DATABASE_URL is set) | |
| Mode 2 is preferred in production. Mode 1 is the contract Mădălina's pipeline | |
| uses today: she batches a week's worth of classifications and posts them. | |
| The aggregation logic is pure Python; only the natural-language summary uses | |
| Claude Haiku. Hotspot detection and trend deltas are deterministic. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| from collections import Counter, defaultdict | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timedelta | |
| from typing import Any | |
| from anthropic import Anthropic | |
| CLAUDE_MODEL = "claude-haiku-4-5-20251001" | |
| SUMMARY_SYSTEM_PROMPT = """You are an SRE intelligence analyst writing a weekly | |
| incident summary for engineering leadership. | |
| You will receive aggregated incident statistics. Produce a concise report with | |
| these sections: | |
| 1. **Executive summary** — 2-3 sentences on the week's overall reliability picture. | |
| 2. **Top hotspots** — which providers and services drove the most severe incidents. | |
| 3. **Trend** — how this week compares to the previous week (volume, severity). | |
| 4. **What to watch next week** — 2-3 specific things engineering should monitor. | |
| Be concrete. Reference numbers from the data. No hedging language. No generic | |
| SRE advice. Write as if briefing a CTO.""" | |
| class WeeklyAggregation: | |
| """Pure Python aggregation result. No LLM in here.""" | |
| period_start : str | |
| period_end : str | |
| total_incidents: int | |
| severity_counts: dict | |
| provider_severity_matrix: dict # provider -> severity -> count | |
| service_severity_matrix : dict # service -> severity -> count | |
| top_hotspots_provider : list # [{"provider": ..., "severe_count": ...}] | |
| top_hotspots_service : list | |
| severity_trend : dict # week-on-week deltas (if previous week given) | |
| notable_incidents : list # critical + high incidents, full descriptions | |
| def to_dict(self) -> dict: | |
| return { | |
| "period_start" : self.period_start, | |
| "period_end" : self.period_end, | |
| "total_incidents" : self.total_incidents, | |
| "severity_counts" : self.severity_counts, | |
| "provider_severity_matrix": self.provider_severity_matrix, | |
| "service_severity_matrix" : self.service_severity_matrix, | |
| "top_hotspots_provider" : self.top_hotspots_provider, | |
| "top_hotspots_service" : self.top_hotspots_service, | |
| "severity_trend" : self.severity_trend, | |
| "notable_incidents" : self.notable_incidents, | |
| } | |
| def aggregate( | |
| incidents : list[dict], | |
| period_start : str, | |
| period_end : str, | |
| previous_week : list[dict] | None = None, | |
| top_n : int = 5, | |
| ) -> WeeklyAggregation: | |
| """Build the aggregation. Pure Python, deterministic, fast.""" | |
| severity_counts = Counter(inc["final_severity"] for inc in incidents) | |
| provider_matrix = defaultdict(lambda: defaultdict(int)) | |
| service_matrix = defaultdict(lambda: defaultdict(int)) | |
| for inc in incidents: | |
| sev = inc["final_severity"] | |
| provider_matrix[inc.get("provider", "unknown")][sev] += 1 | |
| service_matrix[inc.get("service", "unknown")][sev] += 1 | |
| # Hotspots: providers/services with most critical+high incidents | |
| def severe_score(matrix_row): | |
| return matrix_row.get("critical", 0) * 2 + matrix_row.get("high", 0) | |
| top_providers = sorted( | |
| [(p, severe_score(s), dict(s)) for p, s in provider_matrix.items()], | |
| key=lambda t: -t[1], | |
| )[:top_n] | |
| top_services = sorted( | |
| [(s, severe_score(sv), dict(sv)) for s, sv in service_matrix.items()], | |
| key=lambda t: -t[1], | |
| )[:top_n] | |
| top_hotspots_provider = [ | |
| {"provider": p, "severe_score": score, "severity_breakdown": breakdown} | |
| for p, score, breakdown in top_providers | |
| ] | |
| top_hotspots_service = [ | |
| {"service": s, "severe_score": score, "severity_breakdown": breakdown} | |
| for s, score, breakdown in top_services | |
| ] | |
| severity_trend: dict = {} | |
| if previous_week: | |
| prev_counts = Counter(inc["final_severity"] for inc in previous_week) | |
| for sev in ["critical", "high", "medium", "low"]: | |
| curr = severity_counts.get(sev, 0) | |
| prev = prev_counts.get(sev, 0) | |
| severity_trend[sev] = { | |
| "this_week": curr, | |
| "last_week": prev, | |
| "delta" : curr - prev, | |
| "delta_pct": ((curr - prev) / prev * 100) if prev > 0 else None, | |
| } | |
| # Notable incidents: critical and high, capped at 10 to keep prompt size bounded | |
| notable_incidents = [ | |
| { | |
| "incident_id" : inc.get("incident_id"), | |
| "provider" : inc.get("provider"), | |
| "service" : inc.get("service"), | |
| "final_severity": inc.get("final_severity"), | |
| "description" : (inc.get("description") or "")[:300], | |
| } | |
| for inc in incidents | |
| if inc.get("final_severity") in {"critical", "high"} | |
| ][:10] | |
| return WeeklyAggregation( | |
| period_start=period_start, | |
| period_end=period_end, | |
| total_incidents=len(incidents), | |
| severity_counts=dict(severity_counts), | |
| provider_severity_matrix={p: dict(s) for p, s in provider_matrix.items()}, | |
| service_severity_matrix={s: dict(sv) for s, sv in service_matrix.items()}, | |
| top_hotspots_provider=top_hotspots_provider, | |
| top_hotspots_service=top_hotspots_service, | |
| severity_trend=severity_trend, | |
| notable_incidents=notable_incidents, | |
| ) | |
| def generate_summary(aggregation: WeeklyAggregation, anthropic_client: Anthropic) -> str: | |
| """Pass the aggregation to Claude Haiku and ask for a natural-language report.""" | |
| payload = json.dumps(aggregation.to_dict(), indent=2) | |
| response = anthropic_client.messages.create( | |
| model=CLAUDE_MODEL, | |
| max_tokens=1500, | |
| system=SUMMARY_SYSTEM_PROMPT, | |
| messages=[{ | |
| "role": "user", | |
| "content": f"Aggregated incident data for the period {aggregation.period_start} to {aggregation.period_end}:\n\n{payload}\n\nWrite the weekly intelligence report.", | |
| }], | |
| ) | |
| return response.content[0].text.strip() | |
| def build_weekly_report( | |
| incidents : list[dict], | |
| period_start : str, | |
| period_end : str, | |
| anthropic_client: Anthropic, | |
| previous_week : list[dict] | None = None, | |
| ) -> dict: | |
| """Top-level entry point used by the FastAPI endpoint.""" | |
| if not incidents: | |
| return { | |
| "period_start" : period_start, | |
| "period_end" : period_end, | |
| "total_incidents": 0, | |
| "summary" : "No incidents in the requested period.", | |
| "aggregation" : None, | |
| } | |
| agg = aggregate(incidents, period_start, period_end, previous_week=previous_week) | |
| summary = generate_summary(agg, anthropic_client) | |
| return { | |
| "period_start" : period_start, | |
| "period_end" : period_end, | |
| "total_incidents": agg.total_incidents, | |
| "summary" : summary, | |
| "aggregation" : agg.to_dict(), | |
| } | |