Spaces:
Paused
Paused
Download app.py from red-kit/looper-router: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/red-kit/looper-router/resolve/main/app.py
- Command line
-
hf download hf://spaces/red-kit/looper-router/app.py
-
curl -L -o app.py https://huggingface.co/spaces/red-kit/looper-router/resolve/main/app.py
15.2 kB
| import asyncio | |
| import collections | |
| import copy | |
| import json | |
| import os | |
| import re | |
| import time | |
| import httpx | |
| from fastapi import FastAPI, Request | |
| from fastapi.responses import JSONResponse, Response, StreamingResponse | |
| HF_TOKEN = os.environ["HF_TOKEN"] | |
| ROUTER_KEY = os.environ["ROUTER_KEY"] | |
| ROUTES = { | |
| "looper": { | |
| "base": "https://6ac9858de4d5812f4c1a9f75.endpoints.huggingface.cloud/v1", | |
| "model": "s-zaizen/DeepSeek-V4.1-Flash-Abliterated", | |
| "context": 131072, | |
| "max_output": 32768, | |
| "tokenize": True, | |
| }, | |
| "looper flash": { | |
| "base": "https://6ac6f9bf904ec5f3ba7f4e6e.endpoints.huggingface.cloud/v1", | |
| "model": "huihui-ai/Huihui-GLM-5.3-Flash-abliterated-GGUF", | |
| "context": 1048576, | |
| "max_output": 65536, | |
| }, | |
| } | |
| DEFAULT = "looper" | |
| # Fields some OpenAI clients send that these backends either reject or don't implement. | |
| DROP_FIELDS = {"store", "metadata", "service_tier", "prediction", "modalities", "audio", "web_search_options"} | |
| RETRY_STATUSES = {429, 502, 503, 504} | |
| WAKE_TIMEOUT = 600 | |
| FAST_START = 8 | |
| KEEPALIVE_EVERY = 10 | |
| CHARS_PER_TOKEN = 3.0 | |
| MIN_OUTPUT = 8192 | |
| TRUNCATION_NOTE = "[Note: earlier parts of this conversation were omitted to fit the model's context window.]" | |
| app = FastAPI() | |
| client = httpx.AsyncClient(timeout=httpx.Timeout(900.0, connect=30.0)) | |
| recent = collections.deque(maxlen=100) | |
| def route_name(name): | |
| key = " ".join((name or "").strip().lower().replace("-", " ").replace("_", " ").split()) | |
| return key if key in ROUTES else DEFAULT | |
| def authorized(request: Request): | |
| return request.headers.get("authorization", "").removeprefix("Bearer ").strip() == ROUTER_KEY | |
| def text_of(content): | |
| if isinstance(content, list): | |
| return "\n".join(p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") in ("text", "input_text")) | |
| return content | |
| def size(messages): | |
| return len(json.dumps(messages, ensure_ascii=False)) | |
| def has_images(messages): | |
| return any(isinstance(m.get("content"), list) and any(isinstance(p, dict) and p.get("type") == "image_url" for p in m["content"]) | |
| for m in messages) | |
| def normalize(body, route): | |
| for f in DROP_FIELDS: | |
| body.pop(f, None) | |
| if not body.get("stream"): | |
| body.pop("stream_options", None) | |
| if "max_completion_tokens" in body: | |
| mct = body.pop("max_completion_tokens") | |
| body.setdefault("max_tokens", mct) | |
| body["max_tokens"] = min(int(body.get("max_tokens") or route["max_output"]), route["max_output"]) | |
| if not body.get("tools"): | |
| body.pop("tools", None) | |
| body.pop("tool_choice", None) | |
| body.pop("parallel_tool_calls", None) | |
| msgs = [] | |
| for m in body.get("messages", []): | |
| m = dict(m) | |
| if m.get("role") == "developer": | |
| m["role"] = "system" | |
| if m.get("role") == "system" or (m.get("role") == "tool" and not has_images([m])): | |
| m["content"] = text_of(m.get("content")) or "" | |
| if m.get("role") == "assistant": | |
| if isinstance(m.get("content"), list): | |
| m["content"] = text_of(m["content"]) | |
| if m.get("tool_calls") and not m.get("content"): | |
| m["content"] = None | |
| msgs.append(m) | |
| body["messages"] = msgs | |
| def group_turns(messages): | |
| groups = [] | |
| for m in messages: | |
| if m.get("role") == "tool" and groups: | |
| groups[-1].append(m) | |
| else: | |
| groups.append([m]) | |
| return groups | |
| def middle_cut(text, keep): | |
| if len(text) <= keep: | |
| return text | |
| half = keep // 2 | |
| return text[:half] + "\n\n[... content truncated to fit context ...]\n\n" + text[-half:] | |
| def trim(body, max_chars): | |
| """Drop oldest turns (keeping system prompt, first user turn, and tool-call/result pairs intact) until under max_chars.""" | |
| messages = body["messages"] | |
| tools_chars = len(json.dumps(body.get("tools") or [])) | |
| budget = max(max_chars - tools_chars, 2000) | |
| if size(messages) <= budget: | |
| return False | |
| head = [m for m in messages if m.get("role") == "system"] | |
| rest = [m for m in messages if m.get("role") != "system"] | |
| groups = group_turns(rest) | |
| anchor = groups[:1] if groups and groups[0][0].get("role") == "user" else [] | |
| tail = groups[len(anchor):] | |
| def assemble(): | |
| return head + [m for g in anchor + tail for m in g] | |
| while len(tail) > 1 and size(assemble()) > budget: | |
| tail.pop(0) | |
| def shrink(msgs): | |
| for _ in range(12): | |
| over = size(msgs) - budget | |
| if over <= 0: | |
| break | |
| cands = [m for m in msgs if isinstance(m.get("content"), str) and len(m["content"]) > 600] | |
| cands = [m for m in cands if m.get("role") != "system"] or cands | |
| biggest = max(cands, key=lambda m: len(m["content"]), default=None) | |
| if not biggest: | |
| break | |
| biggest["content"] = middle_cut(biggest["content"], max(len(biggest["content"]) - over - 200, 500)) | |
| return msgs | |
| out = shrink(copy.deepcopy(assemble())) | |
| if size(out) > budget and anchor: | |
| anchor = [] | |
| out = shrink(copy.deepcopy(assemble())) | |
| if out and out[0].get("role") == "system": | |
| out[0] = {**out[0], "content": (out[0].get("content") or "") + "\n\n" + TRUNCATION_NOTE} | |
| else: | |
| out.insert(0, {"role": "system", "content": TRUNCATION_NOTE}) | |
| body["messages"] = out | |
| return True | |
| def prompt_tokens_from_error(text): | |
| m = re.search(r"prompt contains at least (\d+) input tokens", text) or re.search(r"(\d+) tokens? in the messages", text) \ | |
| or re.search(r"request \((\d+) tokens\) exceeds", text) or re.search(r"n_prompt_tokens\"?\s*[:=]\s*(\d+)", text) | |
| return int(m.group(1)) if m else None | |
| def is_context_error(status, text): | |
| t = text.lower() | |
| return status == 400 and ("context length" in t or "context size" in t or "exceed_context" in t or "maximum context" in t | |
| or "too long" in t) | |
| def fix_message(obj, requested): | |
| if isinstance(obj, dict): | |
| if "model" in obj: | |
| obj["model"] = requested | |
| for ch in obj.get("choices") or []: | |
| for k in ("message", "delta"): | |
| part = ch.get(k) | |
| if isinstance(part, dict) and "reasoning" in part: | |
| r = part.pop("reasoning") | |
| if r is not None and not part.get("reasoning_content"): | |
| part["reasoning_content"] = r | |
| return obj | |
| async def send_upstream(route, body, log): | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"} | |
| url = route["base"] + "/chat/completions" | |
| deadline = time.time() + WAKE_TIMEOUT | |
| waits = fits = 0 | |
| while True: | |
| try: | |
| resp = await client.send(client.build_request("POST", url, json=body, headers=headers), stream=True) | |
| except httpx.TransportError as e: | |
| log["upstream_errors"].append(f"transport: {e}"[:200]) | |
| if time.time() < deadline: | |
| waits += 1 | |
| log["retries"] = waits | |
| await asyncio.sleep(min(5 * waits, 20)) | |
| continue | |
| return JSONResponse({"error": {"message": f"Upstream unreachable: {e}", "type": "upstream_error"}}, 502) | |
| if resp.status_code < 400: | |
| return resp | |
| err = (await resp.aread()).decode("utf-8", "ignore") | |
| await resp.aclose() | |
| log["upstream_errors"] = (log["upstream_errors"] + [f"{resp.status_code}: {err[:200]}"])[-10:] | |
| if resp.status_code in RETRY_STATUSES and time.time() < deadline: | |
| waits += 1 | |
| log["retries"] = waits | |
| await asyncio.sleep(min(5 * waits, 20)) | |
| continue | |
| if is_context_error(resp.status_code, err) and fits < 5: | |
| fits += 1 | |
| if await fit_context(route, body, log, shrink=0.8 ** fits): | |
| continue | |
| return Response(err, resp.status_code, media_type=resp.headers.get("content-type", "application/json")) | |
| async def count_tokens(route, body): | |
| if not route.get("tokenize"): | |
| return None | |
| url = route["base"].removesuffix("/v1") + "/tokenize" | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| payload = {"model": route["model"], "messages": body["messages"]} | |
| if body.get("tools"): | |
| payload["tools"] = body["tools"] | |
| try: | |
| r = await client.post(url, json=payload, headers=headers, timeout=60) | |
| if r.status_code == 200: | |
| return r.json().get("count") | |
| except httpx.HTTPError: | |
| pass | |
| return None | |
| async def fit_context(route, body, log, shrink=1.0): | |
| """Make prompt + max_tokens fit the context. Uses exact token counts where the backend offers them.""" | |
| ctx = route["context"] | |
| changed = False | |
| for _ in range(5): | |
| chars = size(body["messages"]) + len(json.dumps(body.get("tools") or [])) | |
| n = await count_tokens(route, body) | |
| exact = n is not None | |
| if not exact: | |
| n = int(chars / CHARS_PER_TOKEN / shrink) | |
| log["prompt_tokens_est"] = n | |
| if n + body["max_tokens"] <= ctx - 256 and (exact or shrink == 1.0): | |
| return changed | |
| if n <= ctx - MIN_OUTPUT - 512: | |
| body["max_tokens"] = ctx - n - 512 | |
| log["max_tokens_clamped"] = body["max_tokens"] | |
| return True | |
| body["max_tokens"] = min(body["max_tokens"], MIN_OUTPUT) | |
| ratio = chars / max(n, 1) | |
| target_tokens = ctx - body["max_tokens"] - 1024 | |
| if not trim(body, int(target_tokens * ratio * 0.97)): | |
| return changed | |
| log["trimmed"] += 1 | |
| changed = True | |
| if not exact: | |
| return True | |
| return changed | |
| async def root(): | |
| return {"status": "ok", "models": list(ROUTES)} | |
| async def models(): | |
| now = int(time.time()) | |
| return {"object": "list", "data": [ | |
| {"id": n, "object": "model", "created": now, "owned_by": "looper", | |
| "context_length": r["context"], "max_model_len": r["context"], "max_output_tokens": r["max_output"]} | |
| for n, r in ROUTES.items() | |
| ]} | |
| async def debug_recent(request: Request): | |
| if not authorized(request): | |
| return JSONResponse({"error": "unauthorized"}, 401) | |
| return list(recent) | |
| async def chat(request: Request): | |
| if not authorized(request): | |
| return JSONResponse({"error": {"message": "Invalid API key", "type": "invalid_request_error", "code": "invalid_api_key"}}, 401) | |
| body = await request.json() | |
| requested = body.get("model") or DEFAULT | |
| name = route_name(requested) | |
| route = ROUTES[name] | |
| log = {"t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "requested": requested, "route": name, | |
| "stream": bool(body.get("stream")), "keys": sorted(body.keys()), "n_messages": len(body.get("messages", [])), | |
| "roles": [m.get("role") for m in body.get("messages", [])][-12:], "n_tools": len(body.get("tools") or []), | |
| "chars": size(body.get("messages", [])), "images": has_images(body.get("messages", [])), | |
| "max_tokens_in": body.get("max_tokens") or body.get("max_completion_tokens"), | |
| "retries": 0, "trimmed": 0, "upstream_errors": []} | |
| recent.append(log) | |
| started = time.time() | |
| normalize(body, route) | |
| chars = size(body["messages"]) + len(json.dumps(body.get("tools") or [])) | |
| if (route.get("tokenize") and chars > 150_000) or chars / CHARS_PER_TOKEN + body["max_tokens"] > route["context"] * 0.9: | |
| await fit_context(route, body, log) | |
| body["model"] = route["model"] | |
| task = asyncio.create_task(send_upstream(route, body, log)) | |
| if not body.get("stream"): | |
| resp = await task | |
| log["status"] = resp.status_code | |
| if isinstance(resp, Response): | |
| return resp | |
| content = await resp.aread() | |
| await resp.aclose() | |
| log["seconds"] = round(time.time() - started, 2) | |
| try: | |
| return JSONResponse(fix_message(json.loads(content), requested), resp.status_code) | |
| except ValueError: | |
| return Response(content, resp.status_code, media_type=resp.headers.get("content-type")) | |
| async def relay(resp): | |
| try: | |
| async for line in resp.aiter_lines(): | |
| if line.startswith("data:") and line[5:].strip() not in ("", "[DONE]"): | |
| try: | |
| line = "data: " + json.dumps(fix_message(json.loads(line[5:]), requested), ensure_ascii=False) | |
| except ValueError: | |
| pass | |
| yield line + "\n" | |
| except httpx.HTTPError as e: | |
| log["stream_error"] = str(e)[:200] | |
| err = {"error": {"message": f"Upstream stream interrupted: {e}", "type": "upstream_error"}} | |
| yield "data: " + json.dumps(err) + "\n\n" | |
| finally: | |
| log["seconds"] = round(time.time() - started, 2) | |
| await resp.aclose() | |
| headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"} | |
| done, _ = await asyncio.wait({task}, timeout=FAST_START) | |
| if done: | |
| resp = task.result() | |
| log["status"] = resp.status_code | |
| if isinstance(resp, Response): | |
| return resp | |
| return StreamingResponse(relay(resp), status_code=resp.status_code, media_type="text/event-stream", headers=headers) | |
| # Upstream is slow (cold start or busy slot): commit to a 200 stream and keep the connection alive with SSE comments. | |
| async def delayed(): | |
| try: | |
| while not task.done(): | |
| await asyncio.wait({task}, timeout=KEEPALIVE_EVERY) | |
| if not task.done(): | |
| yield ": keepalive\n\n" | |
| resp = task.result() | |
| log["status"] = resp.status_code | |
| if isinstance(resp, Response): | |
| try: | |
| err = json.loads(resp.body) | |
| except ValueError: | |
| err = {"error": {"message": resp.body.decode("utf-8", "ignore")[:500], "type": "upstream_error"}} | |
| yield "data: " + json.dumps(err) + "\n\n" | |
| return | |
| async for chunk in relay(resp): | |
| yield chunk | |
| finally: | |
| if not task.done(): | |
| task.cancel() | |
| return StreamingResponse(delayed(), media_type="text/event-stream", headers=headers) | |
| async def keep_awake(): | |
| host = os.environ.get("SPACE_HOST") | |
| if not host: | |
| return | |
| while True: | |
| await asyncio.sleep(2 * 3600) | |
| try: | |
| await client.get(f"https://{host}/", timeout=30) | |
| except httpx.HTTPError: | |
| pass | |
| async def start_background(): | |
| asyncio.create_task(keep_awake()) | |
| async def unknown(path: str, request: Request): | |
| recent.append({"t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "unknown_path": f"{request.method} /{path}"}) | |
| return JSONResponse({"error": {"message": f"Unsupported path /{path}", "type": "invalid_request_error"}}, 404) | |