""" Verify every configured API key / service WITHOUT printing any secret. python -m controlplane.scripts.check_keys For each Groq / Gemini key (identified only as groq#1, gemini#2, ...): * lists the models the key can see and flags catalog models it CANNOT see * makes one tiny real completion (max ~8 tokens) to prove it answers Also checks LangSmith, Neo4j and (if configured) the history database + SMTP. Exit code 0 = at least one working LLM key; 1 = no usable LLM. """ from __future__ import annotations import os import sys import time import httpx from controlplane.config import settings _OK, _BAD, _WARN = "\033[32mOK\033[0m", "\033[31mFAIL\033[0m", "\033[33mWARN\033[0m" def _catalog_models(provider: str) -> set[str]: out = set() for models in settings.model_catalog.values(): for m in models: if m.startswith(provider + "/"): out.add(m.split("/", 1)[1]) return out def check_groq() -> int: working = 0 wanted = _catalog_models("groq") if not settings.groq_keys: print(f" [{_WARN}] no Groq keys configured (GROQ_API_KEYS / GROQ_API_KEY)") return 0 for i, key in enumerate(settings.groq_keys, 1): tag = f"groq#{i}" h = {"Authorization": f"Bearer {key}"} try: r = httpx.get("https://api.groq.com/openai/v1/models", headers=h, timeout=10) if r.status_code != 200: print(f" [{_BAD}] {tag}: /models HTTP {r.status_code} - {r.text[:120]}") continue have = {m["id"] for m in r.json().get("data", [])} missing = sorted(wanted - have) t0 = time.perf_counter() r2 = httpx.post( "https://api.groq.com/openai/v1/chat/completions", headers=h, timeout=20, json={"model": "openai/gpt-oss-20b", "max_tokens": 16, "messages": [{"role": "user", "content": "Reply with the word pong."}]}, ) ms = (time.perf_counter() - t0) * 1000 if r2.status_code == 200: working += 1 print(f" [{_OK}] {tag}: completion in {ms:.0f} ms; " f"{len(have)} models visible" + (f"; catalog models NOT available: {missing}" if missing else "")) else: print(f" [{_BAD}] {tag}: completion HTTP {r2.status_code} - {r2.text[:160]}") except Exception as e: # noqa: BLE001 print(f" [{_BAD}] {tag}: {type(e).__name__}: {str(e)[:120]}") return working def check_gemini() -> int: working = 0 if not settings.gemini_keys: print(f" [{_WARN}] no usable Gemini keys (need AI Studio keys starting 'AIza'); Gemini fallback disabled") return 0 for i, key in enumerate(settings.gemini_keys, 1): tag = f"gemini#{i}" try: t0 = time.perf_counter() r = httpx.post( "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", headers={"x-goog-api-key": key}, timeout=25, json={"contents": [{"parts": [{"text": "Reply with the word pong."}]}], "generationConfig": {"maxOutputTokens": 64}}, ) ms = (time.perf_counter() - t0) * 1000 if r.status_code == 200: working += 1 print(f" [{_OK}] {tag}: gemini-2.5-flash answered in {ms:.0f} ms") else: print(f" [{_BAD}] {tag}: HTTP {r.status_code} - {r.text[:160]}") except Exception as e: # noqa: BLE001 print(f" [{_BAD}] {tag}: {type(e).__name__}: {str(e)[:120]}") return working def check_langsmith() -> None: if not settings.langsmith_enabled: print(f" [{_WARN}] LangSmith disabled (no valid lsv2_ key) - tracing off, app still works") return try: from langsmith import Client next(iter(Client().list_projects(limit=1)), None) print(f" [{_OK}] LangSmith key accepted (project '{settings.langsmith_project}')") except Exception as e: # noqa: BLE001 print(f" [{_BAD}] LangSmith: {type(e).__name__}: {str(e)[:140]}") def check_neo4j() -> None: if not settings.neo4j_uri: print(f" [{_WARN}] Neo4j not configured - responsibility graph uses cached triples (fine)") return from controlplane.responsibility.neo4j_util import get_driver t0 = time.perf_counter() drv = get_driver(verify=True) if drv is None: print(f" [{_WARN}] Neo4j unreachable/paused - app falls back to cached triples (fine)") else: print(f" [{_OK}] Neo4j connected in {(time.perf_counter() - t0) * 1000:.0f} ms") drv.close() def check_db() -> None: try: from controlplane.app import store t0 = time.perf_counter() store.init_db() print(f" [{_OK}] history DB ({store.backend_name()}) ready in {(time.perf_counter() - t0) * 1000:.0f} ms") except Exception as e: # noqa: BLE001 print(f" [{_BAD}] history DB: {type(e).__name__}: {str(e)[:160]}") def check_smtp() -> None: from controlplane.app import auth if not auth.smtp_configured(): print(f" [{_WARN}] SMTP not configured - email-OTP sign-in disabled (Google sign-in still works)") return ok, msg = auth.smtp_selftest() print(f" [{_OK if ok else _BAD}] SMTP login: {msg}") def check_site_link() -> None: sec, origins = os.getenv("BACKEND_SECRET", "").strip(), os.getenv("ALLOWED_ORIGINS", "").strip() print(f" [{_OK if len(sec) >= 32 else _WARN}] BACKEND_SECRET " f"{'set' if sec else 'NOT set'}{' (use >= 32 chars)' if sec and len(sec) < 32 else ''} - the Vercel site must use the same value") print(f" [{_OK if origins else _WARN}] ALLOWED_ORIGINS {origins or 'NOT set (browser calls from the site will be blocked by CORS)'}") def main() -> None: print("LLM providers") g = check_groq() m = check_gemini() print("Services") check_langsmith() check_neo4j() check_db() check_smtp() check_site_link() print(f"\nworking LLM keys: groq={g} gemini={m}") if os.getenv("CP_LLM_MOCK", "").lower() in {"1", "true", "yes"}: print("NOTE: CP_LLM_MOCK is set - the app will NOT call real models.") sys.exit(0 if (g + m) > 0 else 1) if __name__ == "__main__": main()