Run this model with HF Jobs

Run KC-Informatics/Crow-9B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/KC-Informatics/Crow-9B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/KC-Informatics/Crow-9B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/KC-Informatics/Crow-9B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/KC-Informatics/Crow-9B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
File size: 33,537 Bytes
cf50a3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#!/usr/bin/env python3
"""nudge.py - make a thinking model always finish with an answer.



A thinking model sometimes spends its whole reply allowance on thinking and stops before it has answered,

so you get an empty reply. This small program sits between your app and the model server and stops that

from happening:



  1. It holds back a slice of the reply allowance (max_tokens) you asked for.

  2. It lets the model think and answer as normal with the rest.

  3. If the model runs out while still thinking, it sends the model its own notes back with one instruction,

     "stop thinking and give the answer now", with thinking switched off, and spends the held-back slice on that.



The total never goes over the max_tokens you asked for. Nothing is voted on and nothing is tried twice: it is

one attempt, finished properly. The model files are not changed; this is only software around them.



Run it next to any OpenAI-compatible server (vLLM, SGLang, llama.cpp server):



    vllm serve <model folder> --port 8000 --reasoning-parser <the parser for your model>

    python nudge.py --upstream http://127.0.0.1:8000 --port 8001



then point your app at http://127.0.0.1:8001/v1 instead of port 8000. The server must be started with a

reasoning parser, so that thinking arrives separately from the answer; without one the nudge never fires.



The nudge only steps in when all of these are true: the request sets max_tokens (or max_completion_tokens)

of at least 1,024, thinking is on, the app is not forcing a tool call, and the model stopped at the limit

with thinking but no answer and no tool call. Everything else passes straight through untouched.



Check it works on your machine, with no model needed:   python nudge.py --self-test

See how often it stepped in:                            http://127.0.0.1:8001/nudge/stats



Needs Python 3.9 or newer and nothing else. Licence: Apache-2.0.

"""
from __future__ import annotations

import argparse
import copy
import http.client
import json
import sys
import threading
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any

NUDGE_TEXT = (
    "Thinking budget reached. Do NOT restart from scratch. Conclude directly from your reasoning above "
    "and output ONLY the final answer in the exact requested format."
)
DRAFT_PREFIX = "Draft reasoning so far:\n"


class UpstreamDown(Exception):
    """The model server could not be reached or hung up before replying."""


class Settings:
    def __init__(self, upstream: str, api_key: str = "", reserve_frac: float = 0.125, reserve_min: int = 256,

                 reserve_max: int = 2048, min_tokens: int = 1024, draft_chars: int = 3600,

                 timeout_s: float = 1800.0, log_path: str = "", verbose: bool = False) -> None:
        u = urllib.parse.urlsplit(upstream if "://" in upstream else "http://" + upstream)
        self.scheme = u.scheme or "http"
        self.host = u.hostname or "127.0.0.1"
        self.port = u.port or (443 if self.scheme == "https" else 80)
        path = (u.path or "").rstrip("/")
        self.base_path = path[:-3] if path.endswith("/v1") else path     # we forward the client's own /v1/... path
        self.api_key = api_key.strip()
        self.reserve_frac = reserve_frac
        self.reserve_min = reserve_min
        self.reserve_max = reserve_max
        self.min_tokens = min_tokens
        self.draft_chars = draft_chars
        self.timeout_s = timeout_s
        self.log_path = log_path
        self.verbose = verbose
        self.lock = threading.Lock()
        self.stats = {"requests": 0, "watched": 0, "nudged": 0, "nudge_failed": 0}

    def count(self, key: str) -> None:
        with self.lock:
            self.stats[key] += 1

    def log(self, row: dict[str, Any]) -> None:
        if not self.log_path:
            return
        row = {"t": round(time.time(), 1), **row}
        with self.lock:
            with open(self.log_path, "a", encoding="utf-8") as f:
                f.write(json.dumps(row) + "\n")

    def open_conn(self) -> http.client.HTTPConnection:
        cls = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection
        return cls(self.host, self.port, timeout=self.timeout_s)


