""" utils/llm.py ============ Central LLM utilities for the BPS AI Agent. Provides: - get_llm() → async, reads active model from Redis; returns (llm, model_name) - handle_quota_error() → detects 429/ResourceExhausted, switches model in Redis, emails admin - invoke_with_fallback()→ wraps LLM invoke with single-retry auto-fallback All Redis operations are async (redis.asyncio). Timestamps are in WIB (UTC+8). """ import os import json import logging import smtplib import asyncio from datetime import datetime, timezone, timedelta from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import redis.asyncio as aioredis from langchain_google_genai import ChatGoogleGenerativeAI # --------------------------------------------------------------------------- # Logging # --------------------------------------------------------------------------- logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- WIB = timezone(timedelta(hours=8)) PRIMARY_MODEL = "gemini-2.5-flash" FALLBACK_MODEL = "gemini-2.5-flash-lite" ALLOWED_MODELS = {PRIMARY_MODEL, FALLBACK_MODEL} REDIS_MODEL_KEY = "config:active_model" REDIS_META_KEY = "config:model_meta" # --------------------------------------------------------------------------- # Redis helper — create a fresh async connection on demand # --------------------------------------------------------------------------- def _get_redis() -> aioredis.Redis: redis_url = os.getenv("REDIS_URL", "redis://localhost:6379") return aioredis.from_url(redis_url, encoding="utf-8", decode_responses=True) # --------------------------------------------------------------------------- # get_llm() # --------------------------------------------------------------------------- async def get_llm() -> tuple: """ Read active model name from Redis and return (llm_instance, model_name). Fallback: if Redis is unreachable, defaults to PRIMARY_MODEL without crashing. """ model_name = PRIMARY_MODEL # safe default try: r = _get_redis() stored = await r.get(REDIS_MODEL_KEY) await r.aclose() if stored and stored in ALLOWED_MODELS: model_name = stored elif stored: logger.warning( "[get_llm] Unknown model '%s' in Redis — defaulting to %s", stored, PRIMARY_MODEL ) except Exception as exc: logger.warning("[get_llm] Redis unavailable (%s) — using default model %s", exc, PRIMARY_MODEL) llm = ChatGoogleGenerativeAI( model=model_name, temperature=0.1, max_tokens=None, timeout=60, max_retries=2, streaming=True, location="us-central1", api_key=os.getenv("GOOGLE_API_KEY"), ) logger.info("[get_llm] Active model: %s", model_name) return llm, model_name def get_llm_sync() -> tuple: """ Synchronous version of get_llm() for use in synchronous tools. """ model_name = PRIMARY_MODEL try: import redis redis_url = os.getenv("REDIS_URL", "redis://localhost:6379") r = redis.from_url(redis_url, encoding="utf-8", decode_responses=True) stored = r.get(REDIS_MODEL_KEY) if stored and stored in ALLOWED_MODELS: model_name = stored elif stored: logger.warning( "[get_llm_sync] Unknown model '%s' in Redis — defaulting to %s", stored, PRIMARY_MODEL ) except Exception as exc: logger.warning("[get_llm_sync] Redis unavailable (%s) — using default model %s", exc, PRIMARY_MODEL) llm = ChatGoogleGenerativeAI( model=model_name, temperature=0.1, max_tokens=None, timeout=60, max_retries=2, streaming=False, location="us-central1", api_key=os.getenv("GOOGLE_API_KEY"), ) logger.info("[get_llm_sync] Active model: %s", model_name) return llm, model_name # --------------------------------------------------------------------------- # Email notification # --------------------------------------------------------------------------- def _build_switch_email(old_model: str, new_model: str, timestamp_wib: str) -> MIMEMultipart: """Build the admin notification email (MIME).""" admin_email = os.getenv("ADMIN_EMAIL", "") sender_email = os.getenv("SMTP_FROM", "") admin_key = os.getenv("ADMIN_KEY", "") subject = "[AI BPS] Auto-switch model — quota habis" body = ( f"Waktu : {timestamp_wib}\n" f"Model lama: {old_model}\n" f"Model baru: {new_model}\n" f"Alasan : Quota exhausted (429)\n\n" f"Model akan tetap {new_model} sampai admin reset manual.\n" f"Reset via: GET /admin/model/switch?key={admin_key}&model={old_model}" ) msg = MIMEMultipart() msg["From"] = sender_email msg["To"] = admin_email msg["Subject"] = subject msg.attach(MIMEText(body, "plain", "utf-8")) return msg async def _send_admin_email_async(old_model: str, new_model: str, timestamp_wib: str): """ Send admin notification email without blocking the event loop. Uses smtplib inside a thread executor so FastAPI stays non-blocking. """ smtp_host = os.getenv("SMTP_HOST", "smtp.gmail.com") smtp_port = int(os.getenv("SMTP_PORT", "587")) smtp_user = os.getenv("SMTP_USER", "") smtp_pass = os.getenv("SMTP_PASS", "") admin_email = os.getenv("ADMIN_EMAIL", "") if not all([smtp_user, smtp_pass, admin_email]): logger.warning("[email] SMTP credentials not configured — skipping notification.") return msg = _build_switch_email(old_model, new_model, timestamp_wib) def _send(): try: with smtplib.SMTP(smtp_host, smtp_port) as server: server.ehlo() server.starttls() server.login(smtp_user, smtp_pass) server.sendmail(smtp_user, admin_email, msg.as_string()) logger.info("[email] Admin notified at %s", admin_email) except Exception as exc: logger.error("[email] Failed to send notification: %s", exc) loop = asyncio.get_event_loop() await loop.run_in_executor(None, _send) # --------------------------------------------------------------------------- # handle_quota_error() # --------------------------------------------------------------------------- async def handle_quota_error(exc: Exception, current_model: str) -> bool: """ Inspect `exc` for Gemini quota signals (HTTP 429 / ResourceExhausted / 'quota'). If quota error: 1. Write FALLBACK_MODEL to Redis. 2. Log the switch with WIB timestamp. 3. Notify admin via email. 4. Return True. If not a quota error: return False. """ error_str = str(exc) is_quota = ( "429" in error_str or "ResourceExhausted" in error_str or "quota" in error_str.lower() ) if not is_quota: return False now_wib = datetime.now(WIB).strftime("%Y-%m-%d %H:%M:%S WIB") new_model = FALLBACK_MODEL logger.warning( "[quota] %s | Switching model: %s → %s | Error: %s", now_wib, current_model, new_model, error_str[:200], ) # --- Write to Redis --- try: r = _get_redis() meta = json.dumps({ "model": new_model, "timestamp": now_wib, "reason": "auto", }) await r.set(REDIS_MODEL_KEY, new_model) await r.set(REDIS_META_KEY, meta) await r.aclose() logger.info("[quota] Redis updated → active_model=%s", new_model) except Exception as redis_exc: logger.error("[quota] Redis write failed: %s", redis_exc) # --- Email admin (fire-and-forget, non-blocking) --- asyncio.create_task( _send_admin_email_async(current_model, new_model, now_wib) ) return True # --------------------------------------------------------------------------- # invoke_with_fallback() # --------------------------------------------------------------------------- async def invoke_with_fallback(model, messages: list, config=None): """ Invoke `model` with `messages`. On quota error, switch to fallback model and retry exactly once. Re-raises on any non-quota error or second failure. Args: model : LLM or bound LLM instance (from get_llm() + optional bind_tools) messages: list of LangChain message objects config : optional RunnableConfig for LangGraph Returns: AIMessage response from the LLM. """ # Track which model is currently active for the error handler llm_base, current_model = await get_llm() # Use the passed-in model (which may have tools bound) but remember its name try: if config is not None: return await model.ainvoke(messages, config=config) return await model.ainvoke(messages) except Exception as first_exc: handled = await handle_quota_error(first_exc, current_model) if not handled: # Not a quota error — propagate immediately raise # Quota error handled → get fresh model from Redis (now FALLBACK_MODEL) logger.info("[fallback] Retrying with fallback model after quota error…") try: new_llm, new_model = await get_llm() if config is not None: return await new_llm.ainvoke(messages, config=config) return await new_llm.ainvoke(messages) except Exception as retry_exc: logger.error("[fallback] Retry also failed: %s", retry_exc) raise # re-raise the retry exception