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: opt-in recovery of tool calls the model writes next to the template's form, "tool_call_recovery": true (#1172)
Gabe Ortiz5bc479d99a1b
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex e0907c51d..9a053278d 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -704,6 +704,13 @@ print(r.choices[0].message.content)long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every15 s, and `GET /status` says what it is doing (`reading the prompt`, `answering`, tokens so far). Closing theconnection or pressing stop in your app really stops the model, so the next request starts at once.+- **Tool calls in other forms (opt-in).** `"tool_call_recovery": true` in `strata-<model>.json` reads a call of a+ tool the request declared also when the model writes it as `<parameter=NAME>` instead of `<function=NAME>`, as JSON+ (`{"name": ..., "arguments": ...}`) inside `<tool_call>`, as a `<function=NAME>` block at the start of a line+ without `<tool_call>` (outside code), or as a second call inside the same `<tool_call>` (without the switch the+ second call's parameters merge into the first). Anything else in those forms stays the text it is. Measured on+ 1,462 agent turns (Qwen3.8 under Claude Code, from signalnine/q27's drift corpus): 98.3% read as intended with it,+ 92.9% without. Off by default, so what a client gets back is unchanged unless you turn it on.- **Prefill progress in the stream (opt-in).** `"return_progress": true` puts that progress on the stream instead ofsending only the keep-alive, as one extra field on a chunk with an empty delta: `prompt_progress` with `total`,`cache`, `processed` and `time_ms`. Those are llama.cpp's four fields and mean the same there (`time_ms` is the timediff --git a/serve/frontend.py b/serve/frontend.pyindex beedd5fdc..4a65089f4 100644--- a/serve/frontend.py+++ b/serve/frontend.py@@ -610,6 +610,58 @@ def forced_call(tool_choice, tools: list[dict] | None) -> str | None:return None+PARAM_START = "<parameter="+++def function_end(text: str) -> int:+ """Where a `<function=NAME>...</function>` at the start of `text` ends (just past `</function>`), walking its+ parameters with param_end like call_end does; -1: not complete (or not in the call format)."""+ s = text.lstrip()+ pos = len(text) - len(s)+ if not s.startswith(FUNC_START):+ return -1+ gt = text.find(">", pos)+ if gt < 0:+ return -1+ pos = gt + 1+ while True:+ rest = text[pos:]+ s = rest.lstrip()+ pos += len(rest) - len(s)+ if s.startswith(PARAM_START):+ gt = text.find(">", pos)+ if gt < 0:+ return -1+ end = param_end(text[gt + 1:])+ if end < 0:+ return -1+ pos = gt + 1 + end + len(PARAM_END)+ elif s.startswith(FUNC_END):+ return pos + len(FUNC_END)+ else:+ return -1+++def json_tool_call(body: str, schemas: dict) -> ToolCall | None:+ """`{"name": N, "arguments": {...}}` (or "parameters", or the arguments as a JSON string) of a declared tool -> its+ call; anything else -> None."""+ try:+ obj = json.loads(body)+ except ValueError:+ return None+ if not isinstance(obj, dict) or not isinstance(obj.get("name"), str) or obj["name"] not in schemas:+ return None+ args = obj.get("arguments", obj.get("parameters", {}))+ if isinstance(args, str):+ try:+ args = json.loads(args)+ except ValueError:+ return None+ if args is None:+ args = {}+ return ToolCall(name=obj["name"], arguments=args) if isinstance(args, dict) else None++def parse_tool_call(body: str, schema: dict | None = None) -> ToolCall:"""`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decodedwhen the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON@@ -650,7 +702,8 @@ class OutputParser:"""Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held backuntil it is complete, so clients never see `<tool_` or `</thi`."""- def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False):+ def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False,+ recover: bool = False):self.state = "reasoning" if thinking else "content"self.buf = ""self.lead = False@@ -667,8 +720,53 @@ class OutputParser:self.rescued = 0 # calls delivered from the reasoningself.refused = 0 # declared calls kept as reasoning text (quoted, or the turn was cut)self.fence, self.line, self.ticks = "", "", 0+ # recover (opt-in, the config's "tool_call_recovery"): a declared tool's call written next to the template's+ # form is the call - `<parameter=NAME>` as the opener, JSON inside <tool_call>, a bare <function=NAME> at the+ # start of a line outside code, or a second call in the same <tool_call> (which otherwise merges into one).+ self.recover = recover+ self.bare = False # the call being read opened with <function= alone (no <tool_call> around it)+ self.batch = False # the call being finished is followed by another in the same wrapperself._reset_scan()+ def _ok_at(self, p: int) -> bool:+ """self.buf[p] would open a call: at the start of a line, outside a code fence and inline code."""+ snap = (self.fence, self.line, self.ticks)+ self._track(self.buf[:p])+ ok = self._opener_ok()+ self.fence, self.line, self.ticks = snap+ return ok++ def _follower(self, after: str) -> str:+ """recover: what a `<tool_call>` followed (after whitespace) by `after` opens: "call" (`<function=`), "param"+ (a declared tool's name written as `<parameter=NAME>`), "json" (`{`), "wait" (not decided yet) or "text"."""+ if after.startswith(FUNC_START):+ return "call"+ if after.startswith(PARAM_START):+ gt = after.find(">")+ if gt < 0:+ return "wait" if "\n" not in after else "text"+ return "param" if after[len(PARAM_START):gt] in self.schemas else "text"+ if after.startswith("{"):+ return "json" if self.schemas else "text"+ if not after or FUNC_START.startswith(after) or PARAM_START.startswith(after):+ return "wait"+ return "text"++ def _bare_opener(self) -> tuple[int, bool]:+ """recover: the first `<function=` in self.buf that opens a call without the wrapper (start of a line, outside+ code, a declared tool) -> (position, decided); (-1, False) for none. A name still arriving is undecided."""+ p = self.buf.find(FUNC_START)+ while p >= 0:+ if self._ok_at(p):+ gt = self.buf.find(">", p)+ name = self.buf[p + len(FUNC_START):gt if gt >= 0 else len(self.buf)]+ if gt < 0 and not any(c.isspace() for c in name):+ return p, False+ if gt >= 0 and name in self.schemas:+ return p, True+ p = self.buf.find(FUNC_START, p + 1)+ return -1, False+def _track(self, text: str) -> str:"""Follow the reasoning text that has gone out: the open code fence, the current line, and the backticks ofthe current paragraph. Returns the text."""@@ -920,10 +1018,30 @@ class OutputParser:return outself.buf, self.lead = stripped, Falsei = self.buf.find(CALL_START)+ b, decided = self._bare_opener() if self.recover and self.schemas else (-1, False)+ if b >= 0 and (i < 0 or b < i):+ # recover: <function=NAME> alone at the start of a line - the call without its <tool_call>.+ # Until the name has arrived it is held.+ j = b+ while j > 0 and self.buf[j - 1] == "\n":+ j -= 1+ if j > 0 and self.buf[:j].strip():+ out.append(Event("content", self._track(self.buf[:j])))+ if not decided:+ self.buf = self.buf[j:]+ return out+ self.buf = self.buf[b:]+ self.state, self.bare = "call", True+ continueif i < 0:# Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped,# so emitting them early would make streamed and whole outputs differ.j = len(self.buf) - self._hold(self.buf, (CALL_START,))+ if self.recover and self.schemas: # a line that may be becoming a bare <function=+ k = self.buf.rfind("\n") + 1+ tail = self.buf[k:]+ if tail and FUNC_START.startswith(tail) and self._ok_at(k):+ j = min(j, k)while j > 0 and self.buf[j - 1] == "\n":j -= 1if j > 0:@@ -944,6 +1062,19 @@ class OutputParser:# it is prose that names the format ("I'll use a <tool_call> block") - content, not a malformed call# that ends the request. Until its follower has arrived it is held, like a partial tag.after = self.buf[i + len(CALL_START):].lstrip()+ kind = self._follower(after) if self.recover else None+ if kind in ("param", "json"):+ if i and self.buf[:i].strip():+ out.append(Event("content", self._track(self.buf[:i].rstrip("\n"))))+ rest = self.buf[i + len(CALL_START):]+ if kind == "param": # <parameter=NAME> as the opener: the call's <function=NAME>+ at = len(rest) - len(after)+ rest = rest[:at] + FUNC_START + after[len(PARAM_START):]+ self.buf = rest+ self.state = "call" if kind == "param" else "json"+ continue+ if kind == "wait":+ after = ""if after and not after.startswith(FUNC_START) and not FUNC_START.startswith(after):out.append(Event("content", self._track(self.buf[:i + len(CALL_START)])))self.buf = self.buf[i + len(CALL_START):]@@ -960,8 +1091,42 @@ class OutputParser:out.append(Event("content", self._track(self.buf[:i].rstrip("\n"))))self.buf = self.buf[i + len(CALL_START):]self.state = "call"+ elif self.state == "json":+ # recover: `{"name": ..., "arguments": {...}}` inside the wrapper is the call once its </tool_call> has+ # arrived and it names a declared tool; anything else is the text it is+ i = self.buf.find(CALL_END)+ if i < 0:+ return out+ call = json_tool_call(self.buf[:i].strip(), self.schemas)+ if call is None:+ out.append(Event("content", self._track(CALL_START + self.buf[:i + len(CALL_END)])))+ else:+ out.append(Event("tool_call", call=call))+ self.buf = self.buf[i + len(CALL_END):]+ self.state, self.lead = "content", call is not Noneelse:- i = call_end(self.buf)+ drop = None+ if self.bare: # no wrapper: the call ends at its </function>; a stray+ i = function_end(self.buf) # </tool_call> after it is the wrapper's closer, dropped+ if i >= 0:+ after = self.buf[i:].lstrip()+ if after.startswith(CALL_END):+ drop = len(self.buf[i:]) - len(after) + len(CALL_END)+ elif after and not CALL_END.startswith(after):+ drop = 0+ else:+ i = call_end(self.buf)+ if i >= 0:+ drop = len(CALL_END)+ if self.recover: # a batch in one wrapper: the next call follows this one's+ f = function_end(self.buf) # </function> (or opens as <parameter=NAME>)+ nxt = self.buf[f:].lstrip() if f >= 0 else ""+ if nxt.startswith(PARAM_START) and self._follower(nxt) == "param":+ at = len(self.buf) - len(nxt)+ self.buf = self.buf[:at] + FUNC_START + nxt[len(PARAM_START):]+ nxt = self.buf[at:]+ if nxt.startswith(FUNC_START):+ i, drop, self.batch = f, 0, Trueif self.stream_tools:if i >= 0:whole, self.buf = self.buf, self.buf[:i] # scan only the body@@ -970,17 +1135,14 @@ class OutputParser:self.buf = wholeelse:out += self._scan()- if i < 0:+ if i < 0 or drop is None:return outbody = self.buf[:i]- self.buf = self.buf[i + len(CALL_END):]- name = body.strip()[len("<function="):].split(">", 1)[0]- call = parse_tool_call(body, self.schemas.get(name))- if self.scall is not None:- call.id = self.scall.id- out.append(Event("tool_call", call=call))- self._reset_scan()- self.state, self.lead = "content", True+ self.buf = self.buf[i + drop:]+ batch, self.batch = self.batch, False+ out += self._finish_call(body)+ if batch and out[-1].kind == "tool_call":+ self.state, self.lead = "call", Falsedef finish(self, reason: str | None = None) -> list[Event]:"""End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was@@ -990,6 +1152,14 @@ class OutputParser:out = []if self.pending:out += self._release(reason in (None, "stop") and self.state == "reasoning" and not self.buf)+ if self.state == "call" and self.bare and function_end(self.buf) >= 0:+ i = function_end(self.buf) # recover: a bare call is whole at its </function>+ body, rest = self.buf[:i], self.buf[i:].strip()+ self.buf = ""+ out += self._finish_call(body)+ if rest and not CALL_END.startswith(rest):+ out.append(Event("content", self._track(rest)))+ return outif 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 announcedif self.ss == "done": # only its </tool_call> is missing: the call itself is whole@@ -1000,7 +1170,26 @@ class OutputParser:if self.buf:# an unfinished call inside the reasoning (#804) is reasoning text, never a callkind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content")- text = self.buf if self.state != "call" else CALL_START + self.buf+ text = CALL_START + self.buf if self.state in ("call", "json") and not self.bare else self.bufout.append(Event(kind, text))self.buf = ""return out++ def _finish_call(self, body: str) -> list[Event]:+ """A whole call body in the template's form -> its tool_call event. With recover, one that still does not+ parse is the text it is instead of an error that ends the request."""+ name = body.strip()[len(FUNC_START):].split(">", 1)[0]+ bare, self.bare = self.bare, False+ try:+ call = parse_tool_call(body, self.schemas.get(name))+ except ValueError:+ if not self.recover:+ raise+ self._reset_scan()+ self.state = "content"+ return [Event("content", self._track(body if bare else CALL_START + body + CALL_END))]+ if self.scall is not None:+ call.id = self.scall.id+ self._reset_scan()+ self.state, self.lead = "content", True+ return [Event("tool_call", call=call)]diff --git a/serve/server.py b/serve/server.pyindex 208869102..005ab72fa 100644--- a/serve/server.py+++ b/serve/server.py@@ -2320,6 +2320,7 @@ class Service:self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none)self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off)self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False+ self.tool_call_recovery = False # opt-in: tool calls in forms next to the template'sself.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +tokenizer.encode("<|endoftext|>", parse_special=True))@@ -2997,7 +2998,7 @@ class Service:sampling = {**defaults, **req_values}# #123: read after the merge, so a budget shared through POST /settings is seen like the other keysbudget = self.reasoning_budget(sampling) if thinking else None- parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True)+ parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True, recover=self.tool_call_recovery)detok, n, finish = Detokenizer(self.tok), 0, "length"run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated tokenthinking_n = 0 # tokens written while thinking (Responses' reasoning_tokens)@@ -5294,6 +5295,10 @@ def main() -> int:if mode not in ("model", "on_request"):raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}")svc.anthropic_think_unasked = mode == "model"+ recovery = cfg.get("tool_call_recovery", False) # opt-in: see OutputParser's recover+ if not isinstance(recovery, bool):+ raise SystemExit(f"[strata] config \"tool_call_recovery\" must be true or false, not {recovery!r}")+ svc.tool_call_recovery = recoveryrs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS) # #606: opt-out with 0if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0:raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}")diff --git a/serve/test_server.py b/serve/test_server.pyindex c510d9db7..c2bf362e0 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -1009,6 +1009,133 @@ class ToolCallTagInProse(unittest.TestCase):([], "The format starts with <tool_call>"))+class ToolCallRecovery(unittest.TestCase):+ """Opt-in ("tool_call_recovery": true): the model sometimes writes a call in a form next to the template's. These+ shapes are from a corpus of 1,462 agent turns (Qwen3.8 under Claude Code, signalnine/q27): with the switch on, a+ declared tool's call in one of them is the call; anything else stays content, verbatim."""+ SCHEMA = ToolCallTerminators.SCHEMA+ PARAMS = "<parameter=path>\na.md\n</parameter>\n<parameter=content>\nhi\n</parameter>\n</function>"+ CALL = {"path": "a.md", "content": "hi"}+ RECOVER = True++ def parse(self, text, stream_tools, step):+ from serve.frontend import OutputParser+ p = OutputParser(thinking=True, tools=self.SCHEMA, stream_tools=stream_tools, recover=self.RECOVER)+ evs = []+ for i in range(0, len(text), step):+ evs += p.feed(text[i:i + step])+ evs += p.finish()+ calls = [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"]+ if stream_tools: # every announced call's streamed JSON is its final arguments+ for c in [e for e in evs if e.kind == "tool_call"]:+ streamed = "".join(e.text for e in evs if e.kind == "tool_args" and e.call is not None+ and e.call.id == c.call.id)+ if streamed:+ self.assertEqual(json.loads(streamed), c.call.arguments)+ return calls, "".join(e.text for e in evs if e.kind == "content").strip()++ def check(self, text, calls, content):+ for stream_tools in (False, True):+ for step in (1, 7, 10_000):+ with self.subTest(stream_tools=stream_tools, step=step):+ self.assertEqual(self.parse("</think>\n\n" + text, stream_tools, step), (calls, content))++ def test_parameter_as_the_opener(self):+ # corpus 300dfba2 (x11): the tool's name written as a parameter tag+ self.check(f"<tool_call>\n<parameter=write>\n{self.PARAMS}\n</tool_call>", [("write", self.CALL)], "")++ def test_parameter_opener_that_is_not_a_tool_is_content(self):+ text = "<tool_call>\n<parameter=path>\na.md\n</parameter>\n</function>\n</tool_call>"+ self.check(text, [], text)++ def test_json_in_the_wrapper(self):+ # corpus 5e847539 (x6): the JSON form inside the XML wrapper+ for key in ("arguments", "parameters"):+ with self.subTest(key=key):+ self.check('<tool_call>\n{"name": "write", "%s": {"path": "a.md", "content": "hi"}}\n</tool_call>'+ % key, [("write", self.CALL)], "")+ self.check('<tool_call>\n{"name": "write", "arguments": "{\\"path\\": \\"a.md\\", \\"content\\": \\"hi\\"}"}'+ '\n</tool_call>', [("write", self.CALL)], "")++ def test_json_of_an_unknown_tool_is_content(self):+ text = '<tool_call>\n{"name": "format_disk", "arguments": {}}\n</tool_call>'+ self.check(text, [], text)++ def test_broken_json_is_content_not_an_error(self):+ text = '<tool_call>\n{"name": "write", "arguments": {"path": \n</tool_call>'+ self.check(text, [], text)++ def test_json_never_closed_is_content(self):+ text = '<tool_call>\n{"name": "write", "arguments": {"path": "a.md"}}'+ self.check(text, [], text)++ def test_bare_function_without_the_wrapper(self):+ # corpus 395efd4c / 6e71eed4 (x5 each): <function=...> with no <tool_call> around it+ self.check(f"Writing it now.\n\n<function=write>\n{self.PARAMS}", [("write", self.CALL)], "Writing it now.")+ self.check(f"<function=write>\n{self.PARAMS}\n</tool_call>", [("write", self.CALL)], "") # stray closer+ self.check(f"<function=write>\n{self.PARAMS}\nDone.", [("write", self.CALL)], "Done.")++ def test_two_calls_in_one_wrapper(self):+ # corpus 0912870b / 51b155c9: a batch inside one <tool_call> - the second call's parameters were merged into+ # the first (wrong arguments, one call); also with the second opened as <parameter=NAME> (03a8a851)+ two = {"path": "b.md", "content": "yo"}+ second = "<parameter=path>\nb.md\n</parameter>\n<parameter=content>\nyo\n</parameter>\n</function>"+ for opener in ("<function=write>", "<parameter=write>"):+ with self.subTest(opener=opener):+ self.check(f"<tool_call>\n<function=write>\n{self.PARAMS}\n{opener}\n{second}\n</tool_call>",+ [("write", self.CALL), ("write", two)], "")++ def test_bare_function_stays_text_where_it_is_not_a_call(self):+ fenced = f"Example:\n```\n<function=write>\n{self.PARAMS}\n```"+ self.check(fenced, [], fenced)+ inline = "Call it as <function=write> with a path."+ self.check(inline, [], inline)+ unknown = "<function=format_disk>\n<parameter=x>\n1\n</parameter>\n</function>"+ self.check(unknown, [], unknown)+++class ToolCallRecoveryOff(unittest.TestCase):+ """Without the switch the parser returns what it always did for the same shapes (the default stays as it is)."""++ def parse(self, text):+ from serve.frontend import OutputParser+ p = OutputParser(thinking=True, tools=ToolCallRecovery.SCHEMA, stream_tools=True)+ evs = p.feed("</think>\n\n" + text) + p.finish()+ return ([e.call.name for e in evs if e.kind == "tool_call"],+ "".join(e.text for e in evs if e.kind == "content").strip())++ def test_drifted_forms_stay_text(self):+ P = ToolCallRecovery.PARAMS+ for text in (f"<tool_call>\n<parameter=write>\n{P}\n</tool_call>",+ '<tool_call>\n{"name": "write", "arguments": {"path": "a.md", "content": "hi"}}\n</tool_call>',+ f"<function=write>\n{P}"):+ with self.subTest(text=text[:30]):+ self.assertEqual(self.parse(text), ([], text))++ def test_a_batch_is_one_call(self):+ P = ToolCallRecovery.PARAMS+ calls, _ = self.parse(f"<tool_call>\n<function=write>\n{P}\n<function=write>\n{P}\n</tool_call>")+ self.assertEqual(calls, ["write"])+++class ToolCallRecoverySwitch(unittest.TestCase):+ """The config's "tool_call_recovery" reaches the parser of every reply."""++ def run_reply(self, on):+ tok = ByteTokenizer()+ script = "</think>\n\n<function=write>\n" + ToolCallRecovery.PARAMS+ svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ svc.tool_call_recovery = on+ with contextlib.redirect_stdout(io.StringIO()):+ evs = [x for kind, x in svc.run(tok.encode("hi"), True, ToolCallRecovery.SCHEMA, 3000, {},+ threading.Event()) if kind == "event"]+ return [e.call.arguments for e in evs if e.kind == "tool_call"]++ def test_switch(self):+ self.assertEqual(self.run_reply(False), [])+ self.assertEqual(self.run_reply(True), [ToolCallRecovery.CALL])++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 thefinish reason is not "tool_calls" / "tool_use" - so a client can tell it from a call to run."""