numes-autoreg: GitHub OAuth farm + new-api shim for $0 numes offers (7 free models, probe-based watcher)

This commit is contained in:
2026-11-13 21:54:01 +02:00
commit 5075c3f19f
10 changed files with 799 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
# secrets / runtime state
bank.jsonl
fail.jsonl
done.json
keys.json
key.txt
acc.json
ptok.txt
.ptok
dead.json
watch_state.json
wave.log
prof/
shots/
*.sql
__pycache__/
+52
View File
@@ -0,0 +1,52 @@
# numes-autoreg
Авторег аккаунтов [numes.ai](https://numes.ai) (маркетплейс инференса) через GitHub OAuth + локальный шим для new-api, который превращает 7 бесплатных ($0.00/$0.00) офферов numes в канал шлюза.
## Что внутри
| Файл | Роль |
|---|---|
| `reg.py` | Playwright + TOTP: GitHub OAuth → кабинет numes → API-ключ → `bank.jsonl` |
| `shim.py` | stdlib HTTP-шим `:NU_PORT`: алиасы иишко → слаги numes, ротация ключей, SSE-passthrough, `/status`, `/v1/models` |
| `numes_probe_watch.py` | сторож на прод-хосте: реальная проба 7 моделей → парковка/подъём канала new-api (`cron */10`) |
| `sync_keys.py` | `bank.jsonl` → `keys.json` на прод-хосте (шим перечитывает по mtime) |
| `e2e.sh` | сквозной тест 7 алиасов через шлюз (код/время/контент) |
## Бесплатные офферы (на 13.11.26)
`glm-5.3`, `glm-5.3-flash`, `glm-5.3-uncensored`, `kimi-k3.1-pro`, `kimi-k3-abliterated`, `deepseek-v4.1-flash`, `deepseek-v4.1-flash-uncensored` — все $0.00 in/out, контекст до 1M, выход 65 536.
## Запуск
```bash
# 1. регистрация (пул GitHub-аккаунтов в формате {"login","password","totp"})
export NUMES_POOL=/path/gh_alive.jsonl
export NUMES_ROOT=/path/numes
python reg.py --start 0 --count 5
# 2. ключи на прод-шим
export NUMES_PROD=root@your-host
python sync_keys.py
# 3. шим
NU_PORT=48961 NU_KEYS=/opt/numes-shim/keys.json python shim.py
```
## Гейты new-api (грабли, на которых теряется полдня)
1. `tokens.model_limits` — **точное имя** модели через запятую. `moonshotai/kimi-k3.1-pro` не даёт доступа к `kimi-k3.1-pro`; проверять регуляркой `~ '(^|,)имя(,|$)'`, не `LIKE`.
2. `channels."group"` — только явный список `default,premium,t1,t2,t3,t4`; сокращение `t1-t4` движок не резолвит (503 `no available channel (distributor)`).
3. `channels.models` — строка через запятую, независимо от `abilities`.
4. `status_code_mapping {"400":429,"402":429,"403":429,"404":429,"422":429}` — чтобы флап апстрима не банил канал.
5. После правок `abilities` дать ~60 с (кэш) или `systemctl restart new-api`.
6. Бот-шлюз перезаписывает `model_limits` через `rank_models()` — новые алиасы добавлять и в `TIER_MODELS[1]`, иначе выпадут на следующем сообщении юзера.
## Почему сторож пробует, а не читает каталог
`/api/v1/models` периодически отдаёт 5-7 моделей вообще без $0-цен, при этом прямой `chat/completions` к тем же слагам отвечает `200` и `usage.cost=0`. Живость = HTTP 200 на реальном чате, а не строка прайса.
## Ограничения
- Все $0-офферы живут на одном апстриме — падение провайдера снимает весь пул.
- AUP numes: мультиаккаунты и перепродажа ключей запрещены, за подмену модели снимают заработок.
- Регистрация только OAuth (email отбит в Keycloak: «Registration not allowed»).
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
TOK=$(cat /root/.numes_ptok)
echo "--- channels.models ---"
su postgres -c "psql -d newapi -At -c \"select models from channels where name='numes-pool'\""
echo "--- 503 body ---"
curl -s -m 60 -o /tmp/nb503 -w "HTTP=%{http_code}\n" http://127.0.0.1:48005/v1/chat/completions \
-H "Authorization: Bearer $TOK" -H 'Content-Type: application/json' \
-d '{"model":"glm-5.3-uncensored","messages":[{"role":"user","content":"hi"}],"max_tokens":20}'
head -c 400 /tmp/nb503
echo
echo "--- top-3 newest logs errors ---"
su postgres -c "psql -d newapi -At -c \"select model_name, channel_id, content, created_at from logs where type=5 and created_at > extract(epoch from now())-600 order by id desc limit 5\"" 2>/dev/null | head -c 600
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
TOK="20mTA9mqjP4ZwSxSugmvefBQaUyu1L5AEH35JLSJcvECWs4E"
for m in glm-5.3 kimi-k3.1-pro deepseek-v4.1-flash glm-5.3-uncensored kimi-k3-abliterated deepseek-v4.1-flash-uncensored glm-5.3-flash; do
t0=$(date +%s.%N)
out=$(curl -s -m 240 -w '\nHTTP=%{http_code}' http://127.0.0.1:48005/v1/chat/completions -H "Authorization: Bearer $TOK" -H 'Content-Type: application/json' \
-d "{\"model\":\"$m\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply: OK $m\"}],\"max_tokens\":1500}")
t1=$(date +%s.%N)
code=$(echo "$out" | tail -1 | cut -d= -f2)
dur=$(echo "$t1 - $t0" | bc)
head=$(echo "$out" | head -1)
txt=$(echo "$head" | python3 -c "import sys,json
try:
d=json.load(sys.stdin); c=d['choices'][0]['message'].get('content') or ''
print((c or 'EMPTY')[:50].replace(chr(10),' '),'| cost',d.get('usage',{}).get('cost'))
except Exception as e:
print('ERR', str(e)[:80], sys.stdin.read()[:80] if False else '')" 2>/dev/null)
printf "%-32s %s %6.1fs %s\n" "$m" "$code" "$dur" "$txt"
done
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""[NUMES 1113] Watch numes $0 aliases by REAL probe (catalog $0 pricing flaps, probe is truth).
Live = HTTP 200 on a tiny chat completion through api.numes.ai.
Unpark channel numes-pool + enable abilities for live aliases; park when none live.
Runs on the gateway host (cron every 10 min).
"""
import json
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
KEYS = os.environ.get("NUMES_KEYS", "/opt/numes-shim/keys.json")
BASE = "https://api.numes.ai/api/v1"
CHANNEL = "numes-pool"
STATE = "/opt/numes-shim/watch_state.json"
MAP = {
"glm-5.3": "z-ai/glm-5.3",
"glm-5.3-flash": "dealignai/glm-5.3-flash-uncensored-fp8",
"glm-5.3-uncensored": "dealignai/glm-5.3-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",
}
def log(msg):
sys.stdout.write("%s %s\n" % (time.strftime("%F %T"), msg))
sys.stdout.flush()
def first_key():
try:
d = json.load(open(KEYS))
if isinstance(d, dict):
d = d.get("keys", [])
return d[0] if d else None
except Exception:
return None
def probe(item):
alias, slug = item
k = first_key()
if not k:
return alias, 0, 0.0
body = json.dumps({"model": slug,
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 16})
t0 = time.time()
r = subprocess.run(
["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-m", "90",
BASE + "/chat/completions", "-H", "Authorization: Bearer " + k,
"-H", "Content-Type: application/json", "-d", body],
capture_output=True, text=True, timeout=120)
try:
code = int((r.stdout or "0").strip() or 0)
except Exception:
code = 0
return alias, code, round(time.time() - t0, 1)
def psql(sql):
p = "/tmp/numes_probe_%d.sql" % int(time.time() * 1000)
open(p, "w").write(sql + "\n")
os.chmod(p, 0o644)
r = subprocess.run(["su", "postgres", "-c",
"psql -d newapi -v ON_ERROR_STOP=1 -At -f " + p],
capture_output=True, text=True, cwd="/tmp", timeout=180)
try:
os.unlink(p)
except Exception:
pass
if r.returncode != 0:
log("psql fail: " + (r.stderr or "")[:200])
return r.stdout.strip()
def main():
with ThreadPoolExecutor(max_workers=4) as ex:
res = list(ex.map(probe, MAP.items()))
live = {a for a, code, _s in res if code == 200}
log("probe: " + " ".join("%s=%s/%.0fs" % (a, c, s) for a, c, s in res))
try:
prev = json.load(open(STATE)).get("live", [])
except Exception:
prev = []
if live:
psql("update channels set status=1 where name='%s';" % CHANNEL)
psql("update abilities set enabled=true where channel_id=(select id from channels where name='%s') and model in (%s);"
% (CHANNEL, ",".join("'%s'" % m for m in sorted(live))))
dead = sorted(set(MAP) - live)
if dead:
psql("update abilities set enabled=false where channel_id=(select id from channels where name='%s') and model in (%s);"
% (CHANNEL, ",".join("'%s'" % m for m in dead)))
if not live:
psql("update channels set status=2 where name='%s';" % CHANNEL)
changed = sorted(live) != sorted(prev)
json.dump({"live": sorted(live), "ts": int(time.time())}, open(STATE, "w"))
log("live=%s%s" % (sorted(live), " CHANGED" if changed else ""))
if changed:
log("ALERT numes live set: %s" % sorted(live))
if __name__ == "__main__":
main()
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
TOK=$(cat /root/.numes_ptok 2>/dev/null)
for m in kimi-k3.1-pro glm-5.3-uncensored kimi-k3-abliterated; do
printf "%-24s " "$m"
curl -s -m 60 -o /tmp/nprobe_body -w "HTTP=%{http_code} %{time_total}s " \
http://127.0.0.1:48005/v1/chat/completions \
-H "Authorization: Bearer $TOK" -H 'Content-Type: application/json' \
-d "{\"model\":\"$m\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":20}"
head -c 160 /tmp/nprobe_body
echo
done
+295
View File
@@ -0,0 +1,295 @@
#!/usr/bin/env python3
"""Numes autoreg: GitHub OAuth -> account -> USD inference key -> bank.
Usage: python reg.py --start 0 --count 3 [--headless 1]
State: done.json (logins tried), bank.jsonl (keys ok), fail.jsonl (reasons)
"""
import argparse, json, os, re, sys, time, traceback
from playwright.sync_api import sync_playwright
import pyotp
CHROME = os.environ.get("NUMES_CHROME", "C:/Program Files/Google/Chrome/Application/chrome.exe")
ROOT = os.environ.get("NUMES_ROOT", os.path.dirname(os.path.abspath(__file__)))
POOL = os.environ.get("NUMES_POOL", "gh_alive.jsonl")
BANK = ROOT + "/bank.jsonl"
FAIL = ROOT + "/fail.jsonl"
DONE = ROOT + "/done.json"
PROF = ROOT + "/prof"
LOG = ROOT + "/wave.log"
def log(*a):
line = time.strftime("%H:%M:%S ") + " ".join(str(x) for x in a)
print(line, flush=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write(line + "\n")
def load_json(path, default):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except Exception:
return default
def append(path, obj):
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
def pool():
out = []
with open(POOL, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line:
try:
out.append(json.loads(line))
except Exception:
pass
return out
def body(page):
try:
return (page.inner_text("body") or "")[:4000]
except Exception:
return ""
def shot(page, tag):
try:
p = f"{ROOT}/shots/{tag}.png"
os.makedirs(ROOT + "/shots", exist_ok=True)
page.screenshot(path=p)
return p
except Exception:
return ""
def wait_dash(page, timeout_ms=45000):
"""Ждём, пока окажемся на numes.ai (после OAuth)."""
t0 = time.time()
while (time.time() - t0) * 1000 < timeout_ms:
url = page.url
if "numes.ai" in url and "auth/login" not in url and "/auth/callback" not in url:
return True
page.wait_for_timeout(1200)
return False
def fill_profile_if_asked(page, acc):
"""Keycloak иногда просит дозаполнить профиль."""
try:
if "auth.numes.ai" not in page.url:
return
if page.locator("input[name=firstName]").count():
login = acc["login"].replace(".", " ").title()
first = login.split()[0][:20] or "Alex"
last = (login.split()[-1] if len(login.split()) > 1 else "Baker")[:20]
page.fill("input[name=firstName]", first)
page.fill("input[name=lastName]", last)
if page.locator("input[name=email]").count():
page.fill("input[name=email]", acc.get("email") or f"{acc['login']}@t-online.de")
page.click("input[type=submit]")
page.wait_for_timeout(4000)
log("profile filled")
except Exception as e:
log("profile fill err", e)
def do_login(page, acc):
"""Возвращает (ok, reason)."""
login, pw = acc["login"], acc["password"]
page.goto("https://numes.ai/auth/login", wait_until="domcontentloaded", timeout=90000)
page.wait_for_timeout(2500)
# GitHub broker
try:
page.get_by_text("Continue with GitHub", exact=True).click(timeout=20000)
except Exception:
page.locator("a:has-text('GitHub')").first.click(timeout=20000)
page.wait_for_timeout(5000)
if "github.com" in page.url and "/login" in page.url:
page.fill("#login_field", login)
page.fill("#password", pw)
page.click("input[type=submit][name=commit]")
page.wait_for_timeout(5500)
# GitHub 2FA
if "two-factor" in page.url or page.locator("#app_totp").count() or page.locator("input[name=app_otp]").count():
code = pyotp.TOTP(acc["totp"]).now()
sel = "#app_totp" if page.locator("#app_totp").count() else "input[name=app_otp]"
try:
page.fill(sel, code)
page.click("button[type=submit], input[type=submit]")
page.wait_for_timeout(6000)
log("2fa ok", login)
except Exception as e:
return False, f"2fa_fill_fail:{e}"
if "verified-device" in page.url or "sessions/verified" in page.url:
return False, "gh_device_verification"
if "/session" in page.url and "github.com" in page.url:
return False, "gh_login_failed"
if page.locator("#signup-form, [data-testid=signup-form]").count() and "join" in page.url:
return False, "gh_account_missing"
# OAuth authorize screen
if "/login/oauth/authorize" in page.url:
clicked = False
for sel in ('button[name=authorize][value="1"]', 'button:has-text("Authorize")'):
try:
page.click(sel, timeout=8000)
clicked = True
break
except Exception:
continue
if not clicked:
try:
page.locator('button[name=authorize][value="1"]').dispatch_event("click")
clicked = True
except Exception:
pass
if not clicked:
return False, "authorize_click_fail"
page.wait_for_timeout(6000)
fill_profile_if_asked(page, acc)
if not wait_dash(page, 40000):
return False, "no_dashboard:" + page.url[:120]
log("logged in", login, page.url[:80])
return True, "ok"
def create_key(page, acc):
page.goto("https://numes.ai/dashboard/keys", wait_until="domcontentloaded", timeout=90000)
page.wait_for_timeout(4000)
if "auth/login" in page.url:
return None, "session_lost"
page.get_by_role("button", name=re.compile(r"^Create key$")).last.click(timeout=20000)
page.wait_for_timeout(2500)
dlg = page.locator("[role=dialog]").last
# имя
try:
name_input = dlg.locator("input[name=name]")
name_input.fill("")
name_input.type("eni-" + acc["login"][:14], delay=25)
except Exception as e:
log("name fill err", e)
# USD уже дефолт; Type=Inference дефолт
page.wait_for_timeout(600)
try:
dlg.get_by_role("button", name=re.compile(r"^Create key$")).click(timeout=15000)
except Exception:
dlg.locator("form").first.evaluate("f => f.requestSubmit ? f.requestSubmit() : f.submit()")
page.wait_for_timeout(6000)
txt = body(page)
m = re.search(r"(sk-numes-[A-Za-z0-9_\-]{20,})", txt)
if not m:
m = re.search(r"(sk-[A-Za-z0-9_\-]{30,})", txt)
if not m:
return None, "no_secret:" + txt[:200].replace("\n", " ")
return m.group(1), "ok"
def warm_key(key):
"""Один вызов на $0 модель для проверки ключа."""
import urllib.request
payload = json.dumps({
"model": "z-ai/glm-5.3",
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 1200,
}).encode()
req = urllib.request.Request(
"https://api.numes.ai/api/v1/chat/completions",
data=payload,
headers={"Content-Type": "application/json", "Authorization": "Bearer " + key},
)
try:
with urllib.request.urlopen(req, timeout=120) as r:
j = json.loads(r.read().decode())
return r.status, j.get("usage", {}).get("cost")
except Exception as e:
return None, str(e)[:120]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--start", type=int, default=0)
ap.add_argument("--count", type=int, default=2)
ap.add_argument("--headless", type=int, default=0)
a = ap.parse_args()
os.makedirs(ROOT, exist_ok=True)
accs = [x for x in pool() if x.get("login") and x.get("password")]
done = set(load_json(DONE, []))
todo = [x for x in accs if x["login"] not in done][a.start:a.start + a.count]
log(f"wave start: pool={len(accs)} done={len(done)} todo={len(todo)}")
with sync_playwright() as p:
ctx = p.chromium.launch_persistent_context(
PROF,
executable_path=CHROME,
headless=bool(a.headless),
args=["--disable-dev-shm-usage", "--disable-gpu", "--no-first-run", "--no-default-browser-check"],
viewport={"width": 1280, "height": 900},
)
page = ctx.pages[0] if ctx.pages else ctx.new_page()
for acc in todo:
login = acc["login"]
log("--- try", login)
try:
ctx.clear_cookies()
ok, reason = do_login(page, acc)
if not ok:
append(FAIL, {"login": login, "reason": reason, "ts": int(time.time())})
log("FAIL", login, reason)
shot(page, "fail_" + re.sub(r"\W", "_", login))
done.add(login)
continue
key, kerr = create_key(page, acc)
if not key:
append(FAIL, {"login": login, "reason": "key:" + kerr, "ts": int(time.time())})
log("KEYFAIL", login, kerr[:120])
shot(page, "keyfail_" + re.sub(r"\W", "_", login))
done.add(login)
continue
code, cost = warm_key(key)
append(BANK, {"gh": login, "email": acc.get("email"), "key": key,
"http": code, "cost": cost, "ts": int(time.time())})
log("OK", login, "http", code, "cost", cost, "keylen", len(key))
done.add(login)
save_key_file()
except Exception as e:
append(FAIL, {"login": login, "reason": "exc:" + str(e)[:200], "ts": int(time.time())})
log("EXC", login, str(e)[:200])
try:
shot(page, "exc_" + re.sub(r"\W", "_", login))
except Exception:
pass
done.add(login)
finally:
with open(DONE, "w", encoding="utf-8") as f:
json.dump(sorted(done), f)
ctx.close()
def save_key_file():
keys = []
try:
with open(BANK, encoding="utf-8") as f:
for line in f:
if line.strip():
keys.append(json.loads(line)["key"])
except Exception:
pass
with open(ROOT + "/keys.txt", "w", encoding="utf-8") as f:
f.write("\n".join(keys) + ("\n" if keys else ""))
if __name__ == "__main__":
main()
+2
View File
@@ -0,0 +1,2 @@
playwright>=1.40
pyotp>=2.9
+227
View File
@@ -0,0 +1,227 @@
#!/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",
}
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
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(4):
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=300)
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 in (429, 500, 502, 503, 504):
mark_dead(k, 60)
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)
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Sync numes keys bank -> prod shim /opt/numes-shim/keys.json (shim re-reads by mtime)."""
import json
import os
import subprocess
import sys
ROOT = os.environ.get("NUMES_ROOT", os.path.dirname(os.path.abspath(__file__)))
BANK = ROOT + "/bank.jsonl"
LOCAL = ROOT + "/keys.json"
SSH_KEY = os.environ.get("NUMES_SSH_KEY", os.path.expanduser("~/.ssh/id_ed25519"))
HOST = os.environ.get("NUMES_PROD", "root@host")
REMOTE = os.environ.get("NUMES_REMOTE_KEYS", "/opt/numes-shim/keys.json")
def main():
keys = []
if os.path.exists(BANK):
with open(BANK, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
k = json.loads(line).get("key", "")
except Exception:
continue
if k and k not in keys:
keys.append(k)
if not keys:
print("no keys in bank")
return 0
with open(LOCAL, "w", encoding="utf-8") as f:
json.dump(keys, f)
r = subprocess.run(
["scp", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=25",
"-i", SSH_KEY, LOCAL, HOST + ":" + REMOTE],
capture_output=True, text=True, timeout=120,
)
if r.returncode != 0:
print("scp failed:", (r.stderr or "")[:300])
return 1
chk = subprocess.run(
["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=25",
"-i", SSH_KEY, HOST, "python3 -c \"import json;print(len(json.load(open('%s'))))\"" % REMOTE],
capture_output=True, text=True, timeout=90,
)
print("synced keys=%d remote=%s" % (len(keys), (chk.stdout or "").strip()))
return 0
if __name__ == "__main__":
sys.exit(main())