Files
factorio-ai-agent/scripts/glm_connection_check.py
kswdev0 3d118fe649 feat: mining_state 설정 최적화 및 GLM 예외 처리 개선
- `mine_resource` 함수에서 채굴 상태를 매 루프마다 반복 설정하던 로직을 제거하여, 우클릭 유지와 유사한 동작으로 최적화
- GLM API 호출 실패 시 예외 처리 로직을 개선하여, 다양한 오류 원인을 로그로 출력하고 상태 요약 기반의 폴백 로직 추가
- 새로운 연결 검사 스크립트 추가 및 README.md에 GLM API 연결 문제 디버깅 섹션 추가
- 관련 문서 및 주의사항 업데이트
2026-03-26 09:49:47 +09:00

88 lines
2.5 KiB
Python

#!/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())