# performance_agent.py import os import requests class PerformanceAgent: """ Wraps the PageSpeed Insights API to fetch Lighthouse scores for a given URL. On any network/API failure, returns all-100% defaults. """ EXPECTED_CATEGORIES = ("performance", "accessibility", "best-practices", "seo") def __init__(self): self.api_key = os.getenv("PAGESPEED_API_KEY","AAIzaSyBcFCQnfZLrAa2azkYvD-0ytIvQe32LlFs") self.endpoint = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed" if not self.api_key: raise ValueError("PAGESPEED_API_KEY not set in .env") def fetch_performance(self, url: str, strategy: str = "mobile") -> dict: params = { "url": url, "strategy": strategy, # "mobile" or "desktop" "key": self.api_key } try: resp = requests.get(self.endpoint, params=params, timeout=30) resp.raise_for_status() data = resp.json() lh = data.get("lighthouseResult", {}) cats = lh.get("categories", {}) audits = lh.get("audits", {}) # Build scores, default missing/unparsable → 100.0 scores = {} for cat in self.EXPECTED_CATEGORIES: raw = cats.get(cat, {}).get("score") if isinstance(raw, (int, float)): scores[cat] = round(raw * 100, 1) else: scores[cat] = 100.0 # Collect audits < 100% for suggestions audit_suggestions = {} for audit_id, info in audits.items(): sc = info.get("score") if isinstance(sc, (int, float)) and sc < 1: audit_suggestions[audit_id] = info.get("displayValue", "").strip() return { "scores": scores, "audit_suggestions": audit_suggestions } except requests.exceptions.RequestException as e: # Log the error and return an all-100% default, with no suggestions print(f"[PerformanceAgent] PSI API error: {e}") return { "scores": {cat: 100.0 for cat in self.EXPECTED_CATEGORIES}, "audit_suggestions": {} }