def _limit_key(body: dict[str, Any]) -> str:
    return "max_completion_tokens" if ("max_completion_tokens" in body and "max_tokens" not in body) else "max_tokens"


def plan(body: dict[str, Any], s: Settings) -> tuple[bool, int, int]:
    """-> (watch this request?, allowance for the first pass, slice held back for the answer)."""
    m = body.get(_limit_key(body))
    if not isinstance(m, int) or isinstance(m, bool) or m < s.min_tokens:
        return False, 0, 0
    ctk = body.get("chat_template_kwargs")
    if isinstance(ctk, dict) and ctk.get("enable_thinking") is False:
        return False, 0, 0
    if str(body.get("reasoning_effort") or "").lower() == "none":
        return False, 0, 0
    tc = body.get("tool_choice")
    if tc == "required" or isinstance(tc, dict):
        return False, 0, 0
    if isinstance(body.get("n"), int) and body["n"] > 1:
        return False, 0, 0
    if not isinstance(body.get("messages"), list):
        return False, 0, 0
    reserve = min(s.reserve_max, max(s.reserve_min, int(m * s.reserve_frac)))
    return True, m - reserve, reserve


def second_body(body: dict[str, Any], reasoning: str, reserve: int, s: Settings) -> dict[str, Any]:
    """The follow-up request: the model's own notes plus the instruction to answer now, with thinking off."""
    b = copy.deepcopy(body)
    b["messages"] = list(b["messages"]) + [
        {"role": "assistant", "content": DRAFT_PREFIX + reasoning[-s.draft_chars:]},
        {"role": "user", "content": NUDGE_TEXT},
    ]
    b.pop("max_tokens", None)
    b.pop("max_completion_tokens", None)
    b[_limit_key(body)] = reserve
    ctk = dict(b.get("chat_template_kwargs") or {})
    ctk["enable_thinking"] = False
    b["chat_template_kwargs"] = ctk
    b.pop("reasoning_effort", None)
    t = b.get("temperature")
    if isinstance(t, (int, float)) and not isinstance(t, bool):
        b["temperature"] = max(0.0, float(t) * 0.5)
    return b


def _reasoning_of(d: dict[str, Any]) -> str:
    return str(d.get("reasoning_content") or d.get("reasoning") or "")


def _sum_usage(u1: dict[str, Any] | None, u2: dict[str, Any] | None) -> dict[str, Any] | None:
    if not u1 and not u2:
        return None
    u1, u2 = u1 or {}, u2 or {}
    prompt = int(u1.get("prompt_tokens") or u2.get("prompt_tokens") or 0)
    comp = int(u1.get("completion_tokens") or 0) + int(u2.get("completion_tokens") or 0)
    return {"prompt_tokens": prompt, "completion_tokens": comp, "total_tokens": prompt + comp}


