#!/usr/bin/env python3 """crowl-shim: OpenAI-compatible pool front for crowllm.com free-tier keys. Rotates keys round-robin, retries the next key on 429/5xx, parks keys on 401/403. stdlib only (no fastapi on prod). """ import json, os, sys, time, threading, urllib.request, urllib.error from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer UPSTREAM = os.environ.get("CROWL_UPSTREAM", "https://crowllm.com/v1") KEYS_FILE = os.environ.get("CROWL_KEYS", "/opt/crowl-shim/keys.jsonl") PORT = int(os.environ.get("CROWL_PORT", "48960")) TIMEOUT = int(os.environ.get("CROWL_TIMEOUT", "120")) UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36" _lock = threading.Lock() STATE = {"keys": [], "idx": 0, "dead": set(), "loaded": 0} ALIAS = {"crow-kimi-k3": "runpod/kimi-k3"} # crowllm's own ids already start with "crow-" - never strip that prefix KEEP_PREFIX = {"crow-uncensored", "crow-limitless"} def to_upstream(model): """crow-* alias -> crowllm free id""" if not model: return model if model in ALIAS: return ALIAS[model] if model in KEEP_PREFIX: return model + ":free" if model.startswith("crow-") and not model.endswith(":free"): return model[5:] + ":free" return model def load_keys(): keys, dead = [], set() try: with open(KEYS_FILE, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: j = json.loads(line) except Exception: continue k = j.get("key") or j.get("api_key") if not k: continue if isinstance(k, dict): k = k.get("key") if not k: continue if j.get("status") in ("dead", "parked"): dead.add(k) keys.append(str(k)) except FileNotFoundError: pass with _lock: STATE["keys"] = keys STATE["dead"] = dead STATE["loaded"] = int(time.time()) return len(keys) def next_key(tried=None): with _lock: keys = STATE["keys"] dead = STATE["dead"] live = [k for k in keys if k not in dead] if not live: return None for _ in range(len(live)): k = live[STATE["idx"] % len(live)] STATE["idx"] += 1 if tried and k in tried: continue return k return None def mark_dead(key): with _lock: STATE["dead"].add(key) try: with open(KEYS_FILE, "a", encoding="utf-8") as f: f.write(json.dumps({"key": key, "status": "dead", "ts": int(time.time())}) + "\n") except Exception: pass def proxy(path, body=None, method="POST"): tried = set() last = (502, {"error": {"message": "no live keys"}}) for _ in range(30): key = next_key(tried) if not key: break tried.add(key) req = urllib.request.Request(UPSTREAM + path, data=body, method=method) req.add_header("Authorization", "Bearer " + key) req.add_header("Content-Type", "application/json") req.add_header("Accept", "application/json") req.add_header("User-Agent", UA) t0 = time.time() try: with urllib.request.urlopen(req, timeout=TIMEOUT) as r: out = r.read() print("upstream ok", r.status, key[:6], round(time.time()-t0,1), len(out), flush=True) return r.status, out except urllib.error.HTTPError as e: data = e.read() print("upstream", e.code, key[:6], round(time.time()-t0,1), data[:120], flush=True) if e.code in (401, 403): mark_dead(key) last = (e.code, data) continue if e.code in (429, 500, 502, 503, 504): last = (e.code, data) continue return e.code, data except Exception as ex: print("upstream exc", type(ex).__name__, str(ex)[:120], key[:6], round(time.time()-t0,1), flush=True) last = (502, json.dumps({"error": {"message": "upstream " + str(ex)[:120]}}).encode()) continue return last[0], last[1] class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): return def _send(self, code, payload, ctype="application/json"): if isinstance(payload, str): payload = payload.encode() self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(payload))) self.end_headers() try: self.wfile.write(payload) except Exception: pass def do_GET(self): if self.path.startswith("/healthz"): return self._send(200, json.dumps({"ok": True, "keys": len(STATE["keys"]), "dead": len(STATE["dead"])})) if self.path.startswith("/v1/models"): code, data, _ = (200, b"", {}) tried = set() while True: key = next_key(tried) if not key: return self._send(502, json.dumps({"error": {"message": "no live keys"}})) tried.add(key) req = urllib.request.Request(UPSTREAM + "/models") req.add_header("Authorization", "Bearer " + key) req.add_header("User-Agent", UA) try: with urllib.request.urlopen(req, timeout=30) as r: return self._send(200, r.read()) except urllib.error.HTTPError as e: if e.code in (401, 403): mark_dead(key) continue if e.code == 429: continue return self._send(e.code, e.read()) except Exception as ex: return self._send(502, json.dumps({"error": {"message": str(ex)[:120]}})) return self._send(404, json.dumps({"error": {"message": "not found"}})) def do_POST(self): ln = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(ln) if ln else b"" if self.path.startswith("/admin/reload"): n = load_keys() return self._send(200, json.dumps({"reloaded": n})) if self.path.startswith("/v1/chat/completions") or self.path.startswith("/chat/completions"): try: reqj = json.loads(body or b"{}") except Exception: return self._send(400, json.dumps({"error": {"message": "bad json"}})) reqj["model"] = to_upstream(reqj.get("model")) body = json.dumps(reqj).encode() if reqj.get("stream"): return self._stream(body) code, data = proxy("/chat/completions", body) # empty 200 (uncensored models do this) -> retry on another key for _ in range(2): if code != 200: break try: jj = json.loads(data) ch = jj.get("choices") or [] txt = (ch[0].get("message") or {}).get("content") if ch else "" except Exception: break if txt: break print("empty content, retrying", flush=True) code, data = proxy("/chat/completions", body) return self._send(code, data) return self._send(404, json.dumps({"error": {"message": "not found"}})) def _stream(self, body): tried = set() for _ in range(10): key = next_key(tried) if not key: return self._send(502, json.dumps({"error": {"message": "no live keys"}})) tried.add(key) req = urllib.request.Request(UPSTREAM + "/chat/completions", data=body, method="POST") req.add_header("Authorization", "Bearer " + key) req.add_header("Content-Type", "application/json") req.add_header("Accept", "text/event-stream") req.add_header("User-Agent", UA) try: r = urllib.request.urlopen(req, timeout=TIMEOUT) status = r.status except urllib.error.HTTPError as e: if e.code in (401, 403): mark_dead(key) continue if e.code in (429, 500, 502, 503, 504): continue return self._send(e.code, e.read()) except Exception as ex: continue self.send_response(status) 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 = r.read(1024) if not chunk: break self.wfile.write(chunk) self.wfile.flush() except Exception: pass try: r.close() except Exception: pass return None return self._send(502, json.dumps({"error": {"message": "all keys failed"}})) def main(): n = load_keys() print("crowl-shim keys:", n, "port:", PORT, flush=True) srv = ThreadingHTTPServer(("127.0.0.1", PORT), H) srv.daemon_threads = True srv.serve_forever() if __name__ == "__main__": main()