#!/usr/bin/env python3 """ GLM API 연결만 검사 (main.py와 동일한 urllib + URL). 에이전트 실행 전/타임아웃 원인 조사용. ZAI_API_KEY=... python scripts/glm_connection_check.py GLM_DEBUG=1 GLM_HTTP_TIMEOUT_SECONDS=180 python scripts/glm_connection_check.py """ from __future__ import annotations import json import os import sys import time import urllib.error import urllib.request # 프로젝트 루트를 path에 넣어 ai_planner 상수 재사용 _ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if _ROOT not in sys.path: sys.path.insert(0, _ROOT) from ai_planner import ( # noqa: E402 GLM_API_URL, GLM_MODEL, describe_glm_exception, _glm_debug_enabled, ) def main() -> int: key = os.environ.get("ZAI_API_KEY", "").strip() if not key: print("[오류] ZAI_API_KEY 가 비어 있습니다.") return 2 timeout = float(os.environ.get("GLM_HTTP_TIMEOUT_SECONDS", "120")) payload = json.dumps({ "model": GLM_MODEL, "messages": [ {"role": "user", "content": "Reply with exactly: OK"}, ], "max_tokens": 16, "temperature": 0, }).encode("utf-8") req = urllib.request.Request( GLM_API_URL, data=payload, headers={ "Content-Type": "application/json", "Authorization": f"Bearer {key}", }, method="POST", ) if _glm_debug_enabled(): print(f"[디버그] POST {GLM_API_URL}") print(f"[디버그] timeout={timeout}s payload_bytes={len(payload)} model={GLM_MODEL}") t0 = time.perf_counter() try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") dt = time.perf_counter() - t0 except Exception as e: dt = time.perf_counter() - t0 print(f"[실패] {dt:.2f}s 경과 후 예외") print(f" {describe_glm_exception(e)}") return 1 dt = time.perf_counter() - t0 print(f"[성공] HTTP 응답 수신 {dt:.2f}s, 본문 {len(raw)}자") try: data = json.loads(raw) content = data.get("choices", [{}])[0].get("message", {}).get("content", "") preview = (content or "").strip().replace("\n", " ")[:200] print(f" assistant 미리보기: {preview!r}") except Exception as e: print(f"[경고] JSON 파싱 실패: {e}") print(f" 원문 앞 400자: {raw[:400]!r}") return 0 if __name__ == "__main__": raise SystemExit(main())