def make_handler(s: Settings):
    class Handler(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def log_message(self, fmt: str, *args: Any) -> None:
            if s.verbose and sys.stderr is not None:
                sys.stderr.write("[nudge] " + (fmt % args) + "\n")

        # ---- plumbing -------------------------------------------------------------------------------------
        def _up_headers(self, n: int | None = None) -> dict[str, str]:
            h = {"Content-Type": self.headers.get("Content-Type") or "application/json", "Connection": "close"}
            if s.api_key:
                h["Authorization"] = "Bearer " + s.api_key
            else:
                auth = (self.headers.get("Authorization") or "").strip()
                if auth and auth.lower() != "bearer":
                    h["Authorization"] = auth
            if n is not None:
                h["Content-Length"] = str(n)
            return h

        def _send_json(self, status: int, obj: Any) -> None:
            raw = json.dumps(obj, ensure_ascii=False).encode("utf-8")
            self._send_raw(status, "application/json", raw)

        def _send_raw(self, status: int, ctype: str, raw: bytes) -> None:
            self.send_response(status)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(raw)))
            self.send_header("Connection", "close")
            self.end_headers()
            self.wfile.write(raw)
            self.close_connection = True

        def _relay(self, method: str, raw_body: bytes | None) -> None:
            """Pass a request straight through and copy the reply back as it arrives."""
            conn = s.open_conn()
            try:
                try:
                    conn.request(method, s.base_path + self.path, body=raw_body,
                                 headers=self._up_headers(len(raw_body) if raw_body is not None else None))
                    resp = conn.getresponse()
                except (OSError, http.client.HTTPException) as exc:
                    raise UpstreamDown(str(exc) or type(exc).__name__) from exc
                self.send_response(resp.status)
                self.send_header("Content-Type", resp.getheader("Content-Type", "application/json"))
                self.send_header("Connection", "close")
                self.end_headers()
                self.close_connection = True
                while True:
                    chunk = resp.read1(65536)
                    if not chunk:
                        break
                    self.wfile.write(chunk)
                    self.wfile.flush()
            finally:
                conn.close()

        def _post_up(self, body: dict[str, Any]) -> tuple[http.client.HTTPConnection, http.client.HTTPResponse]:
            raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
            conn = s.open_conn()
            try:
                conn.request("POST", s.base_path + self.path, body=raw, headers=self._up_headers(len(raw)))
                return conn, conn.getresponse()
            except (OSError, http.client.HTTPException) as exc:
                conn.close()
                raise UpstreamDown(str(exc) or type(exc).__name__) from exc

        # ---- routes ---------------------------------------------------------------------------------------
        def do_GET(self) -> None:
            try:
                if self.path.rstrip("/") == "/nudge/stats":
                    with s.lock:
                        self._send_json(200, dict(s.stats))
                    return
                self._relay("GET", None)
            except UpstreamDown as exc:
                self._send_json(502, {"error": f"could not reach the model server: {exc}"})
            except (BrokenPipeError, ConnectionResetError):
                return
            except Exception as exc:
                try:
                    self._send_json(502, {"error": f"could not reach the model server: {exc}"})
                except Exception:
                    pass

        def do_POST(self) -> None:
            try:
                raw_body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
                if self.path.split("?")[0].rstrip("/") != "/v1/chat/completions":
                    self._relay("POST", raw_body)
                    return
                s.count("requests")
                try:
                    body = json.loads(raw_body.decode("utf-8"))
                except ValueError:
                    self._relay("POST", raw_body)
                    return
                watch, first_max, reserve = plan(body, s) if isinstance(body, dict) else (False, 0, 0)
                if not watch:
                    self._relay("POST", raw_body)
                    return
                s.count("watched")
                first = dict(body)
                first[_limit_key(body)] = first_max
                if body.get("stream"):
                    self._chat_stream(body, first, reserve)
                else:
                    self._chat_plain(body, first, reserve)
            except UpstreamDown as exc:
                try:
                    self._send_json(502, {"error": f"could not reach the model server: {exc}"})
                except Exception:
                    pass
            except (BrokenPipeError, ConnectionResetError):
                return
            except Exception as exc:
                try:
                    self._send_json(502, {"error": f"nudge error: {exc}"})
                except Exception:
                    pass

        # ---- one reply at the end (stream off) ------------------------------------------------------------
        def _chat_plain(self, body: dict[str, Any], first: dict[str, Any], reserve: int) -> None:
            conn = conn2 = None
            nudged = False
            try:
                conn, resp = self._post_up(first)
                raw = resp.read()
                status, ctype = resp.status, resp.getheader("Content-Type", "application/json")
                if status == 200:
                    try:
                        ev = json.loads(raw.decode("utf-8"))
                        ch = (ev.get("choices") or [{}])[0]
                        msg = ch.get("message") or {}
                        thought = _reasoning_of(msg)
                        if (ch.get("finish_reason") == "length" and thought.strip()
                                and not str(msg.get("content") or "").strip() and not msg.get("tool_calls")):
                            try:
                                conn2, resp2 = self._post_up({**second_body(body, thought, reserve, s), "stream": False})
                                raw2, status2 = resp2.read(), resp2.status
                            except (UpstreamDown, OSError, http.client.HTTPException):
                                raw2, status2 = b"", 0
                            if status2 == 200:
                                ev2 = json.loads(raw2.decode("utf-8"))
                                ch2 = (ev2.get("choices") or [{}])[0]
                                msg2 = ch2.get("message") or {}
                                if str(msg2.get("content") or "").strip() or msg2.get("tool_calls"):
                                    msg["content"] = msg2.get("content")
                                    if msg2.get("tool_calls"):
                                        msg["tool_calls"] = msg2["tool_calls"]
                                    ch["finish_reason"] = ch2.get("finish_reason") or "stop"
                                    usage = _sum_usage(ev.get("usage"), ev2.get("usage"))
                                    if usage:
                                        ev["usage"] = usage
                                    ev["nudged"] = True
                                    raw = json.dumps(ev, ensure_ascii=False).encode("utf-8")
                                    nudged = True
                            if not nudged:
                                s.count("nudge_failed")
                    except ValueError:
                        pass
                if nudged:
                    s.count("nudged")
                s.log({"limit": body.get(_limit_key(body)), "stream": False, "nudged": nudged})
                self._send_raw(status, ctype, raw)
            finally:
                for c in (conn, conn2):
                    if c is not None:
                        c.close()

        # ---- word by word (stream on) ---------------------------------------------------------------------
        def _chat_stream(self, body: dict[str, Any], first: dict[str, Any], reserve: int) -> None:
            conn = conn2 = None
            nudged = False
            try:
                conn, resp = self._post_up(first)
                if resp.status != 200:
                    self._send_raw(resp.status, resp.getheader("Content-Type", "application/json"), resp.read())
                    return
                self.send_response(200)
                self.send_header("Content-Type", resp.getheader("Content-Type", "text/event-stream"))
                self.send_header("Cache-Control", "no-cache")
                self.send_header("Connection", "close")
                self.end_headers()
                self.close_connection = True

                def out(obj_or_bytes: Any) -> None:
                    if isinstance(obj_or_bytes, (bytes, bytearray)):
                        self.wfile.write(obj_or_bytes)
                    else:
                        self.wfile.write(b"data: " + json.dumps(obj_or_bytes, ensure_ascii=False).encode("utf-8") + b"\n\n")
                    self.wfile.flush()

                thought: list[str] = []
                saw_answer = saw_tools = saw_done = False
                held: list[dict[str, Any]] = []       # the "ran out" ending, kept back while we try the nudge
                usage1: dict[str, Any] | None = None
                meta: dict[str, Any] = {}
                while True:
                    line = resp.readline()
                    if not line:
                        break
                    text = line.strip()
                    if not text.startswith(b"data:"):
                        if text and not held:
                            out(line)                  # comments / other event fields
                        continue
                    payload = text[5:].strip()
                    if payload == b"[DONE]":
                        saw_done = True
                        break
                    try:
                        ev = json.loads(payload.decode("utf-8"))
                    except ValueError:
                        ev = None
                    if not isinstance(ev, dict):
                        if not held:
                            out(text + b"\n\n")
                        continue
                    for k in ("id", "created", "model", "object", "system_fingerprint"):
                        if k in ev and k not in meta:
                            meta[k] = ev[k]
                    if ev.get("usage"):
                        usage1 = ev["usage"]
                    ran_out = False
                    for ch in ev.get("choices") or []:
                        if not isinstance(ch, dict):
                            continue
                        d = ch.get("delta") or {}
                        r = _reasoning_of(d)
                        if r:
                            thought.append(r)
                        if str(d.get("content") or "").strip():
                            saw_answer = True
                        if d.get("tool_calls"):
                            saw_tools = True
                        if ch.get("finish_reason") == "length" and not saw_answer and not saw_tools and "".join(thought).strip():
                            ran_out = True
                    if ran_out or held:
                        held.append(ev)
                    else:
                        out(ev)

                if held:
                    try:
                        conn2, resp2 = self._post_up({**second_body(body, "".join(thought), reserve, s), "stream": True})
                        if resp2.status == 200:
                            usage2: dict[str, Any] | None = None
                            sent_any = False
                            while True:
                                line2 = resp2.readline()
                                if not line2:
                                    break
                                t2 = line2.strip()
                                if not t2.startswith(b"data:"):
                                    continue
                                p2 = t2[5:].strip()
                                if p2 == b"[DONE]":
                                    break
                                try:
                                    ev2 = json.loads(p2.decode("utf-8"))
                                except ValueError:
                                    continue
                                if not isinstance(ev2, dict):
                                    continue
                                if ev2.get("usage"):
                                    usage2 = ev2["usage"]
                                choices = [c for c in (ev2.get("choices") or []) if isinstance(c, dict)]
                                if not choices:
                                    continue                        # the usage-only chunk; we send our own below
                                if not sent_any:
                                    # last words of thinking that arrived in the held-back chunk
                                    for h in held:
                                        for c in h.get("choices") or []:
                                            d = (c.get("delta") or {}) if isinstance(c, dict) else {}
                                            if _reasoning_of(d):
                                                out({**meta, "choices": [{"index": 0, "delta": d, "finish_reason": None}]})
                                    sent_any = True
                                ev2.update(meta)
                                ev2.pop("usage", None)
                                out(ev2)
                            if sent_any:
                                nudged = True
                                usage = _sum_usage(usage1, usage2)
                                if usage and usage1 is not None:
                                    out({**meta, "choices": [], "usage": usage, "nudged": True})
                    except (BrokenPipeError, ConnectionResetError):
                        raise
                    except Exception:
                        pass                                        # follow-up failed: fall back below
                    if not nudged:
                        s.count("nudge_failed")
                        for h in held:                              # fall back to exactly what the server said
                            out(h)
                if nudged:
                    s.count("nudged")
                s.log({"limit": body.get(_limit_key(body)), "stream": True, "nudged": nudged})
                if saw_done or nudged:
                    out(b"data: [DONE]\n\n")
            finally:
                for c in (conn, conn2):
                    if c is not None:
                        try:
                            c.close()
                        except Exception:
                            pass

    return Handler


