File size: 15,210 Bytes
39e0f92
 
 
76c2cd2
 
39e0f92
76c2cd2
 
 
 
 
 
 
 
 
 
 
 
 
39e0f92
 
42511fc
76c2cd2
 
 
 
39e0f92
 
76c2cd2
 
 
 
39e0f92
 
 
c144391
 
 
39e0f92
42511fc
39e0f92
 
76c2cd2
39e0f92
 
76c2cd2
 
39e0f92
 
 
76c2cd2
 
 
39e0f92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9547336
 
 
39e0f92
 
9547336
 
 
39e0f92
 
 
9547336
 
 
 
 
 
39e0f92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c144391
 
 
 
 
 
 
 
 
 
 
 
39e0f92
 
 
 
c144391
39e0f92
c144391
 
 
39e0f92
c144391
 
 
39e0f92
 
76c2cd2
 
42511fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76c2cd2
 
 
 
 
 
 
 
 
39e0f92
 
 
76c2cd2
 
 
39e0f92
 
 
 
 
 
 
76c2cd2
 
 
39e0f92
76c2cd2
39e0f92
 
 
 
 
 
 
 
 
 
 
 
 
 
c144391
42511fc
76c2cd2
39e0f92
c144391
76c2cd2
 
c144391
 
 
 
76c2cd2
 
39e0f92
76c2cd2
39e0f92
76c2cd2
 
 
c144391
76c2cd2
39e0f92
 
 
 
 
 
 
 
 
 
 
76c2cd2
39e0f92
76c2cd2
 
c144391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e0f92
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
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


@app.get("/")
async def root():
    return {"status": "ok", "models": list(ROUTES)}


@app.get("/v1/models")
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()
    ]}


@app.get("/debug/recent")
async def debug_recent(request: Request):
    if not authorized(request):
        return JSONResponse({"error": "unauthorized"}, 401)
    return list(recent)


@app.post("/v1/chat/completions")
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


@app.on_event("startup")
async def start_background():
    asyncio.create_task(keep_awake())


@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
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)