stability: shim fallback map + health_loop (base<->fallback), 429 retry, watcher probes the shim; guide 7.5
This commit is contained in:
@@ -27,6 +27,19 @@ MAP = {
|
||||
"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 = {}
|
||||
@@ -90,6 +103,44 @@ def alive():
|
||||
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()
|
||||
k = ks[int(time.time() // 600) % len(ks)] if ks else None
|
||||
if k:
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
pairs = [(a, b) for a, b in BASE_SLUG.items() if FALLBACK.get(a)]
|
||||
with ThreadPoolExecutor(max_workers=4) as ex:
|
||||
oks = list(ex.map(lambda ab: _slug_ok(ab[1], k, timeout=70), 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"
|
||||
|
||||
@@ -145,7 +196,7 @@ class H(BaseHTTPRequestHandler):
|
||||
payload = json.dumps(body).encode()
|
||||
|
||||
last = None
|
||||
for _ in range(4):
|
||||
for _ in range(6):
|
||||
cand = alive()
|
||||
if not cand:
|
||||
break
|
||||
@@ -158,7 +209,7 @@ class H(BaseHTTPRequestHandler):
|
||||
headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=300)
|
||||
resp = urllib.request.urlopen(req, timeout=200)
|
||||
except urllib.error.HTTPError as e:
|
||||
code = e.code
|
||||
try:
|
||||
@@ -174,8 +225,10 @@ class H(BaseHTTPRequestHandler):
|
||||
last = (code, err)
|
||||
continue
|
||||
if code == 429:
|
||||
mark_dead(k, 30) # rate limit: короткая пауза
|
||||
elif code in (500, 502, 503, 504):
|
||||
mark_dead(k, 30) # rate limit: короткая пауза и другой ключ
|
||||
last = (code, err)
|
||||
continue
|
||||
if code in (500, 502, 503, 504):
|
||||
mark_dead(k, 15) # upstream flap: не вина ключа, пауза минимальная
|
||||
last = (code, err)
|
||||
continue
|
||||
@@ -226,4 +279,5 @@ class H(BaseHTTPRequestHandler):
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user