tool calls: the damaged followers end a value; a parameter's name is cut where the model ran past it (#6032 R1)

First narrow repair from PR #6032 (Matthias Nott; Gyro / Coder-L recordings), reimplemented on the current
parser for whole and streamed calls alike:
- after a `</parameter>`, the Anthropic XML form's `</invoke>` and `<parameter name=`, a garbled `</<`, a
  damaged opener `<=NAME>` and a stray closer `</NAME>` standing where `</function>` belongs (right before
  `</tool_call>`) end the value, as the call format's own tags do; a prefix of one still arriving holds;
- a `<parameter=` opener's name is cut at its first whitespace, `<` or `>` (`<parameter=command </parameter>`,
  `<parameter=command </think>`, `<parameter=run_in_background >`), and a name that is then empty, a null /
  none placeholder or one of the call format's own tags (function, think, parameter) is read and dropped.
Anything else after a closer stays in the value as before (a tag line of a heredoc, `</command>` with text,
`</b> and more`); prose that shows these forms stays text.

Test: serve/test_parser_followers.py (11 of the PR's cases + 4 negatives + prose, whole and in pieces of 1 and
5, streamed JSON = final arguments). Before (9466f6be3, p2003-20261116-1811-57cc): the 11 cases fail (66
subtests), the negatives pass. After (p2003-20261116-1814-4d0f): 103 passed over the parser files, the tool
tests of test_server 59 passed.
This commit is contained in:
Niko1221 committed 2026-11-16 18:15:37 +01:00
1 parent 9466f6be3f
commit 2569c79ec0
2 files changed
+182 -12

No files matched your search

