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++
fix(serve): report a tool call cut off by the end of the output as unfinished
Sunil Srivatsa67d5ed427768
diff --git a/serve/frontend.py b/serve/frontend.pyindex 23144e408..48dc2dbf5 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -527,12 +527,13 @@ class OutputParser:self.state, self.lead = "content", Truedef finish(self) -> list[Event]:- """End of generation: flush whatever is held (an unterminated tool call is returned as content)."""+ """End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was+ already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211)."""out = []if self.state == "call" and self.stream_tools and self.scall is not None:out += self._scan() # the output ended inside a call that was already announced- out += self._close_scan()- out.append(Event("tool_call", call=self.scall))+ if self.ss == "done": # only its </tool_call> is missing: the call itself is whole+ out.append(Event("tool_call", call=self.scall))self.buf = ""self._reset_scan()return outdiff --git a/serve/server.py b/serve/server.pyindex 730d309b5..41b4c7e0c 100644--- a/serve/server.py+++ b/serve/server.py@@ -1237,6 +1237,7 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancelyield chunk({"role": "assistant", "content": ""})calls = 0streamed = {} # tool call id -> index, for calls sent piece by piece+ finished = set() # ... and the ones whose final tool_call came (#211)for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel):if kind == "ping":yield None@@ -1258,14 +1259,16 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancelelif ev.kind == "tool_args":yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "function": {"arguments": ev.text}}]})elif ev.kind == "tool_call" and ev.call.id in streamed:- continue+ finished.add(ev.call.id)elif ev.kind == "tool_call":yield chunk({"tool_calls": [{"index": calls, "id": ev.call.id, "type": "function","function": {"name": ev.call.name,"arguments": json.dumps(ev.call.arguments, ensure_ascii=False)}}]})calls += 1else:- finish = "tool_calls" if calls and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"])+ # a streamed call without its final tool_call is one the output ended inside: not "tool_calls" (#211)+ whole = calls and streamed.keys() <= finished+ finish = "tool_calls" if whole and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"])last = chunk({}, finish)pt = x.get("prompt_tokens", len(ids)) # after MCP rounds: the last round's promptlast["usage"] = {"prompt_tokens": pt, "completion_tokens": x["completion_tokens"],@@ -1322,7 +1325,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, candef close():return ("content_block_stop", {"type": "content_block_stop", "index": index})- streamed = set()+ streamed, finished = set(), set() # calls sent piece by piece; those whose final tool_call came (#211)for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel):if kind == "ping":yield None@@ -1334,6 +1337,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can"delta": {"type": "input_json_delta", "partial_json": ev.text}}continueif ev.kind == "tool_call" and ev.call.id in streamed:+ finished.add(ev.call.id)continuewant = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use", "tool_start": "tool_use"}[ev.kind]if ev.kind not in ("tool_call", "tool_start") and not ev.text:@@ -1366,7 +1370,7 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, canelse:if open_kind is not None:yield close()- stop = "tool_use" if used_tool and x["finish"] == "stop" else \+ stop = "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \{"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]]# the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held,# which is cache_read_input_tokens (message_start could only say the whole prompt)@@ -1397,7 +1401,10 @@ def anthropic_collect(events) -> dict:b["_json"] = b.get("_json", "") + d["partial_json"]elif name == "content_block_stop" and blocks and "_json" in blocks[-1]:b = blocks[-1]- b["input"] = json.loads(b.pop("_json") or "{}")+ try:+ b["input"] = json.loads(b.pop("_json") or "{}")+ except ValueError: # a call the output ended inside (#211): it has no input to give+ blocks.pop()elif name == "message_delta":msg["stop_reason"] = e["delta"]["stop_reason"]msg["usage"].update(e["usage"])diff --git a/serve/test_mcp.py b/serve/test_mcp.pyindex 711f172c1..c80c5d015 100644--- a/serve/test_mcp.py+++ b/serve/test_mcp.py@@ -298,6 +298,19 @@ class ToolLoop(unittest.TestCase):self.assertIn("<tool_response>\nhello from the tool\n</tool_response>", second)self.assertEqual(cs[-1]["usage"]["prompt_tokens"], len(self.engine.prompts[1]))+ def test_a_call_the_output_ends_inside_is_not_run(self):+ """#211: the model's turn ends inside an MCP call: nothing runs (it used to run with no arguments)."""+ script = call_script("fake__echo", text="hello from the tool")+ self.start(script[:script.index("from the tool")], "</think>\n\nnever")+ code, text = self.post({"strata_mcp": True})+ self.assertEqual(code, 200, text)+ cs = self.chunks(text)+ mcp = [c["strata_mcp"] for c in cs if "strata_mcp" in c]+ self.assertEqual([m["event"] for m in mcp], ["start"]) # the web app shows it as "Not run" at the end+ self.assertEqual(len(self.engine.prompts), 1)+ self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran+ self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop")+def test_non_stream(self):self.start(call_script("fake__add", a=2, b=3), "</think>\n\n5.")code, text = self.post({"strata_mcp": True}, stream=False)diff --git a/serve/test_server.py b/serve/test_server.pyindex ec2146bab..378687e8d 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -252,6 +252,92 @@ class ToolCallTerminators(unittest.TestCase):self.assertEqual(json.loads(streamed), {"path": "doc.md", "content": self.CONTENT})+class UnfinishedToolCall(unittest.TestCase):+ """#211: a call the output ends inside is not reported as a whole one - its streamed JSON is not closed and the+ finish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run."""+ CALL = ("</think>\n\n<tool_call>\n<function=write>\n<parameter=path>\nnotes.txt\n</parameter>\n"+ "<parameter=content>\n")+ CUT = CALL + "first half of the fi" # the model's turn ends here+ WHOLE = CALL + "all of it\n</parameter>\n</function>\n</tool_call>"+ PROPS = {"path": {"type": "string"}, "content": {"type": "string"}}++ def test_parser(self):+ from serve.frontend import OutputParser+ schema = [{"name": "write", "parameters": {"properties": self.PROPS}}]+ for text, content in ((self.CUT, None), (self.WHOLE, "all of it"),+ (self.WHOLE[:-len("</tool_call>")], "all of it")): # only </tool_call> missing: whole+ for step in (1, 7, 10_000):+ with self.subTest(end=text[-12:], step=step):+ p = OutputParser(thinking=True, tools=schema, stream_tools=True)+ evs = []+ for i in range(0, len(text), step):+ evs += p.feed(text[i:i + step])+ evs += p.finish()+ streamed = "".join(e.text for e in evs if e.kind == "tool_args")+ calls = [e for e in evs if e.kind == "tool_call"]+ if content is None:+ self.assertEqual((calls, streamed), ([], '{"path":"notes.txt","content":"first half of the fi'))+ else:+ self.assertEqual(len(calls), 1)+ self.assertEqual(json.loads(streamed), {"path": "notes.txt", "content": content})++ def answers(self, script):+ """(finish reason, the call's arguments) from OpenAI and Anthropic, whole and streamed, for the model's `script`."""+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}"+ tools = {"openai": [{"type": "function", "function": {"name": "write", "parameters": {+ "type": "object", "properties": self.PROPS}}}],+ "anthropic": [{"name": "write", "input_schema": {"type": "object", "properties": self.PROPS}}]}+ out = {}+ try:+ for api, path in (("openai", "/v1/chat/completions"), ("anthropic", "/v1/messages")):+ for stream in (False, True):+ body = {"model": "x", "max_tokens": 500, "stream": stream, "tools": tools[api],+ "messages": [{"role": "user", "content": "save my notes"}]}+ req = urllib.request.Request(base + path, 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()+ if stream:+ evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]+ if api == "openai":+ out[api, stream] = (evs[-1]["choices"][0]["finish_reason"], "".join(+ (tc.get("function") or {}).get("arguments") or "" for e in evs+ for tc in e["choices"][0]["delta"].get("tool_calls") or []))+ else:+ out[api, stream] = (evs[-2]["delta"]["stop_reason"], "".join(+ e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta"+ and e["delta"]["type"] == "input_json_delta"))+ elif api == "openai":+ c = json.loads(raw)["choices"][0]+ out[api, stream] = (c["finish_reason"], [tc["function"]["arguments"]+ for tc in c["message"].get("tool_calls") or []])+ else:+ m = json.loads(raw)+ out[api, stream] = (m["stop_reason"], [b["input"] for b in m["content"] if b["type"] == "tool_use"])+ finally:+ httpd.shutdown()+ httpd.server_close()+ return out++ def test_a_cut_call(self):+ cut = '{"path":"notes.txt","content":"first half of the fi'+ self.assertEqual(self.answers(self.CUT), {+ ("openai", False): ("stop", [cut]), ("openai", True): ("stop", cut),+ ("anthropic", False): ("end_turn", []), # no input to give: the call is left out+ ("anthropic", True): ("end_turn", cut)})++ def test_a_whole_call(self):+ whole = {"path": "notes.txt", "content": "all of it"}+ a = self.answers(self.WHOLE)+ self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]), ("tool_calls", [whole]))+ self.assertEqual((a["openai", True][0], json.loads(a["openai", True][1])), ("tool_calls", whole))+ self.assertEqual(a["anthropic", False], ("tool_use", [whole]))+ self.assertEqual((a["anthropic", True][0], json.loads(a["anthropic", True][1])), ("tool_use", whole))++class ClientShapes(unittest.TestCase):"""What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into theconversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message."""