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 tool call inside the reasoning counts only for a declared tool (#804, strict form of #787)
Niko12218d0bb4462042
diff --git a/serve/frontend.py b/serve/frontend.pyindex 02a1d2f9b..34374109c 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -601,10 +601,42 @@ class OutputParser:self.buf += deltaout: list[Event] = []while True:- if self.state == "reasoning":+ if self.state == "rcall":+ # #804: a `<tool_call>` inside the reasoning, with tools declared. It is held whole (never streamed+ # as a call) until it ends: a declared name is then a tool call, anything else stays reasoning text.+ body = self.buf[len(CALL_START):]+ end, think = call_end(body), body.find(THINK_END)+ if end >= 0 and (think < 0 or think >= end):+ call = None+ try:+ name = body[:end].strip()[len("<function="):].split(">", 1)[0]+ if name in self.schemas:+ call = parse_tool_call(body[:end], self.schemas.get(name))+ except ValueError:+ pass+ if call is not None:+ out.append(Event("tool_call", call=call))+ else:+ out.append(Event("reasoning", self.buf[:len(CALL_START) + end + len(CALL_END)]))+ self.buf = body[end + len(CALL_END):]+ self.state = "reasoning"+ elif think >= 0: # the thinking ended inside it: it never was a call+ out.append(Event("reasoning", self.buf[:len(CALL_START) + think]))+ self.buf = body[think:]+ self.state = "reasoning"+ else:+ return out+ elif self.state == "reasoning":i = self.buf.find(THINK_END)+ tool = self.buf.find(CALL_START) if self.schemas else -1+ if tool >= 0 and (i < 0 or tool < i):+ if tool:+ out.append(Event("reasoning", self.buf[:tool]))+ self.buf = self.buf[tool:]+ self.state = "rcall"+ continueif i < 0:- keep = self._hold(self.buf, (THINK_END,))+ keep = self._hold(self.buf, (THINK_END, CALL_START) if self.schemas else (THINK_END,))if len(self.buf) > keep:out.append(Event("reasoning", self.buf[:len(self.buf) - keep]))self.buf = self.buf[len(self.buf) - keep:]@@ -669,7 +701,8 @@ class OutputParser:self._reset_scan()return outif self.buf:- kind = {"reasoning": "reasoning", "content": "content"}.get(self.state, "content")+ # an unfinished call inside the reasoning (#804) is reasoning text, never a call+ kind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content")text = self.buf if self.state != "call" else CALL_START + self.bufout.append(Event(kind, text))self.buf = ""diff --git a/serve/server.py b/serve/server.pyindex fc3b45d40..1048e9125 100644--- a/serve/server.py+++ b/serve/server.py@@ -2381,7 +2381,7 @@ class Service:breakraw_ids.append(t)seg.append(t)- thinking_n += parser.state == "reasoning"+ thinking_n += parser.state in ("reasoning", "rcall")run_len = run_len + 1 if t == run_tok else 1run_tok = tif self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens:@@ -2433,7 +2433,7 @@ class Service:for t in extra:n += 1raw_ids.append(t)- thinking_n += parser.state == "reasoning"+ thinking_n += parser.state in ("reasoning", "rcall")evs = parser.feed(detok.push(t))self._note(n, evs, st, rate)for ev in evs:@@ -2507,7 +2507,7 @@ class Service:hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)"print(f"[strata] done: {n} tokens in {el:.0f} s ({rate:.1f} tok/s) "f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True)- if finish == "length" and parser.state == "reasoning": # #530+ if finish == "length" and parser.state in ("reasoning", "rcall"): # #530print("[strata] the reply reached max tokens while still thinking, so it has no ""answer: a thinking budget (reasoning_budget_tokens, in the request or in ""strata-<model>.json for every request) leaves room to answer", flush=True)diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.pynew file mode 100644index 000000000..a75adcd1d--- /dev/null+++ b/serve/test_reasoning_tools.py@@ -0,0 +1,137 @@+"""serve/test_reasoning_tools.py - #804 (strict form of PR #787): a tool call the model writes inside its reasoning.++A call inside the reasoning counts only when tools are declared and the name is one of them; anything else stays+reasoning text. Without tools the parser is byte-identical to before.++ python -m unittest serve.test_reasoning_tools -v+"""+from __future__ import annotations++import json+import sys+import unittest+import urllib.request+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from serve.frontend import ChatTemplate, OutputParser # noqa: E402+from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402+from serve.test_server import CTX, UnfinishedToolCall # noqa: E402++ROOT = Path(__file__).resolve().parents[1]+CALL = "<tool_call>\n<function=read_file>\n<parameter=limit>\n120\n</parameter>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>"+OTHER = CALL.replace("read_file", "not_declared")+TOOLS = [{"name": "read_file", "parameters": {"properties": {"limit": {"type": "integer"}, "path": {"type": "string"}}}}]+++def run(text, width, tools=TOOLS, thinking=True, stream_tools=True):+ p = OutputParser(thinking=thinking, tools=tools, stream_tools=stream_tools)+ evs = []+ for i in range(0, len(text), width):+ evs += p.feed(text[i:i + width])+ return evs + p.finish()+++def joined(evs, kind):+ return "".join(e.text for e in evs if e.kind == kind)+++class Parser(unittest.TestCase):+ def test_a_declared_call_in_the_reasoning_is_a_call(self):+ text = "before " + CALL + " after</think>\n\nanswer"+ for width in (1, 2, 7, 100_000):+ with self.subTest(width=width):+ evs = run(text, width)+ calls = [e.call for e in evs if e.kind == "tool_call"]+ self.assertEqual([(c.name, c.arguments) for c in calls],+ [("read_file", {"limit": 120, "path": "file.txt"})])+ self.assertEqual(joined(evs, "reasoning"), "before after")+ self.assertEqual(joined(evs, "content"), "answer")+ self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) # never streamed++ def test_an_undeclared_name_stays_reasoning(self):+ text = "see " + OTHER + " done</think>\n\nanswer"+ for width in (1, 5, 100_000):+ with self.subTest(width=width):+ evs = run(text, width)+ self.assertFalse([e for e in evs if e.kind == "tool_call"])+ self.assertEqual(joined(evs, "reasoning"), "see " + OTHER + " done")+ self.assertEqual(joined(evs, "content"), "answer")++ def test_no_tools_declared_is_unchanged(self):+ text = "before " + CALL + " after</think>\n\nanswer"+ for tools in (None, []):+ for width in (1, 7, 100_000):+ with self.subTest(tools=tools, width=width):+ evs = run(text, width, tools=tools)+ self.assertFalse([e for e in evs if e.kind == "tool_call"])+ self.assertEqual(joined(evs, "reasoning"), "before " + CALL + " after")+ self.assertEqual(joined(evs, "content"), "answer")++ def test_an_unfinished_call_is_never_a_call(self):+ for text in ("before<tool_call>\n<function=read_file>\n",+ "before<tool_call>\n<function=read_file>\n<parameter=path>\nfile.txt\n</parameter>\n"):+ for width in (1, 100_000):+ with self.subTest(text=text[-20:], width=width):+ evs = run(text, width)+ self.assertFalse([e for e in evs if e.kind == "tool_call"])+ self.assertEqual(joined(evs, "reasoning"), text)++ def test_the_thinking_ending_inside_a_call_makes_it_text(self):+ text = "a<tool_call>\n<function=read_file>\nhmm</think>\n\nthe answer"+ for width in (1, 100_000):+ with self.subTest(width=width):+ evs = run(text, width)+ self.assertFalse([e for e in evs if e.kind == "tool_call"])+ self.assertEqual(joined(evs, "reasoning"), "a<tool_call>\n<function=read_file>\nhmm")+ self.assertEqual(joined(evs, "content"), "the answer")++ def test_a_call_in_the_answer_is_unchanged(self):+ text = "think</think>\n\nok " + CALL+ for width in (1, 100_000):+ evs = run(text, width)+ self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1)+ self.assertEqual(joined(evs, "reasoning"), "think")++ def test_a_partial_tag_is_held(self):+ p = OutputParser(thinking=True, tools=TOOLS)+ evs = p.feed("hello <tool_c")+ self.assertEqual(joined(evs, "reasoning"), "hello ")+ self.assertEqual(joined(p.feed("ats are nice</think>"), "reasoning"), "<tool_cats are nice")+++class OverHttp(unittest.TestCase):+ def test_finish_reasons_and_block_order(self):+ helper = UnfinishedToolCall("test_parser")+ helper.PROPS = {"path": {"type": "string"}}+ script = "Let me look. <tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n" \+ "</tool_call> More thought.</think>\n\ndone"+ a = helper.answers(script)+ self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]),+ ("tool_calls", [{"path": "file.txt"}]))+ self.assertEqual(a["anthropic", False], ("tool_use", [{"path": "file.txt"}]))+ # the order of the Anthropic stream's blocks: thinking, the call, more thinking, the answer+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ httpd = serve(svc, port=0)+ try:+ body = {"model": "x", "max_tokens": 500, "stream": True, "messages": [{"role": "user", "content": "hi"}],+ "tools": [{"name": "write", "input_schema": {"type": "object", "properties": helper.PROPS}}]}+ req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/messages",+ data=json.dumps(body).encode(), headers={"Content-Type": "application/json",+ "anthropic-version": "2023-06-01"})+ with urllib.request.urlopen(req, timeout=30) as r:+ raw = r.read().decode()+ evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]+ order = [e["content_block"]["type"] for e in evs if e["type"] == "content_block_start"]+ self.assertEqual(order, ["thinking", "tool_use", "thinking", "text"])+ tool = [e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta"+ and e["delta"]["type"] == "input_json_delta"]+ self.assertEqual(json.loads("".join(tool)), {"path": "file.txt"})+ finally:+ httpd.shutdown()+ httpd.server_close()+++if __name__ == "__main__":+ unittest.main()