#!/usr/bin/env python3 """inferx_watch.py — health-сторож каналов InferX в new-api. Каждый ключ пробивается напрямую в апстрим (/endpoints/v1/chat/completions): 200 -> alive -> канал status=1 + abilities enabled 401/402/403 -> dead -> канал status=2 + abilities disabled 429/таймаут -> flaky -> НЕ трогаем (free-эндпоинты InferX забиты, это норма) Печатает ТОЛЬКО при изменениях (годится для cron no_agent). Env: INFERX_BANK, INFERX_SSH_HOST, INFERX_SSH_KEY, INFERX_TAG (default inferx), INFERX_STATE (default ./watch_state.json) """ import json, os, subprocess, sys, time import requests try: sys.stdout.reconfigure(encoding='utf-8', errors='replace') except Exception: pass HERE = os.path.dirname(os.path.abspath(__file__)) BANK = os.environ.get("INFERX_BANK", os.path.join(HERE, "inferx_bank.jsonl")) STATE = os.environ.get("INFERX_STATE", os.path.join(HERE, "watch_state.json")) HOST = os.environ.get("INFERX_SSH_HOST", "") KEYFILE = os.environ.get("INFERX_SSH_KEY", "") TAG = os.environ.get("INFERX_TAG", "inferx") BASE = "https://model.inferx.net/endpoints/v1" MODEL = "deepseek-v4.1-flash-1017" def ssh(cmd, t=180): r = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", "-i", KEYFILE, HOST, cmd], capture_output=True, text=True, timeout=t, encoding='utf-8', errors='replace') return (r.stdout or "") + (r.stderr or "") def probe(key): try: r = requests.post(BASE + "/chat/completions", headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}, json={"model": MODEL, "messages": [{"role": "user", "content": "hi"}], "max_tokens": 4}, timeout=40) if r.status_code == 200: return "alive" if r.status_code in (401, 402, 403): return "dead" return "flaky" except Exception: return "flaky" def main(): keys, seen = [], set() for line in open(BANK, encoding='utf-8'): line = line.strip() if not line: continue try: d = json.loads(line) except Exception: continue k = d.get('key', '') if d.get('ok') and k.startswith('ix_') and k not in seen: seen.add(k) keys.append(k) old = {} if os.path.exists(STATE): try: old = json.load(open(STATE, encoding='utf-8')) except Exception: old = {} new, changes = {}, [] for i, k in enumerate(keys, 1): st = probe(k) new[k] = st if old.get(k) != st: changes.append(("%s-%02d" % (TAG, i), old.get(k), st)) json.dump(new, open(STATE, 'w', encoding='utf-8'), indent=0) if not changes: return sql = [] for i, k in enumerate(keys, 1): name = "%s-%02d" % (TAG, i) st = new[k] if st == 'dead': sql.append("update channels set status=2 where tag='%s' and name='%s';" % (TAG, name)) sql.append("update abilities set enabled=false where channel_id in " "(select id from channels where tag='%s' and name='%s');" % (TAG, name)) elif st == 'alive': sql.append("update channels set status=1 where tag='%s' and name='%s';" % (TAG, name)) sql.append("update abilities set enabled=true where channel_id in " "(select id from channels where tag='%s' and name='%s');" % (TAG, name)) if sql and HOST and KEYFILE: p = os.path.join(HERE, "_watch.sql") open(p, 'w', encoding='utf-8').write("\n".join(sql) + "\n") subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-i", KEYFILE, p, HOST + ":/tmp/_watch.sql"], capture_output=True, timeout=90) ssh("chmod 644 /tmp/_watch.sql; su postgres -c 'psql -d newapi -q -f /tmp/_watch.sql' >/dev/null 2>&1; " "systemctl restart new-api.service >/dev/null 2>&1") print("INFERX WATCH %s: %d changes" % (time.strftime('%d.%m %H:%M'), len(changes))) for n, a, b in changes: print(" %s: %s -> %s" % (n, a or 'new', b)) if __name__ == "__main__": main()