Skip to content

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 thinking is a call only when it was an act (#804, #1058)

Niko122138357f1858da
diff --git a/serve/fixtures/rcall_specimens.json b/serve/fixtures/rcall_specimens.json
new file mode 100644
index 000000000..199c6d32b
--- /dev/null
+++ b/serve/fixtures/rcall_specimens.json
@@ -0,0 +1,375 @@
+{
+ "_about": "Recorded and constructed reasoning outputs for #804/#1058. 25 entries from PR #525's corpus (talisp, 47Hunter47 and reviewers) and 12 live strandings recovered by 47Hunter47 (https://gist.github.com/47Hunter47/4abcd3a80701f5634f85b96e4c067cc3). 'calls' = the tool names delivered as calls under the #1058 rules. Mixed tails (a declared call beside a wrapper call naming no declared tool): the declared call is delivered, the wrapper stays reasoning.",
+ "specimens": [
+ {
+ "name": "act-natural-stop",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The user asked what the file contains. Reading it first is the right step, and then I can summarize what is inside.\n\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code"
+ ]
+ },
+ {
+ "name": "act-first-text",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code"
+ ]
+ },
+ {
+ "name": "act-two-adjacent",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The comparison needs both files. I will read them one after the other.\n\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code",
+ "execute_code"
+ ]
+ },
+ {
+ "name": "envelope-undeclared",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The tool for this step is not in my visible list, so it goes through the wrapper with a single entry.\n\n<tool_call>\n<function=tool_call>\n<parameter=calls>\n[{\"name\": \"execute_code\", \"arguments\": {\"code\": \"print(1)\"}}]\n</parameter>\n</function>\n</tool_call>",
+ "calls": []
+ },
+ {
+ "name": "envelope-declared",
+ "finish": "stop",
+ "tools": [
+ "execute_code",
+ "tool_call"
+ ],
+ "input": "The tool for this step is not in my visible list, so it goes through the wrapper with a single entry.\n\n<tool_call>\n<function=tool_call>\n<parameter=calls>\n[{\"name\": \"execute_code\", \"arguments\": {\"code\": \"print(1)\"}}]\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "tool_call"
+ ]
+ },
+ {
+ "name": "mention-backticks-midsentence",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Before answering, a note on the wire protocol: I must emit `<tool_call>` then `<function=execute_code>` - the format.\nWith that settled, the plan is clear.",
+ "calls": []
+ },
+ {
+ "name": "mention-midsentence-whole-call",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The format is <tool_call>\n<function=execute_code>\n</function>\n</tool_call> ok.\nI will follow it for the real call next.",
+ "calls": []
+ },
+ {
+ "name": "mention-backticks-line-start",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Plan:\n`<tool_call>\n<function=execute_code>` comes next.\nThat is the shape the harness wants.",
+ "calls": []
+ },
+ {
+ "name": "mention-line-start-no-function",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Next step:\n<tool_call> is the tag the format starts with.\nThe parameters follow it.",
+ "calls": []
+ },
+ {
+ "name": "mention-line-start-other-tag",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Example:\n<tool_call>\n<parameter=code>\nx\n</parameter>\nThe body would continue here.",
+ "calls": []
+ },
+ {
+ "name": "mention-indented",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "As a list:\n <tool_call>\n <function=execute_code>\n ...and so on for each field.\nThat covers the layout.",
+ "calls": []
+ },
+ {
+ "name": "mention-markdown-quote",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The doc says:\n> <tool_call>\n> <function=execute_code>\nand that is all it says about calling.",
+ "calls": []
+ },
+ {
+ "name": "mention-backtick-block",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Format:\n```xml\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n```\nThat is how a call looks, for reference.",
+ "calls": []
+ },
+ {
+ "name": "mention-tilde-block",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Format:\n~~~\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n~~~\nDone, that is the whole example.",
+ "calls": []
+ },
+ {
+ "name": "mention-tag-before-think-end",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "So I call it:\n<tool_call>\n</think>Here is the answer to your question.",
+ "calls": []
+ },
+ {
+ "name": "mention-closed-span-fenced",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "This is a documentation example, not an action:\n```xml\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n```\nI should explain it without calling any tool.\n</think>Here is the explanation.",
+ "calls": []
+ },
+ {
+ "name": "mention-unclosed-disclaimed",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "This is a documentation example, not an action:\n```xml\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n```\nI should explain it without calling any tool.",
+ "calls": []
+ },
+ {
+ "name": "cut-max-tokens",
+ "finish": "length",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "I could run\n<tool_call>\n<function=execute_code>\n<parameter=code>\nrm -rf build\n</parameter>\n</function>\n</tool_call>\nbut first let me check what build holds...",
+ "calls": []
+ },
+ {
+ "name": "mention-midsentence-declared",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "I could run <tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": []
+ },
+ {
+ "name": "mention-trailing-prose",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "The file is small, so one read is enough.\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\nlet me see what comes back.",
+ "calls": []
+ },
+ {
+ "name": "mention-prose-between-calls",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Both are needed.\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call> and also <tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": []
+ },
+ {
+ "name": "mention-empty-span",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Next:\n<tool_call>\n</tool_call>\nNothing further to add.",
+ "calls": []
+ },
+ {
+ "name": "known-miss-bare-function-opener",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Let me run it.\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>",
+ "calls": []
+ },
+ {
+ "name": "normal-call-after-think-end",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "I must emit `<tool_call>` then `<function=execute_code>` - the format.\n</think>\n\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code"
+ ]
+ },
+ {
+ "name": "mixed-declared-and-envelope",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Two things to do, so both calls go out together.\n\n<tool_call>\n<function=execute_code>\n<parameter=code>\nprint(1)\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=tool_call>\n<parameter=calls>\n[{\"name\": \"execute_code\", \"arguments\": {\"code\": \"print(1)\"}}]\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code"
+ ]
+ },
+ {
+ "name": "live-01-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "I'm spotting an off-by-one error in my struct unpacking logic. The GGUF header structure is: magic (4 bytes), version (4 bytes), n_tensors (8 bytes),\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\ntimeout 60 ssh -o connecttimeout=10 <host> 'python3 - <<PY\nimport struct\np=\"<private-path> …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal"
+ ]
+ },
+ {
+ "name": "live-02-declared",
+ "finish": "length",
+ "tools": [
+ "read_file"
+ ],
+ "input": "I should check the <tool> project note to see what's already been completed and what's still open, then look at the current live state to understand w\n\n\n<tool_call>\n<function=read_file>\n<parameter=path>\nC:\\Users\\Ai\\Documents\\<private-path>\n</parameter>\n<parameter=limit>\n120\n</parameter>\n</function>\n</tool_call>",
+ "calls": []
+ },
+ {
+ "name": "live-03-envelope",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "<tool>'a güncelemeyi yapmalıyım ve skill'e de patch atmalıyım. <tool>'a eklenmesi gereken önemli bilgi var — bu bir ders değil, ama bir ilerleme kaydı\n\n\n<tool_call>\n<function=tool_call>\n<parameter=calls>\n[{\"arguments\": {\"note_name\": \"Projeler/<project>\n</parameter>\n</function>\n</tool_call>",
+ "calls": []
+ },
+ {
+ "name": "live-04-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal",
+ "web_extract"
+ ],
+ "input": "Looking at the Hermes vision setup, the main model needs to support vision inputs directly—images pasted into the CLI get sent as multimodal input. Th\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\nssh -o ConnectTimeout=8 <host> 'cd <private-path>\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=web_extract>\n<parameter=char_limit>\n8000\n</parameter>\n<parameter=urls>\n[\"https://hermes-agent.nousresearch.com/docs/user-guide/features/vision\"]\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal",
+ "web_extract"
+ ]
+ },
+ {
+ "name": "live-05-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "Strata şu anda IQ3_XXS modelini port 8080'de serving ediyor ve görsel modaliteleri destekliyor. GPU PC'deki Hermes kurulumu `<private-path>\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\n/c/Windows/System32/OpenSSH/ssh.exe -o BatchMode=yes <host> 'echo \"=== hermes version ===\" …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal"
+ ]
+ },
+ {
+ "name": "live-06-envelope",
+ "finish": "stop",
+ "tools": [
+ "todo_list"
+ ],
+ "input": "Tamam, bitti. Şimdi son bir kontroller:\n\n\n<tool_call>\n<function=todo_list>\n<parameter=todos>\n[{\"content\": \"Tum profillerdeki skill dizinlerini keşfet\", \"id\": \"1\", \"status\": \"completed …\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=tool_call>\n<parameter=calls>\n[{\"name\": \"mcp__obsidian_vault__mcp_obsidian_create_note\", \"arguments\": {\"path\": \"AI Stack …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "todo_list"
+ ]
+ },
+ {
+ "name": "live-07-declared",
+ "finish": "stop",
+ "tools": [
+ "search_files"
+ ],
+ "input": "Index.md'yi kontrol edip güncellemem gerekiyor, sonra skill'i yamamam, backup dosyasını silmem, commit ve push işlemini yapmam, codegraph sync ve grap\n\n\n<tool_call>\n<function=search_files>\n<parameter=context>\n2\n</parameter>\n<parameter=output_mode>\ncontent\n</parameter>\n<parameter=path>\nC:\\Users\\Ai\\Documents\\<private-path>\n</parameter>\n<parameter=pattern>\nemulat|Emulat|borç|kopya\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "search_files"
+ ]
+ },
+ {
+ "name": "live-08-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "Now the full picture is in place. Let me audit the claims in the environment hint one by one:\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\ndate \"+%Y-%m-%d %A %Z %z\"; echo ---; sed -n '60,64p' \"/c/Users/Ai/AppData/Local/hermes/con …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal"
+ ]
+ },
+ {
+ "name": "live-09-declared",
+ "finish": "stop",
+ "tools": [
+ "execute_code"
+ ],
+ "input": "Önemli bir çelişkiyi fark ettim. Kullanıcının yerel makinesi Windows ve şu anda <host> adresinde. 21 Ağustos tarihli bir kayıt eski IP'lerin artık geç\n\n\n<tool_call>\n<function=execute_code>\n<parameter=code>\nimport re\ndef show(pat, label, maxn=30):\n hits=[r for r in recs if re.search(pat, r.get …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "execute_code"
+ ]
+ },
+ {
+ "name": "live-10-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "I'm noticing the plugin already handles max_tokens in mem0.json, so I should check how LlmConfig is set up around lines 360-380 and look for any max_t\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\nsed -n 300,470p \"C:/Users/Ai/AppData/Local/hermes/plugins/mem0-local/__init__.py\"\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal"
+ ]
+ },
+ {
+ "name": "live-11-declared",
+ "finish": "stop",
+ "tools": [
+ "terminal"
+ ],
+ "input": "So the root cause is becoming clear: mem0 sends a chat completion request with `response_format` set to JSON object and `max_tokens` capped at 2000 by\n\n\n<tool_call>\n<function=terminal>\n<parameter=command>\ngrep -n \"_get_supported_params\" -A 40 \"C:/Users/Ai/AppData/Local/hermes/installs/d54dbf11f …\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=terminal>\n<parameter=command>\nssh -o ConnectTimeout=8 <host> \"cat <private-path>\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "terminal",
+ "terminal"
+ ]
+ },
+ {
+ "name": "live-12-declared",
+ "finish": "stop",
+ "tools": [
+ "web_extract"
+ ],
+ "input": "I need to check the DETAILS.md file to understand what llama.cpp actually supports for the qwen4exp architecture—specifically MoE expert offloading wi\n\n\n<tool_call>\n<function=web_extract>\n<parameter=char_limit>\n25000\n</parameter>\n<parameter=urls>\n[\"https://raw.githubusercontent.com/Niko1221/Strata/main/DETAILS.md\", \"https://raw.githubu …\n</parameter>\n</function>\n</tool_call>",
+ "calls": [
+ "web_extract"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/serve/frontend.py b/serve/frontend.py
index 176f418c4..25667f2ee 100644
--- a/serve/frontend.py
+++ b/serve/frontend.py
@@ -600,8 +600,56 @@ class OutputParser:
# character; other types whole, once complete) - before the final "tool_call". Without it, a client sees
# nothing until the call is complete, which for a large file write can be many minutes.
self.stream_tools = stream_tools
+ # #804/#1058: calls found inside the reasoning wait here as [raw text, ToolCall | None] until the turn shows
+ # they were acts: only whitespace (or more calls) after them, then the end of the turn or `</think>`. The
+ # reasoning text before them is tracked (code fence, inline code, current line) to tell an act from a quote.
+ self.pending: list[list] = []
+ self.rescued = 0 # calls delivered from the reasoning
+ self.refused = 0 # declared calls kept as reasoning text (quoted, or the turn was cut)
+ self.fence, self.line, self.ticks = "", "", 0
self._reset_scan()
+ def _track(self, text: str) -> str:
+ """Follow the reasoning text that has gone out: the open code fence, the current line, and the backticks of
+ the current paragraph. Returns the text."""
+ parts = text.split("\n")
+ for k, part in enumerate(parts):
+ if k < len(parts) - 1:
+ line, self.line = self.line + part, ""
+ s = line.lstrip()
+ if self.fence:
+ if s.startswith(self.fence * 3):
+ self.fence = ""
+ elif s[:3] in ("```", "~~~") and (s[0] * 3) not in s[3:]:
+ self.fence = s[0]
+ elif not s:
+ self.ticks = 0
+ else:
+ self.ticks += line.count("`")
+ else:
+ self.line += part
+ return text
+
+ def _opener_ok(self) -> bool:
+ """The reasoning text so far puts a `<tool_call>` at the start of a line, outside a code fence and outside
+ inline code."""
+ return not self.fence and not self.line.strip() and self.ticks % 2 == 0
+
+ def _release(self, deliver: bool) -> list[Event]:
+ """Settle the calls waiting in self.pending: events for real calls, or all of it back as reasoning text."""
+ out = []
+ for raw, call in self.pending:
+ if call is not None and deliver:
+ out.append(Event("tool_call", call=call))
+ self.rescued += 1
+ elif call is None or not deliver:
+ if call is not None:
+ self.refused += 1
+ if raw:
+ out.append(Event("reasoning", self._track(raw)))
+ self.pending = []
+ return out
+
def _reset_scan(self):
self.sp = 0 # how much of self.buf (the call body) the scanner has consumed
self.ss = "name" # name -> between -> str|raw -> ... -> done
@@ -739,39 +787,64 @@ class OutputParser:
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))
+ raw = self.buf[:len(CALL_START) + end + len(CALL_END)]
+ if call is not None or self.pending:
+ self.pending.append([raw, call]) # settled by what follows it (see __init__)
else:
- out.append(Event("reasoning", self.buf[:len(CALL_START) + end + len(CALL_END)]))
+ out.append(Event("reasoning", self._track(raw)))
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]))
+ out += self._release(False)
+ out.append(Event("reasoning", self._track(self.buf[:len(CALL_START) + think])))
self.buf = body[think:]
self.state = "reasoning"
elif len(body) > RCALL_MAX: # a tag in the prose that never closes: stop holding the thinking back
- out.append(Event("reasoning", self.buf))
+ out += self._release(False)
+ out.append(Event("reasoning", self._track(self.buf)))
self.buf = ""
self.state = "reasoning"
else:
return out
elif self.state == "reasoning":
+ if self.pending:
+ # calls wait for what follows: more calls or whitespace keep them, `</think>` makes them acts,
+ # any other text means they were quoted
+ stripped = self.buf.lstrip()
+ if len(stripped) < len(self.buf):
+ self.pending[-1][0] += self.buf[:len(self.buf) - len(stripped)]
+ self.buf = stripped
+ if not self.buf:
+ return out
+ if self.buf.startswith(CALL_START):
+ self.state = "rcall"
+ elif self.buf.startswith(THINK_END):
+ out += self._release(True)
+ elif CALL_START.startswith(self.buf) or THINK_END.startswith(self.buf):
+ return out
+ else:
+ out += self._release(False)
+ continue
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"
+ out.append(Event("reasoning", self._track(self.buf[:tool])))
+ if self._opener_ok():
+ self.buf = self.buf[tool:]
+ self.state = "rcall"
+ else: # mid-sentence, in a fence or in inline code: a quote
+ out.append(Event("reasoning", self._track(CALL_START)))
+ self.buf = self.buf[tool + len(CALL_START):]
continue
if i < 0:
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]))
+ out.append(Event("reasoning", self._track(self.buf[:len(self.buf) - keep])))
self.buf = self.buf[len(self.buf) - keep:]
return out
if i:
- out.append(Event("reasoning", self.buf[:i]))
+ out.append(Event("reasoning", self._track(self.buf[:i])))
self.buf = self.buf[i + len(THINK_END):]
self.state, self.lead = "content", True
elif self.state == "content":
@@ -834,10 +907,14 @@ class OutputParser:
self._reset_scan()
self.state, self.lead = "content", True
- def finish(self) -> list[Event]:
+ def 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
- already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211)."""
+ already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211). `reason` is
+ how the turn ended: calls waiting from the reasoning become real calls only on a natural stop (None = stop);
+ a turn cut by max tokens (or cancelled, or failed) keeps them as reasoning text (#1058)."""
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.stream_tools and self.scall is not None:
out += self._scan() # the output ended inside a call that was already announced
if self.ss == "done": # only its </tool_call> is missing: the call itself is whole
diff --git a/serve/server.py b/serve/server.py
index 8357b42b9..4522ab399 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -2945,7 +2945,8 @@ class Service:
finish = "stop" # gen.close() below STOPs the engine, as for a stop token
break
if (self.reasoning_loop_recovery and not recovery_count and parser.state == "reasoning"
- and n >= next_loop_check and not parser.buf and not detok.pending()):
+ and n >= next_loop_check and not parser.buf and not parser.pending
+ and not detok.pending()):
next_loop_check = n + LOOP_CHECK_EVERY
repeat_coverage = reasoning_repeat_coverage(reasoning_text)
if repeat_coverage >= LOOP_COVERAGE:
@@ -3134,7 +3135,7 @@ class Service:
finally:
if emb:
Path(emb).unlink(missing_ok=True)
- for ev in cut(parser.finish()):
+ for ev in cut(parser.finish(finish)):
yield "event", ev
if stops is not None and stops.hit is None and stops.held:
yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all
@@ -3156,6 +3157,10 @@ def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:
return prompt_tokens
return min(prompt_tokens, int(last.get("reused") or 0) + int(read))
+ if parser.rescued or parser.refused:
+ self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued
+ print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as "
+ f"reasoning (quoted, or the turn did not end on a stop)", flush=True)
def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None:
"""One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock
diff --git a/serve/test_reasoning_rescue.py b/serve/test_reasoning_rescue.py
new file mode 100644
index 000000000..404ecac00
--- /dev/null
+++ b/serve/test_reasoning_rescue.py
@@ -0,0 +1,242 @@
+"""serve/test_reasoning_rescue.py - #804 / #1058: when a `<tool_call>` written inside the reasoning is a real call.
+
+A call inside the reasoning counts only when ALL hold: tools are declared and the name is one of them; the opener is
+at the start of a line; it is outside a Markdown code fence and outside inline code; the call closes with
+</tool_call> and nothing but whitespace (or more calls) follows it before the end of the turn or `</think>`; and the
+turn did not end by max tokens (or a cancel or an error). Anything else stays reasoning text.
+
+The corpus in serve/fixtures/rcall_specimens.json holds 25 entries from PR #525's corpus and the 12 live strandings
+recovered by 47Hunter47 (gist 4abcd3a8...): 16 act, 21 must not (the reporter's 20 negative controls
+plus the live one cut by max tokens).
+
+ python -m unittest serve.test_reasoning_rescue -v
+"""
+from __future__ import annotations
+
+import json
+import random
+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 # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[1]
+SPECIMENS = json.loads((ROOT / "serve/fixtures/rcall_specimens.json").read_text(encoding="utf-8"))["specimens"]
+CALL = "<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>"
+RM = CALL.replace("file.txt", "rm -rf build")
+PROPS = {"path": {"type": "string"}}
+SCHEMA = [{"name": "write", "parameters": {"properties": PROPS}}]
+
+
+def parse(text, width, tools=SCHEMA, finish=None, stream_tools=True):
+ """Events for `text` fed `width` characters at a time (0 = random 1-9, seeded)."""
+ p = OutputParser(thinking=True, tools=tools, stream_tools=stream_tools)
+ evs, rnd, i = [], random.Random(7), 0
+ while i < len(text):
+ k = width or rnd.randint(1, 9)
+ evs += p.feed(text[i:i + k])
+ i += k
+ return evs + p.finish(finish)
+
+
+def calls(evs):
+ return [e.call.name for e in evs if e.kind == "tool_call"]
+
+
+def reasoning(evs):
+ return "".join(e.text for e in evs if e.kind == "reasoning")
+
+
+WIDTHS = (1, 2, 3, 7, 0, 100_000)
+
+
+class Corpus(unittest.TestCase):
+ def test_every_specimen_whole_and_in_chunks(self):
+ for sp in SPECIMENS:
+ tools = [{"name": n, "parameters": {"properties": {}}} for n in sp["tools"]]
+ seen = set()
+ for width in WIDTHS:
+ for st in (True, False):
+ with self.subTest(name=sp["name"], width=width, stream_tools=st):
+ evs = parse(sp["input"], width, tools, sp["finish"], st)
+ self.assertEqual(calls(evs), sp["calls"])
+ seen.add((reasoning(evs), tuple(e.call.name for e in evs if e.kind == "tool_call")))
+ self.assertEqual(len(seen), 1, sp["name"]) # streamed and whole agree
+
+ def test_the_corpus_has_the_reported_split(self):
+ self.assertEqual((len(SPECIMENS), sum(bool(s["calls"]) for s in SPECIMENS)), (37, 16))
+
+
+class Gates(unittest.TestCase):
+ def check(self, text, expect, finish=None, tools=SCHEMA):
+ for width in WIDTHS:
+ with self.subTest(text=text[:40], width=width):
+ evs = parse(text, width, tools, finish)
+ self.assertEqual(len(calls(evs)), expect)
+ if not expect:
+ self.assertEqual(reasoning(evs), text) # nothing lost, nothing turned into content
+
+ def test_a_stranded_call_is_recovered(self):
+ self.check("I will write it now.\n\n" + CALL, 1)
+ self.check(CALL, 1)
+ self.check("Hmm.\n " + CALL + "\n", 1) # indented opener and trailing blank lines
+ self.check("Two steps.\n" + CALL + "\n\n" + CALL, 2)
+ self.check("Two steps.\n" + CALL + "\n</think>\n\ndone", 1)
+
+ def test_recovered_call_keeps_the_text_before_it(self):
+ evs = parse("Let me think.\n\n" + CALL, 3)
+ self.assertEqual(reasoning(evs), "Let me think.\n\n")
+
+ def test_the_reporters_negative_controls(self):
+ self.check("I could run\n" + RM + "\nbut first let me check what build holds...", 0)
+ self.check("I could run\n" + RM, 0, finish="length") # cut by max tokens: the destructive one
+ self.check("Example:\n```xml\n" + RM + "\n```\nok", 0)
+ self.check("Example:\n~~~\n" + RM + "\n~~~\nok", 0)
+ self.check("The format is " + RM + " ok.", 0)
+ self.check("I must emit `<tool_call>` then more", 0)
+ self.check("Use `\n" + RM, 0) # inside inline code spanning a line
+ self.check("> " + RM, 0)
+ self.check("Plan: " + RM, 0)
+
+ def test_a_length_cut_keeps_even_a_clean_stranded_call_as_text(self):
+ for finish in ("length", "cancel", "error", "disconnect"):
+ self.check("Now.\n" + CALL, 0, finish=finish)
+ self.check("Now.\n" + CALL, 1, finish="stop")
+
+ def test_after_a_closed_fence_a_call_counts_again(self):
+ self.check("```\nx\n```\n" + CALL, 1)
+ self.check("~~~\nx\n~~~\n" + CALL, 1)
+ self.check("a `b` c\n" + CALL, 1)
+
+ def test_a_fence_needs_the_same_marker_to_close(self):
+ self.check("~~~\n```\n" + CALL, 0)
+
+ def test_fence_split_across_chunks(self):
+ text = "Format:\n```xml\n" + CALL + "\n```\n"
+ for cut in range(1, len(text)):
+ with self.subTest(cut=cut):
+ p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
+ evs = p.feed(text[:cut]) + p.feed(text[cut:]) + p.finish()
+ self.assertEqual(calls(evs), [])
+ self.assertEqual(reasoning(evs), text)
+
+ def test_opener_split_across_chunks(self):
+ text = "Go.\n" + CALL
+ for cut in range(1, len(text)):
+ with self.subTest(cut=cut):
+ p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
+ evs = p.feed(text[:cut]) + p.feed(text[cut:]) + p.finish("stop")
+ self.assertEqual(calls(evs), ["write"])
+ quoted = "Go " + CALL
+ for cut in range(1, len(quoted)):
+ with self.subTest(cut=cut, quoted=True):
+ p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
+ evs = p.feed(quoted[:cut]) + p.feed(quoted[cut:]) + p.finish("stop")
+ self.assertEqual(calls(evs), [])
+
+ def test_the_end_of_the_turn_splits_a_held_tail(self):
+ p = OutputParser(thinking=True, tools=SCHEMA)
+ evs = p.feed("ok\n" + CALL + "\n<tool_c") # a half opener after the call: it was prose
+ evs += p.finish("stop")
+ self.assertEqual(calls(evs), [])
+ self.assertEqual(reasoning(evs), "ok\n" + CALL + "\n<tool_c")
+
+ def test_a_call_waits_and_is_not_streamed_early(self):
+ p = OutputParser(thinking=True, tools=SCHEMA)
+ evs = p.feed("go\n" + CALL + "\n")
+ self.assertEqual(calls(evs), []) # not yet: the turn could still say it was a quote
+ self.assertEqual(calls(p.finish("stop")), ["write"])
+
+ def test_no_tools_declared_is_unchanged(self):
+ text = "before\n" + CALL + "\n</think>\n\nanswer"
+ for tools in (None, []):
+ evs = parse(text, 5, tools)
+ self.assertEqual(calls(evs), [])
+ self.assertEqual(reasoning(evs), "before\n" + CALL + "\n")
+
+ def test_an_undeclared_name_stays_reasoning(self):
+ self.check("go\n" + CALL.replace("write", "other"), 0)
+
+ def test_the_counters(self):
+ p = OutputParser(thinking=True, tools=SCHEMA)
+ p.feed("go\n" + CALL)
+ p.finish("length")
+ self.assertEqual((p.rescued, p.refused), (0, 1))
+ p = OutputParser(thinking=True, tools=SCHEMA)
+ p.feed("go\n" + CALL)
+ p.finish("stop")
+ self.assertEqual((p.rescued, p.refused), (1, 0))
+
+
+class OverHttp(unittest.TestCase):
+ """The same rules through the real server: OpenAI chat (whole and streamed), Anthropic and Responses."""
+
+ def ask(self, script, max_tokens=800):
+ 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]}"
+ msgs = [{"role": "user", "content": "save my notes"}]
+ reqs = {
+ "openai": ("/v1/chat/completions", {"tools": [{"type": "function", "function": {
+ "name": "write", "parameters": {"type": "object", "properties": PROPS}}}], "messages": msgs,
+ "max_tokens": max_tokens}),
+ "anthropic": ("/v1/messages", {"tools": [{"name": "write", "input_schema": {
+ "type": "object", "properties": PROPS}}], "messages": msgs, "max_tokens": max_tokens}),
+ "responses": ("/v1/responses", {"tools": [{"type": "function", "name": "write", "parameters": {
+ "type": "object", "properties": PROPS}}], "input": "save my notes", "max_output_tokens": max_tokens}),
+ }
+ out = {}
+ try:
+ for api, (path, body) in reqs.items():
+ for stream in (False, True):
+ req = urllib.request.Request(base + path, data=json.dumps(dict(body, model="x", stream=stream)).encode(),
+ headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
+ with urllib.request.urlopen(req, timeout=30) as r:
+ raw = r.read().decode()
+ out[api, stream] = self.tool_uses(api, stream, raw)
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+ return out
+
+ @staticmethod
+ def tool_uses(api, stream, raw):
+ """How many tool calls the answer carries."""
+ if not stream:
+ m = json.loads(raw)
+ if api == "openai":
+ return len(m["choices"][0]["message"].get("tool_calls") or [])
+ if api == "anthropic":
+ return sum(b["type"] == "tool_use" for b in m["content"])
+ return sum(o["type"] == "function_call" for o in m["output"])
+ evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
+ if api == "openai":
+ return len({tc["index"] for e in evs for c in e["choices"] for tc in c["delta"].get("tool_calls") or []})
+ if api == "anthropic":
+ return sum(e["type"] == "content_block_start" and e["content_block"]["type"] == "tool_use" for e in evs)
+ return sum(e["type"] == "response.output_item.added" and e["item"]["type"] == "function_call" for e in evs)
+
+ def test_a_stranded_call_is_a_call_in_every_api(self):
+ a = self.ask("Writing the file now.\n\n" + CALL)
+ self.assertEqual(set(a.values()), {1}, a)
+
+ def test_quotes_and_cuts_are_not(self):
+ for name, script, tokens in (
+ ("fence", "Format:\n```xml\n" + RM + "\n```\nand that is all.", 800),
+ ("midsentence", "I could run " + RM + " but no.", 800),
+ ("prose after", "I could run\n" + RM + "\nbut first let me check what build holds.", 800),
+ ("cut", "I could run\n" + RM + "\nthen more thinking " * 40, len("I could run\n" + RM)),
+ ("cut exactly at the call", "Now.\n" + CALL + "\nmore thought " * 40, len("Now.\n" + CALL))):
+ with self.subTest(name):
+ a = self.ask(script, max_tokens=tokens)
+ self.assertEqual(set(a.values()), {0}, a)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/test_reasoning_tools.py b/serve/test_reasoning_tools.py
index 4468fbd35..a34171e48 100644
--- a/serve/test_reasoning_tools.py
+++ b/serve/test_reasoning_tools.py
@@ -39,14 +39,14 @@ def joined(evs, kind):
class Parser(unittest.TestCase):
def test_a_declared_call_in_the_reasoning_is_a_call(self):
- text = "before " + CALL + " after</think>\n\nanswer"
+ text = "before\n" + CALL + "\n</think>\n\nanswer" # at a line start, nothing but whitespace after it (#1058)
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, "reasoning"), "before\n")
self.assertEqual(joined(evs, "content"), "answer")
self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")]) # never streamed
@@ -60,13 +60,13 @@ class Parser(unittest.TestCase):
self.assertEqual(joined(evs, "content"), "answer")
def test_no_tools_declared_is_unchanged(self):
- text = "before " + CALL + " after</think>\n\nanswer"
+ text = "before\n" + CALL + "\n</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, "reasoning"), "before\n" + CALL + "\n")
self.assertEqual(joined(evs, "content"), "answer")
def test_an_unfinished_call_is_never_a_call(self):
@@ -96,7 +96,7 @@ class Parser(unittest.TestCase):
def test_a_tag_that_never_closes_does_not_hold_the_thinking_back(self):
from serve import frontend
- text = "a <tool_call> " + "thinking on and on " * 3000 + "</think>\n\nanswer"
+ text = "a\n<tool_call> " + "thinking on and on " * 3000 + "</think>\n\nanswer"
with unittest.mock.patch.object(frontend, "RCALL_MAX", 1000):
evs = run(text, 50)
first_reasoning_at = next(i for i, e in enumerate(evs) if e.kind == "reasoning" and len(e.text) > 100)
@@ -115,13 +115,13 @@ 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"
+ script = "Let me look.\n<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n" \
+ "</tool_call>\n</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
+ # the order of the Anthropic stream's blocks: thinking, the call, the answer
tok = ByteTokenizer()
svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
httpd = serve(svc, port=0)
@@ -135,7 +135,7 @@ class OverHttp(unittest.TestCase):
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"])
+ self.assertEqual(order, ["thinking", "tool_use", "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"})