speka autoreg + shim pool
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OpenAI-compatible shim for Speka free keys ($1/mo per account, 10 rpm).
|
||||
Rotation over bank.jsonl, dead on 401/403, cooldown on 429/quota-402.
|
||||
ENV: SPEKA_BANK, SPEKA_PORT, SPEKA_UP
|
||||
"""
|
||||
import json, os, time, threading, urllib.request, urllib.error
|
||||
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
|
||||
|
||||
BANK = os.environ.get("SPEKA_BANK", "/opt/speka-shim/bank.jsonl")
|
||||
PORT = int(os.environ.get("SPEKA_PORT", "8819"))
|
||||
UP = os.environ.get("SPEKA_UP", "https://speka.me")
|
||||
# short alias -> upstream model id
|
||||
MAP = {
|
||||
"speka-muse-glimmer": "meta/muse-glimmer-30b",
|
||||
"speka-nemotron-ultra": "nvidia/nemotron-3-ultra-550b-a55b",
|
||||
"speka-laguna-xs": "poolside/laguna-xs-2.1",
|
||||
"speka-bolt": "nvidia/nemotron-3.5-bolt-e4b",
|
||||
"speka-lightning": "nvidia/nemotron-3.5-lightning-30b-a3b",
|
||||
"speka-step5": "stepfun-ai/step-5-preview",
|
||||
"speka-llama-vision": "meta/llama-3.2-90b-vision-instruct",
|
||||
}
|
||||
lock = threading.Lock()
|
||||
state = {"keys": [], "idx": 0, "dead": {}, "cool": {}}
|
||||
|
||||
|
||||
def load():
|
||||
keys = []
|
||||
try:
|
||||
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 k and d.get("ok", True):
|
||||
keys.append(k)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
with lock:
|
||||
state["keys"] = keys
|
||||
return keys
|
||||
|
||||
|
||||
def pick():
|
||||
with lock:
|
||||
keys = state["keys"]
|
||||
now = time.time()
|
||||
if not keys:
|
||||
return None
|
||||
for _ in range(len(keys)):
|
||||
state["idx"] = (state["idx"] + 1) % len(keys)
|
||||
k = keys[state["idx"]]
|
||||
if state["dead"].get(k):
|
||||
continue
|
||||
if state["cool"].get(k, 0) > now:
|
||||
continue
|
||||
return k
|
||||
return None
|
||||
|
||||
|
||||
def mark(k, code, body=b""):
|
||||
with lock:
|
||||
if code in (401, 403):
|
||||
state["dead"][k] = True
|
||||
elif code == 429:
|
||||
state["cool"][k] = time.time() + 60
|
||||
elif code == 402:
|
||||
# monthly $1 allowance exhausted -> park until monthly reset/restart
|
||||
state["dead"][k] = True
|
||||
elif code == 400 and b"insufficient" in body.lower():
|
||||
state["dead"][k] = True
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, code, obj, ctype="application/json"):
|
||||
b = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(b)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._send(200, {"object": "list", "data": [
|
||||
{"id": a, "object": "model", "owned_by": "speka", "root": m} for a, m in MAP.items()
|
||||
]})
|
||||
if self.path.startswith("/health"):
|
||||
return self._send(200, {"keys": len(state["keys"]), "dead": len(state["dead"]),
|
||||
"cool": len(state["cool"])})
|
||||
return self._send(404, {"error": "not found"})
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(n) if n else b""
|
||||
if not self.path.startswith("/v1/chat/completions") and not self.path.startswith("/v1/embeddings"):
|
||||
return self._send(404, {"error": "not found"})
|
||||
try:
|
||||
_j = json.loads(body.decode() or "{}")
|
||||
except Exception:
|
||||
_j = {}
|
||||
if _j.get("model") in MAP:
|
||||
_j["model"] = MAP[_j["model"]]
|
||||
body = json.dumps(_j).encode()
|
||||
last = None
|
||||
for _ in range(4):
|
||||
key = pick()
|
||||
if not key:
|
||||
return self._send(503, {"error": {"message": "speka pool exhausted", "type": "no_keys"}})
|
||||
req = urllib.request.Request(UP + self.path, data=body, method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
req.add_header("Authorization", "Bearer " + key)
|
||||
try:
|
||||
r = urllib.request.urlopen(req, timeout=180)
|
||||
ctype = r.headers.get("Content-Type", "application/json")
|
||||
if "text/event-stream" in ctype:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Cache-Control", "no-cache")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
try:
|
||||
while True:
|
||||
chunk = r.read(1024)
|
||||
if not chunk:
|
||||
break
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
data = r.read()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
except urllib.error.HTTPError as e:
|
||||
data = e.read()
|
||||
mark(key, e.code, data)
|
||||
last = (e.code, data)
|
||||
if e.code in (400, 404, 422):
|
||||
# real request error, not key issue
|
||||
self.send_response(e.code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
continue
|
||||
except Exception as e:
|
||||
last = (500, str(e).encode())
|
||||
continue
|
||||
code, data = last or (502, b'{"error":"upstream failed"}')
|
||||
self.send_response(code if code >= 400 else 502)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load()
|
||||
threading.Thread(target=lambda: [time.sleep(30) or load() for _ in iter(int, 1)], daemon=True).start()
|
||||
print("speka-shim on :%d keys=%d" % (PORT, len(state["keys"])), flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
Reference in New Issue
Block a user