def serve(s: Settings, host: str, port: int) -> ThreadingHTTPServer:
    srv = ThreadingHTTPServer((host, port), make_handler(s))
    srv.daemon_threads = True
    return srv


# ---- self-test: a pretend model server, so this can be checked without a GPU ----------------------------------
def _self_test() -> int:
    import urllib.request

    seen: list[dict[str, Any]] = []

    class Fake(BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def log_message(self, *a: Any) -> None:
            pass

        def do_GET(self) -> None:
            raw = b'{"data":[{"id":"fake"}]}'
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(raw)))
            self.end_headers()
            self.wfile.write(raw)

        def do_POST(self) -> None:
            body = json.loads(self.rfile.read(int(self.headers["Content-Length"])).decode("utf-8"))
            seen.append(body)
            lim = body.get("max_tokens") or body.get("max_completion_tokens")
            last = body["messages"][-1]["content"]
            thinking = (body.get("chat_template_kwargs") or {}).get("enable_thinking", True)
            if last == NUDGE_TEXT and "then break" in body["messages"][0]["content"]:
                self.send_response(500)
                self.send_header("Content-Length", "0")
                self.end_headers()
                return
            if last == NUDGE_TEXT:
                thought, answer, fin, used = "", "FINAL 42", "stop", 5
            elif "easy" in last or not thinking:
                thought, answer, fin, used = ("quick thought " if thinking else ""), "EASY 7", "stop", 9
            else:                                   # a hard question: thinks until the allowance is gone
                thought, answer, fin, used = "long thinking " * 40, "", "length", lim or 100
            usage = {"prompt_tokens": 11, "completion_tokens": used, "total_tokens": 11 + used}
            if body.get("stream"):
                self.send_response(200)
                self.send_header("Content-Type", "text/event-stream")
                self.send_header("Connection", "close")
                self.end_headers()
                base = {"id": "chat-1", "object": "chat.completion.chunk", "created": 1, "model": "fake"}

                def w(o: Any) -> None:
                    self.wfile.write(b"data: " + (o if isinstance(o, bytes) else json.dumps(o).encode()) + b"\n\n")

                w({**base, "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}]})
                for i in range(0, len(thought), 80):
                    w({**base, "choices": [{"index": 0, "delta": {"reasoning": thought[i:i + 80]}, "finish_reason": None}]})
                if answer:
                    w({**base, "choices": [{"index": 0, "delta": {"content": answer}, "finish_reason": None}]})
                w({**base, "choices": [{"index": 0, "delta": {}, "finish_reason": fin}]})
                if (body.get("stream_options") or {}).get("include_usage"):
                    w({**base, "choices": [], "usage": usage})
                w(b"[DONE]")
                self.close_connection = True
            else:
                raw = json.dumps({"id": "chat-1", "object": "chat.completion", "model": "fake", "usage": usage, "choices": [
                    {"index": 0, "finish_reason": fin,
                     "message": {"role": "assistant", "reasoning": thought or None, "content": answer or None}}]}).encode()
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(raw)))
                self.end_headers()
                self.wfile.write(raw)

    fake = ThreadingHTTPServer(("127.0.0.1", 0), Fake)
    fake.daemon_threads = True
    threading.Thread(target=fake.serve_forever, daemon=True).start()
    s = Settings(f"http://127.0.0.1:{fake.server_address[1]}/v1")
    front = serve(s, "127.0.0.1", 0)
    threading.Thread(target=front.serve_forever, daemon=True).start()
    url = f"http://127.0.0.1:{front.server_address[1]}"

    def post(body: dict[str, Any]) -> Any:
        req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(),
                                     headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=20) as r:
            raw = r.read().decode("utf-8")
        if not body.get("stream"):
            return json.loads(raw)
        evs = [x[5:].strip() for x in raw.splitlines() if x.startswith("data:")]
        assert evs[-1] == "[DONE]", evs[-3:]
        return [json.loads(x) for x in evs[:-1]]

    def stream_view(evs: list[dict[str, Any]]) -> tuple[str, str, str, dict[str, Any]]:
        think = ans = fin = ""
        usage: dict[str, Any] = {}
        for ev in evs:
            usage = ev.get("usage") or usage
            for ch in ev.get("choices") or []:
                d = ch.get("delta") or {}
                think += d.get("reasoning") or ""
                ans += d.get("content") or ""
                fin = ch.get("finish_reason") or fin
        return think, ans, fin, usage

    hard = {"model": "m", "messages": [{"role": "user", "content": "hard question"}], "max_tokens": 16384, "temperature": 0.6}
    easy = {"model": "m", "messages": [{"role": "user", "content": "easy question"}], "max_tokens": 16384}

    # 1. hard question, one reply: thinking runs out -> nudged -> answer, inside the allowance asked for
    seen.clear()
    r = post(hard)
    assert r["choices"][0]["message"]["content"] == "FINAL 42" and r["choices"][0]["finish_reason"] == "stop", r
    assert r.get("nudged") is True and r["choices"][0]["message"]["reasoning"].startswith("long thinking")
    assert seen[0]["max_tokens"] == 16384 - 2048 and seen[1]["max_tokens"] == 2048, [x["max_tokens"] for x in seen]
    assert seen[1]["chat_template_kwargs"]["enable_thinking"] is False and seen[1]["temperature"] == 0.3
    assert seen[1]["messages"][-2]["content"].startswith(DRAFT_PREFIX) and len(seen[1]["messages"]) == 3
    assert r["usage"]["completion_tokens"] == (16384 - 2048) + 5 <= 16384, r["usage"]

    # 2. hard question, word by word: same result, the "ran out" ending never reaches the app
    seen.clear()
    think, ans, fin, usage = stream_view(post({**hard, "stream": True, "stream_options": {"include_usage": True}}))
    assert ans == "FINAL 42" and fin == "stop" and think.startswith("long thinking"), (ans, fin)
    assert usage["completion_tokens"] == (16384 - 2048) + 5, usage
    assert len(seen) == 2 and seen[1]["stream"] is True

    # 3. easy question: answered first time, nothing added
    for body in (easy, {**easy, "stream": True}):
        seen.clear()
        r = post(body)
        ans = stream_view(r)[1] if body.get("stream") else r["choices"][0]["message"]["content"]
        assert ans == "EASY 7" and len(seen) == 1, (ans, len(seen))

    # 4. left alone: thinking off, small allowance, no allowance, forced tool call
    for extra in ({"chat_template_kwargs": {"enable_thinking": False}}, {"max_tokens": 512}, {"max_tokens": None},
                  {"tool_choice": "required"}):
        seen.clear()
        body = {**hard, **extra}
        if body.get("max_tokens") is None:
            body.pop("max_tokens")
        post(body)
        assert len(seen) == 1 and seen[0].get("max_tokens") == body.get("max_tokens"), (extra, seen)

    # 5. if the follow-up call fails, the app gets exactly what the server said (thinking, ran out), not an error
    for stream in (False, True):
        seen.clear()
        r = post({**hard, "stream": stream, "messages": [{"role": "user", "content": "hard question, then break"}]})
        fin = stream_view(r)[2] if stream else r["choices"][0]["finish_reason"]
        assert fin == "length" and len(seen) == 2, (stream, fin, len(seen))

    # 6. allowance sizes, other routes, counters
    assert plan({"messages": [], "max_tokens": 12288}, s)[1:] == (12288 - 1536, 1536)
    assert plan({"messages": [], "max_tokens": 1024}, s)[1:] == (1024 - 256, 256)
    assert plan({"messages": [], "max_completion_tokens": 8192}, s)[1:] == (8192 - 1024, 1024)
    with urllib.request.urlopen(url + "/v1/models", timeout=10) as r:
        assert json.loads(r.read())["data"][0]["id"] == "fake"
    with urllib.request.urlopen(url + "/nudge/stats", timeout=10) as r:
        st = json.loads(r.read())
    assert st["nudged"] == 2 and st["nudge_failed"] == 2 and st["watched"] == 6, st
    front.shutdown()
    fake.shutdown()
    print("NUDGE_SELF_TEST_OK", st)
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description="Make a thinking model always finish with an answer.")
    ap.add_argument("--upstream", default="http://127.0.0.1:8000", help="your model server (vLLM, SGLang, ...)")
    ap.add_argument("--host", default="127.0.0.1")
    ap.add_argument("--port", type=int, default=8001, help="the port your app should talk to")
    ap.add_argument("--api-key", default="", help="key for the model server, if it needs one")
    ap.add_argument("--reserve-frac", type=float, default=0.125, help="share of max_tokens held back for the answer")
    ap.add_argument("--reserve-min", type=int, default=256)
    ap.add_argument("--reserve-max", type=int, default=2048)
    ap.add_argument("--min-tokens", type=int, default=1024, help="requests with a smaller max_tokens are left alone")
    ap.add_argument("--draft-chars", type=int, default=3600, help="how much of the model's notes to hand back")
    ap.add_argument("--timeout", type=float, default=1800.0)
    ap.add_argument("--log", default="", help="write one line per watched request to this file (no message text)")
    ap.add_argument("--verbose", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return _self_test()
    s = Settings(a.upstream, a.api_key, a.reserve_frac, a.reserve_min, a.reserve_max, a.min_tokens, a.draft_chars,
                 a.timeout, a.log, a.verbose)
    srv = serve(s, a.host, a.port)
    print(f"nudge: listening on http://{a.host}:{a.port}/v1  ->  {s.scheme}://{s.host}:{s.port}{s.base_path}/v1", flush=True)
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass
    return 0


if __name__ == "__main__":
    raise SystemExit(main())