+53 -12
View File
@@ -840,12 +840,53 @@ def param_end(text: str, final: bool = False, name: str | None = None, hold: boo
return at
if verdict == "hold":
return -2
elif not after or PARAM_START.startswith(after) or FUNC_END.startswith(after) or CALL_END.startswith(after):
elif after.startswith(FOLLOWERS) or _follower_form(after): # #6032 R1: the damaged followers
return at
elif not after or PARAM_START.startswith(after) or FUNC_END.startswith(after) or CALL_END.startswith(after) \
or any(t.startswith(after) for t in FOLLOWERS) or _follower_form(after) is None:
return at if final else -2
at = text.find(PARAM_END, at + 1)
return -1
# #6032 R1: what else ends a value after its `</parameter>` (Gyro / Coder-L recordings): the Anthropic XML form's
# `</invoke>` and `<parameter name=` written in place of the call format's own tags, and a garbled `</<`
FOLLOWERS = ("</<", "</invoke>", "<parameter name=")
_DAMAGED_OPENER = re.compile(r"<=[^<>\s]+>") # `<=NAME>`: a damaged parameter opener
_STRAY_CLOSER = re.compile(r"</(?!parameter>|function>|tool_call>)[^<>\s=/]+>\s*")
def _follower_form(after: str):
"""#6032 R1: `after` (what follows a `</parameter>`, no leading whitespace) starts with a damaged opener `<=NAME>`,
or with a stray closer `</NAME>` standing where `</function>` belongs (then `</tool_call>`): True; None while it
may still become one (streaming); False otherwise (a tag of the value itself: the value goes on)."""
if _DAMAGED_OPENER.match(after):
return True
if re.fullmatch(r"<=[^<>\s]*", after):
return None
m = _STRAY_CLOSER.match(after)
if m:
rest = after[m.end():]
if rest.startswith(CALL_END):
return True
return None if not rest or CALL_END.startswith(rest) else False
return None if re.fullmatch(r"</(?!parameter>|function>|tool_call>)[^<>\s=/]*", after) else False
NOT_PARAMS = ("function", "think", "parameter")
def param_name(opener: str) -> str | None:
"""#6032 R1: the parameter a `<parameter=` opener names (`opener`: what follows `=` up to the `>` found): the name
cut at its first whitespace, `<` or `>` (the model ran a closer or `</think>` into it, or put a space before the
`>`); None - the value is read and dropped - when that leaves nothing, a placeholder (null / none) or one of the
call format's own tag names."""
name = re.split(r"[\s<>]", opener.lstrip(), 1)[0]
if not name or name in NOT_PARAMS or name.lower() in ("null", "none"):
return None
return name
def call_end(text: str, final: bool = False, hold: bool = True) -> int:
"""Where a tool call's body ends (#210): the `</tool_call>` after the call's own `</function>`, found by walking
its parameters with param_end, so a value may contain either tag. -1: not complete yet. A body that is not in
@@ -866,7 +907,7 @@ def call_end(text: str, final: bool = False, hold: bool = True) -> int:
gt = text.find(">", pos)
if gt < 0:
return -1
end = param_end(text[gt + 1:], final, text[pos:gt].split("=", 1)[1].strip(), hold, allow_reopen=True)
end = param_end(text[gt + 1:], final, param_name(text[pos:gt].split("=", 1)[1]), hold, allow_reopen=True)
if end < 0:
return -1
pos = gt + 1 + end + len(PARAM_END)
@@ -948,7 +989,7 @@ def function_end(text: str) -> int:
gt = text.find(">", pos)
if gt < 0:
return -1
end = param_end(text[gt + 1:], name=text[pos:gt].split("=", 1)[1].strip(), hold=False, allow_reopen=True) # a bare or unwrapped call: the old rule
end = param_end(text[gt + 1:], name=param_name(text[pos:gt].split("=", 1)[1]), hold=False, allow_reopen=True) # a bare or unwrapped call: the old rule
if end < 0:
return -1
pos = gt + 1 + end + len(PARAM_END)
@@ -1182,19 +1223,19 @@ def parse_tool_call(body: str, schema: dict | None = None, notes: list | None =
args = {}
while "<parameter=" in rest:
rest = rest[rest.index("<parameter=") + len("<parameter="):]
pname = rest[:rest.index(">")]
pname = param_name(rest[:rest.index(">")]) # #6032 R1: None = read the value and drop it
rest = rest[rest.index(">") + 1:]
declared = declared_type(props.get(pname))
declared = declared_type(props.get(pname)) if pname else None
# #5493: a close followed by the same name again is part of a STRING value (#4078); a non-string parameter
# written twice is two writes of it, and the later one counts
end = param_end(rest, final=True, name=pname.strip(), allow_reopen=(declared is None or _declares(declared, "string")))
end = param_end(rest, final=True, name=pname, allow_reopen=(declared is None or _declares(declared, "string")))
value = rest[:end] if end >= 0 else rest
rest = rest[end + len(PARAM_END):] if end >= 0 else ""
if value.startswith("\n"):
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
v = coerce_value(value, declared, notes)
v = coerce_value(value, declared, notes) if pname else _SKIP
if v is not _SKIP:
args[pname] = v
return ToolCall(name=name, arguments=args)
@@ -1611,11 +1652,11 @@ class OutputParser:
b = stripped.find(">")
if b < 0:
return out
pname = stripped[11:b]
pname = param_name(stripped[11:b]) # #6032 R1: as parse_tool_call names it; None = dropped
self.sp += b + 1
self.sraw_pname = pname
self.spname = pname.strip()
if self.sdeclared.get(pname) == "string":
self.spname = pname
if pname is not None and self.sdeclared.get(pname) == "string":
args(("" if self.sfirst else ",") + json.dumps(pname) + ':"')
self.sfirst = False
self.ss, self.sval_started = "str", False
@@ -1665,7 +1706,7 @@ class OutputParser:
value = value[1:]
if value.endswith("\n"):
value = value[:-1]
v = coerce_value(value, declared) # the note comes with the final call (parse_tool_call)
v = coerce_value(value, declared) if self.sraw_pname is not None else _SKIP # the note comes with the final call
if v is not _SKIP:
# #5493: held until the call closes, so a parameter the model writes again (anywhere later in the
# call) streams once, with the value the final call has (the later write), not as two JSON keys
@@ -1684,7 +1725,7 @@ class OutputParser:
tail = ""
if self.ss == "str":
tail += '"'
elif self.ss == "raw": # a value the output ended inside: its text, as before
elif self.ss == "raw" and self.sraw_pname is not None: # a value the output ended inside: its text, as before
self.sheld.pop(self.sraw_pname, None)
self.sheld[self.sraw_pname] = self.buf[self.sp:].strip("\n")
for k, v in self.sheld.items(): # #5493: the non-string parameters, each once, the later write
+129
View File
@@ -0,0 +1,129 @@
"""serve/test_parser_followers.py - #6032 R1: what ends a parameter value after its `</parameter>`, and the parameter
names a damaged opener writes (cases from PR #6032's test_parser_followers.py, Gyro / Coder-L recordings; the ones of
later repairs left out), plus negatives: text that only looks like a follower stays in the value.
python -m pytest serve/test_parser_followers.py -q
Every case: whole and in pieces of 1 and 5 bytes, with the arguments streamed and not; the streamed JSON of a call is
its final arguments.
"""
import json
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from serve.frontend import OutputParser, param_name # noqa: E402
LT, GT = "<", ">"
F, FE = LT + "function=", LT + "/function" + GT
P, PE = LT + "parameter=", LT + "/parameter" + GT
CS, CE = LT + "tool_call" + GT, LT + "/tool_call" + GT
def tool(name, **props):
return {"name": name, "parameters": {"type": "object", "properties": {k: {"type": v} for k, v in props.items()}}}
SCHEMAS = [tool("Grep", pattern="string", path="string", head_limit="integer", context="number", **{"-n": "boolean"}),
tool("Read", file_path="string", offset="integer"),
tool("Bash", command="string", description="string", timeout="number", run_in_background="boolean")]
def run(text, stream, step):
p = OutputParser(thinking=False, tools=SCHEMAS, stream_tools=stream, recover=True)
evs = []
for k in range(0, len(text), step):
evs += p.feed(text[k:k + step])
return evs + p.finish()
def body(name, inner, close=True):
return CS + "\n" + F + name + GT + "\n" + inner + ("\n" + FE + "\n" + CE if close else "")
CASES = {
# followers (the PR's)
"damaged_opener_ends_the_value": (
body("Grep", P + "pattern" + GT + "\nfoo\n" + PE + "\n" + P + "path" + GT + "\n/d/src\n" + PE + "\n"
+ LT + "=limit" + GT + "\n60\n" + PE),
("Grep", {"pattern": "foo", "path": "/d/src"})),
"garbled_closer_follower": (
body("Grep", P + "pattern" + GT + "\nfoo\n" + PE + "\n" + P + "path" + GT + "\n/d/src\n" + PE + "\n"
+ LT + "/" + LT + "novel" + GT),
("Grep", {"pattern": "foo", "path": "/d/src"})),
"anthropic_invoke_closer": (
CS + "\n" + F + "Read" + GT + "\n" + P + "file_path" + GT + "\n/d/f\n" + PE + "\n</invoke>\n" + CE,
("Read", {"file_path": "/d/f"})),
"anthropic_parameter_name_follower": (
body("Grep", P + "pattern" + GT + "\nfoo\n" + PE + "\n<parameter name=\"path\">/d</parameter>"),
("Grep", {"pattern": "foo"})),
"stray_closer_before_the_wrapper_closer": (
CS + "\n" + F + "Read" + GT + "\n" + P + "file_path" + GT + "\n/d/f\n" + PE + "\n</Read>\n" + CE,
("Read", {"file_path": "/d/f"})),
# parameter names (the PR's)
"name_runs_past_closer": (
body("Bash", P + "command " + PE + "\necho hi\n" + PE + "\n" + P + "timeout" + GT + "\n2.5\n" + PE),
("Bash", {"command": "echo hi", "timeout": 2.5})),
"name_null_dropped": (
body("Bash", P + "command" + GT + "\nls\n" + PE + "\n" + P + " null " + PE + "\nx\n" + PE),
("Bash", {"command": "ls"})),
"name_think_cut": (
body("Bash", P + "command" + GT + "\nls\n" + PE + "\n" + P + "command " + LT + "/think" + GT + "\nx\n" + PE),
("Bash", {"command": "x"})),
"function_is_no_parameter": (
body("Bash", P + "command" + GT + "\nls\n" + PE + "\n" + P + "function" + GT + "\nBash\n" + PE),
("Bash", {"command": "ls"})),
"coerced_after_cut": (
body("Bash", P + "command" + GT + "\nls\n" + PE + "\n" + P + "run_in_background " + GT + "\ntrue\n" + PE),
("Bash", {"command": "ls", "run_in_background": True})),
# negatives: these stay in the value (the PR's last two, and ours)
"closing_tag_of_a_value_stays": (
body("Bash", P + "command" + GT + "\nls\n" + PE + "\n" + LT + "/command" + GT + "\nx\n" + PE),
("Bash", {"command": "ls\n" + PE + "\n" + LT + "/command" + GT + "\nx"})),
"plain_text_after_closer_stays": (
body("Bash", P + "command" + GT + "\necho a\n" + PE + " then text\n" + PE),
("Bash", {"command": "echo a" + "\n" + PE + " then text"})),
"a_tag_line_of_the_value_stays": (
body("Bash", P + "command" + GT + "\ncat <<EOF\n" + PE + "\n<div>\nEOF\n" + PE),
("Bash", {"command": "cat <<EOF\n" + PE + "\n<div>\nEOF"})),
"a_stray_closer_not_before_the_wrapper_stays": (
body("Bash", P + "command" + GT + "\nprintf x\n" + PE + "\n</b> and more\n" + PE),
("Bash", {"command": "printf x\n" + PE + "\n</b> and more"})),
"a_spaced_name_is_the_name": (
body("Read", P + " file_path " + GT + "\n/d/f\n" + PE),
("Read", {"file_path": "/d/f"})),
}
class Followers(unittest.TestCase):
def test_cases(self):
for label, (text, want) in CASES.items():
for stream in (False, True):
for step in (1, 5, len(text)):
with self.subTest(label, stream=stream, step=step):
evs = run(text, stream, step)
calls = [e for e in evs if e.kind == "tool_call"]
self.assertEqual([(e.call.name, e.call.arguments) for e in calls], [want])
if stream:
streamed = "".join(e.text for e in evs if e.kind == "tool_args")
self.assertEqual(json.loads(streamed), want[1], streamed)
def test_prose_that_shows_the_forms_stays_text(self):
text = "Write `</parameter>` then `</invoke>` or `<=limit>` in your notes; `<parameter name=\"x\">` too."
for stream in (False, True):
for step in (1, len(text)):
evs = run(text, stream, step)
self.assertFalse([e for e in evs if e.kind in ("tool_call", "tool_start")])
self.assertEqual("".join(e.text for e in evs if e.kind == "content"), text)
def test_param_name(self):
self.assertEqual(param_name("path"), "path")
self.assertEqual(param_name(" path "), "path")
self.assertEqual(param_name("command </parameter"), "command")
for dropped in ("", " ", " null ", "None", "function", "think", "parameter"):
self.assertIsNone(param_name(dropped), dropped)
if __name__ == "__main__":
unittest.main()