"""Diagnose why the layout model call fails from this machine/container. Run it wherever the app runs (locally, or in the Space via the terminal): python diagnose_api.py It never prints the API key. It walks the failure chain so a bare "Connection error." from the SDK becomes an actual reason: DNS failure, TLS/certificate problem, proxy interference, refusal, or an API-level error (bad key, no quota, unknown model). """ import os import socket import ssl import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) HOST = "api.openai.com" def chain(exc): parts = [f"{type(exc).__name__}: {exc}"] seen = {id(exc)} cur = exc.__cause__ or exc.__context__ while cur is not None and id(cur) not in seen and len(parts) < 5: parts.append(f"caused by {type(cur).__name__}: {cur}") seen.add(id(cur)) cur = cur.__cause__ or cur.__context__ return "\n ".join(parts) def step(n, label): print(f"\n[{n}] {label}") print("=" * 68) print("Layout model connectivity diagnosis") print("=" * 68) step(1, "Is a key configured?") from core import layout_engine as le # noqa: E402 key, var = le._api_key_source() if not key: print(" NO KEY. Set LAYOUT_API_KEY (or OPENAI_API_KEY).") sys.exit(1) print(f" yes: from {var}, length {len(key)}, starts {key[:3]!r}") if key != key.strip() or "\n" in key: print(" !! the key has surrounding whitespace/newline") step(2, "Proxy environment variables (these can break outbound TLS)") proxies = {k: v for k, v in os.environ.items() if "proxy" in k.lower()} print(f" {proxies or 'none set'}") step(3, f"DNS: can we resolve {HOST}?") try: print(f" {HOST} -> {socket.gethostbyname(HOST)}") except Exception as exc: print(f" FAILED. {chain(exc)}") print("\n => The container has no DNS / no outbound internet.") sys.exit(2) step(4, f"TCP+TLS: can we open a socket to {HOST}:443?") try: ctx = ssl.create_default_context() with socket.create_connection((HOST, 443), timeout=15) as sock: with ctx.wrap_socket(sock, server_hostname=HOST) as tls: print(f" connected, TLS {tls.version()}") except Exception as exc: print(f" FAILED. {chain(exc)}") print("\n => Network reachable but TLS/egress blocked " "(firewall, missing CA certs, or proxy).") sys.exit(3) step(5, "SDK: a real (tiny) API call") try: from openai import OpenAI client = OpenAI(api_key=key, timeout=30) models = client.models.list() ids = [m.id for m in list(models)[:5]] print(f" OK. Sample models visible: {ids}") except Exception as exc: print(f" FAILED. {chain(exc)}") print("\n => Network is fine; this is an API-level problem " "(bad key, no credit/quota, or org restriction).") sys.exit(4) step(6, f"Is the configured model reachable? ({le.MODEL})") try: client.chat.completions.create( model=le.MODEL, messages=[{"role": "user", "content": "reply with the word ok"}], max_completion_tokens=5, ) print(" OK -- the model answered.") except Exception as exc: print(f" FAILED. {chain(exc)}") print(f"\n => The key works but '{le.MODEL}' is not usable on this " "account. Set the LAYOUT_MODEL secret to a model you do have.") sys.exit(5) print("\n" + "=" * 68) print("ALL CHECKS PASSED -- the layout model should work here.") print("=" * 68)