#!/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 --port 8000 --reasoning-parser 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())