Files

286 lines
11 KiB
Python

#!/usr/bin/env python3
"""Numes marketplace shim for iishko new-api.
alias (our catalogue name) -> numes author/model slug, key rotation, SSE passthrough.
Listens 127.0.0.1:48960 (NU_PORT).
Endpoints: POST /v1/chat/completions, GET /v1/models, GET /status
Keys: /opt/numes-shim/keys.json (JSON array of sk-numes-v1-... strings, re-read on mtime)
Dead state: /opt/numes-shim/dead.json
"""
import json, os, sys, time, threading, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT = int(os.environ.get("NU_PORT", "48960"))
BASE = os.environ.get("NU_BASE", "https://api.numes.ai/api/v1")
KEYS_PATH = os.environ.get("NU_KEYS", "/opt/numes-shim/keys.json")
STATE = os.environ.get("NU_STATE", "/opt/numes-shim/dead.json")
MIN_MAX_TOKENS = int(os.environ.get("NU_MIN_TOKENS", "1500"))
MAP = {
"glm-5.3": "z-ai/glm-5.3",
"glm-5.3-uncensored": "dealignai/glm-5.3-uncensored-fp8",
"glm-5.3-flash": "dealignai/glm-5.3-flash-uncensored-fp8",
"kimi-k3.1-pro": "moonshotai/kimi-k3.1-pro",
"kimi-k3-abliterated": "uniboshi/kimi-k3-abliterated-v1",
"deepseek-v4.1-flash": "deepseek/deepseek-v4.1-flash",
"deepseek-v4.1-flash-uncensored": "dealignai/deepseek-v4.1-flash-uncensored-fp8",
}
# Семантически ближайший слаг, если провайдер базового ушёл (503 держится часами).
# health_loop переключает alias на резерв автоматически и возвращает обратно, когда база оживает.
FALLBACK = {
"glm-5.3": "z-ai/glm-5.3",
"glm-5.3-uncensored": "z-ai/glm-5.3",
"glm-5.3-flash": "dealignai/glm-5.3-uncensored-fp8",
"kimi-k3.1-pro": "moonshotai/kimi-k3.1-pro",
"kimi-k3-abliterated": "moonshotai/kimi-k3.1-pro",
"deepseek-v4.1-flash": "deepseek/deepseek-v4.1-flash",
"deepseek-v4.1-flash-uncensored": "deepseek/deepseek-v4.1-flash",
}
BASE_SLUG = dict(MAP)
lock = threading.Lock()
_rr = [0]
_dead = {}
try:
with open(STATE) as f:
_dead = json.load(f)
except Exception:
_dead = {}
_keys = {"list": [], "mtime": 0.0}
def keys():
try:
mt = os.path.getmtime(KEYS_PATH)
except OSError:
return []
with lock:
if mt != _keys["mtime"]:
try:
with open(KEYS_PATH) as f:
data = json.load(f)
if isinstance(data, dict):
data = data.get("keys", [])
out = []
for k in data:
k = (k or "").strip()
if k and k not in out:
out.append(k)
_keys["list"] = out
_keys["mtime"] = mt
except Exception as e:
sys.stderr.write("keys load error: %s\n" % e)
return list(_keys["list"])
def save_dead():
try:
with open(STATE, "w") as f:
json.dump(_dead, f)
except Exception:
pass
def mark_dead(k, seconds=1800):
with lock:
_dead[k] = time.time() + seconds
save_dead()
def alive():
now = time.time()
ks = keys()
live = [k for k in ks if _dead.get(k, 0) <= now]
if not live and ks:
# all parked: forget cooldowns and retry, a 503 is worse than a repeated probe
with lock:
_dead.clear()
save_dead()
live = list(ks)
return live
def _slug_ok(slug, k, timeout=120):
body = json.dumps({"model": slug,
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 8}).encode()
req = urllib.request.Request(BASE + "/chat/completions", data=body,
headers={"Authorization": "Bearer " + k,
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status == 200
except Exception:
return False
def health_loop(interval=120):
"""Держит каждый alias на живом слаге: база умерла -> резерв, база ожила -> обратно."""
time.sleep(20)
while True:
try:
ks = alive()
if ks:
from concurrent.futures import ThreadPoolExecutor
pairs = [(a, b) for a, b in BASE_SLUG.items() if FALLBACK.get(a)]
base_i = int(time.time() // 120)
with ThreadPoolExecutor(max_workers=4) as ex:
oks = list(ex.map(
lambda t: _slug_ok(t[1][1], ks[(base_i + t[0]) % len(ks)], timeout=70),
enumerate(pairs)))
for (alias, base), ok in zip(pairs, oks):
want = base if ok else FALLBACK[alias]
if MAP.get(alias) != want:
MAP[alias] = want
print("health: %s -> %s (%s)" % (alias, want, "base" if ok else "fallback"),
flush=True)
except Exception as e:
print("health err: %s" % str(e)[:120], flush=True)
time.sleep(interval)
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *a):
sys.stderr.write("%s %s\n" % (time.strftime("%H:%M:%S"), fmt % a))
def _json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
try:
self.wfile.write(body)
except Exception:
pass
def do_GET(self):
if self.path.startswith("/status") or self.path == "/healthz":
now = time.time()
ks = keys()
return self._json(200, {
"ok": True,
"keys_total": len(ks),
"keys_alive": len([k for k in ks if _dead.get(k, 0) <= now]),
"models": MAP,
})
if self.path.startswith("/v1/models"):
data = [{"id": m, "object": "model", "owned_by": "numes"} for m in MAP]
return self._json(200, {"object": "list", "data": data})
self._json(404, {"error": {"message": "not found", "type": "not_found"}})
def do_POST(self):
if not self.path.startswith("/v1/chat/completions"):
return self._json(404, {"error": {"message": "not found", "type": "not_found"}})
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n)
try:
body = json.loads(raw)
except Exception:
return self._json(400, {"error": {"message": "bad json", "type": "invalid_request_error"}})
model = body.get("model", "")
if model not in MAP:
return self._json(404, {"error": {"message": "model %s not mapped" % model,
"type": "invalid_request_error"}})
body["model"] = MAP[model]
mt = body.get("max_tokens") or body.get("max_completion_tokens")
if isinstance(mt, int) and 0 < mt < MIN_MAX_TOKENS:
if "max_tokens" in body:
body["max_tokens"] = MIN_MAX_TOKENS
else:
body["max_completion_tokens"] = MIN_MAX_TOKENS
payload = json.dumps(body).encode()
last = None
for _ in range(6):
cand = alive()
if not cand:
break
idx = _rr[0] % len(cand)
_rr[0] += 1
k = cand[idx]
req = urllib.request.Request(
BASE + "/chat/completions",
data=payload,
headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"},
)
try:
resp = urllib.request.urlopen(req, timeout=200)
except urllib.error.HTTPError as e:
code = e.code
try:
err = e.read()
except Exception:
err = b""
if code in (401, 403):
mark_dead(k, 900)
last = (code, err)
continue
if code == 402:
mark_dead(k, 600)
last = (code, err)
continue
if code == 429:
mark_dead(k, 30) # rate limit: короткая пауза и другой ключ
last = (code, err)
continue
if code in (500, 502, 503, 504):
# upstream flap: НЕ паркуем ключ (иначе флап апстрима парализует весь пул),
# просто идём следующим ключом
last = (code, err)
continue
return self._relay(code, err)
except Exception as e:
last = (502, json.dumps({"error": {"message": str(e)[:200]}}).encode())
continue
if body.get("stream"):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
try:
while True:
chunk = resp.read(2048)
if not chunk:
break
self.wfile.write(chunk)
self.wfile.flush()
except Exception:
pass
return
data = resp.read()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
try:
self.wfile.write(data)
except Exception:
pass
return
code, err = last if last else (502, b'{"error":{"message":"no live numes key"}}')
return self._relay(code, err)
def _relay(self, code, err):
if code in (401, 402, 403, 429, 500, 502, 503, 504):
code = 503
try:
obj = json.loads(err)
except Exception:
obj = {"error": {"message": (err or b"").decode("utf-8", "ignore")[:400]}}
self._json(code, obj)
if __name__ == "__main__":
print("numes-shim on 127.0.0.1:%d models=%d keys=%d" % (PORT, len(MAP), len(keys())), flush=True)
threading.Thread(target=health_loop, daemon=True).start()
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()