Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: a reply that ends inside its thinking can be continued once with the thinking closed, opt-in (#1053)
Niko122150ba742bcb2a
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 931f7fb7a..10f181776 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -637,6 +637,10 @@ print(r.choices[0].message.content)part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in`strata-<model>.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default;Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above.+- **A reply that ends inside its thinking (#1053, opt-in).** Some turns write a sentence of reasoning and then the+ end-of-turn token with no `</think>`: the content is empty and an agent stops. `"reasoning_close_retry": true` in+ `strata-<model>.json` closes the thinking once (as the thinking budget does) and continues, once per request, only for+ a reply that ended that way with no answer and no tool call. Off by default.- **A reply stuck on one token is ended (0.1.39, #606).** When a reply repeats the same token 256 times in a row, theserver ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a brokenstate that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` indiff --git a/serve/server.py b/serve/server.pyindex 9e360e0fd..58893a7cb 100644--- a/serve/server.py+++ b/serve/server.py@@ -143,6 +143,9 @@ VISION_START = "<|vision_start|>"# sets it; 0 turns it off.REPEAT_STOP_TOKENS = 256# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)+# #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside <think>, with no answer+# and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it)+REASONING_CLOSE = "\n</think>\n\n"REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see).# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the@@ -2206,6 +2209,7 @@ class Service:self.literals = literal_tags(getattr(tokenizer, "control_tokens", ())) # texts that stay text inside a messageself.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`)+ self.reasoning_close_retry = False # #1053 (opt-in): close the thinking once when a reply ends inside itself.codex_compaction_cache = False # #924 (opt-in): a Codex compaction is rendered with its conversation's toolsself.codex_thread_titles = False # #923 (opt-in): answer Codex's thread-title turns without the engineself.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block@@ -2968,6 +2972,7 @@ class Service:if force and not thinking: # the parser reads it as if the model had written itopening, force = parser.feed(force), Nonetail = "" # the last characters written (the newlines before a call)+ answered, close_retried = False, False # #1053: content or a call came out; the thinking was closedtimings, before = None, None # this request's timings; the engine's `last` before itrecovery_count, reasoning_text, repeat_coverage = 0, "", 0.0looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passages@@ -3051,6 +3056,8 @@ class Service:for ev in evs:if self.reasoning_loop_recovery and ev.kind == "reasoning":reasoning_text += ev.text or ""+ if ev.kind in ("content", "tool_start", "tool_call"):+ answered = Trueyield "event", evif stops is not None and stops.hit is not None:finish = "stop" # gen.close() below STOPs the engine, as for a stop token@@ -3124,6 +3131,27 @@ class Service:f"(coverage={repeat_coverage:.3f}); resuming the same output with the low-effort ""instruction (reasoning_loop_recovery)", flush=True)continue+ if (self.reasoning_close_retry and thinking and finish == "stop" and not close_retried+ and not answered and not wrap and not opens and parser.state == "reasoning"+ and (stops is None or stops.hit is None) and not cancel.is_set()):+ # #1053: the model wrote its reasoning and stopped before </think>: the client would get+ # an empty answer. Close the thinking once and let it answer.+ close_retried = True+ extra = self.tok.encode(REASONING_CLOSE, parse_special=True)+ if max_new - n - len(extra) >= 1:+ print("[strata] the reply ended inside its thinking with no answer: closing the "+ "thinking once and continuing (reasoning_close_retry)", flush=True)+ for t in extra:+ n += 1+ raw_ids.append(t)+ thinking_n += parser.state in ("reasoning", "rcall")+ evs = cut(parser.feed(detok.push(t)))+ self._note(n, evs, st, rate)+ for ev in evs:+ yield "event", ev+ prompt = prompt + seg + extra+ finish = "length"+ continueif not (wrap or opens) or cancel.is_set():break# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a@@ -5156,6 +5184,7 @@ def main() -> int:model_name=cfg.get("model_name", "qwen3.8-flash-next"), vision=vision,sampling_defaults=sampling_defaults,fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)+ svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True # #1053: opt-in, off by defaultsvc.codex_thread_titles = cfg.get("codex_thread_titles") is True # #923: opt-in, off by defaultsvc.codex_compaction_cache = cfg.get("codex_compaction_cache") is True # #924: opt-in, off by defaulttry:diff --git a/serve/test_server.py b/serve/test_server.pyindex 8a07de829..5f2d75c9d 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -2845,6 +2845,64 @@ class ThinkingEngine(MockEngine):yield t+class EndsInsideThinkingEngine(ThinkingEngine):+ """The #1053 reply: one sentence of reasoning, then the end-of-turn token, no </think>. A prompt that ends the+ thinking (the retry) gets the answer."""+ THOUGHT = "Let me think: two plus two is four."++ def generate(self, ids, max_new, sampling, cancel, embeddings=None):+ self.prompts.append(list(ids))+ done = self.tok.decode(ids).endswith("</think>" + chr(10) + chr(10))+ text = self.ANSWER if done else self.THOUGHT+ for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]:+ if cancel.is_set():+ return+ yield t+++class ReasoningCloseRetry(unittest.TestCase):+ """#1053 (opt-in): a reply that ends inside <think> with no answer is continued once with the thinking closed."""++ def setUp(self):+ self.tok = ByteTokenizer()+ self.engine = EndsInsideThinkingEngine(self.tok)+ self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ self.httpd = serve(self.svc, port=0)+ self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"++ def tearDown(self):+ self.httpd.shutdown()+ self.httpd.server_close()++ def chat(self):+ body = {"model": "m", "messages": [{"role": "user", "content": "2+2?"}], "max_tokens": 300}+ req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),+ headers={"Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=30) as r:+ return json.loads(r.read().decode())["choices"][0]++ def test_off_by_default_the_reply_stays_empty(self):+ c = self.chat()+ self.assertEqual(self.engine.prompts.__len__(), 1)+ self.assertFalse(c["message"].get("content"))++ def test_on_it_closes_the_thinking_once_and_answers(self):+ self.svc.reasoning_close_retry = True+ c = self.chat()+ self.assertEqual(len(self.engine.prompts), 2)+ self.assertTrue(self.tok.decode(self.engine.prompts[1]).endswith("</think>" + chr(10) + chr(10)))+ self.assertEqual(c["message"]["content"], EndsInsideThinkingEngine.ANSWER)+ self.assertIn("two plus two is four", c["message"]["reasoning_content"])+ self.assertEqual(c["finish_reason"], "stop")++ def test_a_reply_that_answered_is_not_touched(self):+ self.svc.reasoning_close_retry = True+ self.engine.THOUGHT = "ok</think>" + chr(10) + chr(10) + "Fine."+ c = self.chat()+ self.assertEqual(len(self.engine.prompts), 1)+ self.assertEqual(c["message"]["content"], "Fine.")++class ThinkingBudget(unittest.TestCase):"""#123: reasoning_budget_tokens (opt-in): at the budget the thinking is wrapped up and the model answers,continuing from the prompt plus what it generated plus the wrap-up (a prefix the engine already holds)."""