tool calls: a body of <arguments> + a JSON object is the call's arguments (#6032 R3, recovery on)

Third narrow repair from PR #6032 (Matthias Nott; Gyro / Coder-L recording), reimplemented on the current
parser, only with tool_call_recovery on: right after the function opener, `<arguments>` + a JSON object
(closed by `</arguments>`, by the stray `</parameter>` the model wrote, or by nothing) is the call's
arguments; a string value of a declared non-string parameter is read by its type ("true" -> true, "3" -> 3).
The streamed view holds the object until it is whole and sends it with the call's other non-string values
when the call closes, so the streamed JSON is the final arguments; a call cut inside the object is never run.
`<arguments>` text inside a parameter's value stays text; with recovery off nothing changes.

Test: serve/test_parser_json_args.py (the PR's three closers, typed values, a cut object, a call after a JSON
call, a value holding the same text, recovery off; whole and in pieces of 1 and 7, streamed and not). Before
(b3e6361c5, p2003-20261116-1843-891f): 26 FAIL; after (p2003-20261116-1844-52bf): 111 passed over the parser
files, test_server tool tests 61 passed.
This commit is contained in:
Niko1221 committed 2026-11-16 18:46:20 +01:00
1 parent b3e6361c53
commit ae9b390afc
2 files changed
+150

No files matched your search

+47
View File
@@ -890,6 +890,34 @@ def param_name(opener: str) -> str | None:
return name
ARGS_START = "<arguments>"
def json_args(s: str, props=None, notes: list | None = None):
"""#6032 R3 (recover): `s` starts with `<arguments>` + a JSON object (Gyro / Coder-L wrote the call's arguments so,
instead of `<parameter=` tags), closed by `</arguments>`, by the stray `</parameter>` the model wrote, or by
nothing. -> (arguments, length read) with each string value of a declared non-string parameter read by its type
(coerce_value); None while the object is not whole (a call cut inside it is never run with partial strings)."""
t = s[len(ARGS_START):]
body = t.lstrip()
try:
obj, end = json.JSONDecoder().raw_decode(body)
except ValueError:
return None
if not isinstance(obj, dict):
return None
tail = re.match(r"\s*(?:</arguments>|" + re.escape(PARAM_END) + r")?", body[end:])
args = {}
for k, v in obj.items():
declared = declared_type((props or {}).get(k))
if isinstance(v, str) and declared is not None and not _declares(declared, "string"):
v = coerce_value(v, declared, notes)
if v is _SKIP:
continue
args[k] = v
return args, len(ARGS_START) + len(t) - len(body) + end + tail.end()
_COLON_OPENER = re.compile(r"<parameter=([^<>\s:=]+):[ \t]*([^\n<>]*)\n")
_BARE_OPENER = re.compile(r"<(?:/|=)?([^<>\s=/]+)>")
@@ -1272,6 +1300,12 @@ def parse_tool_call(body: str, schema: dict | None = None, notes: list | None =
rest = body[body.index(">") + 1:]
props = ((schema or {}).get("parameters") or {}).get("properties") or {}
args = {}
if recover and rest.lstrip().startswith(ARGS_START): # #6032 R3: the arguments as one JSON object
got = json_args(rest.lstrip(), props, notes)
if got is None:
raise ValueError("malformed tool call: " + body[:80])
args.update(got[0])
rest = rest.lstrip()[got[1]:]
while True:
# #6032 R2 (recover): where a parameter may begin, a damaged opener of a declared parameter not set yet
# counts (opener_at); anything else is skipped to the next `<parameter=`, as before
@@ -1719,6 +1753,19 @@ class OutputParser:
stripped = rest.lstrip()
self.sp += len(rest) - len(stripped)
got = None
if self.recover and (stripped.startswith(ARGS_START) or (stripped and ARGS_START.startswith(stripped))):
# #6032 R3: the arguments as one JSON object: held until it is whole, then sent with the call's
# other non-string values when it closes (as parse_tool_call reads it); a cut one sends nothing
props = ((self.schemas.get(self.scall.name) or {}).get("parameters") or {}).get("properties") or {}
whole = json_args(stripped, props) if stripped.startswith(ARGS_START) else None
if whole is None:
return out
for k, v in whole[0].items():
self.sheld.pop(k, None)
self.sheld[k] = v
self.sset.add(k)
self.sp += whole[1]
continue
if self.recover and not stripped.startswith(FUNC_END):
# #6032 R2: the opener parse_tool_call reads here (a damaged one of a declared parameter not set
# yet, or the colon form); other text up to the next `<parameter=` is skipped, as there
+103
View File
@@ -0,0 +1,103 @@
"""serve/test_parser_json_args.py - #6032 R3 (recovery on): a call whose body is `<arguments>` + a JSON object instead of
`<parameter=` tags (Gyro / Coder-L recording; cases from PR #6032's test_parser_json_args.py): the object is the call's
arguments, closed by `</arguments>`, by the stray `</parameter>` the model wrote, or by nothing; string values of
declared non-string parameters are read by their type; a call cut inside the object is never run.
python -m pytest serve/test_parser_json_args.py -q
"""
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 # noqa: E402
SCHEMAS = [
{"name": "Edit", "parameters": {"properties": {"file_path": {"type": "string"}, "old_string": {"type": "string"},
"new_string": {"type": "string"}}}},
{"name": "Grep", "parameters": {"properties": {"pattern": {"type": "string"}, "-n": {"type": "boolean"},
"head_limit": {"type": "integer"}, "-A": {"type": "number"}}}},
{"name": "Read", "parameters": {"properties": {"file_path": {"type": "string"}}}},
{"name": "Write", "parameters": {"properties": {"file_path": {"type": "string"}, "content": {"type": "string"}}}},
]
OLD = ("/** Shipped defaults merged under the user's main config. */\nasync function defaultConfigReader() {\n"
" const { getConfigValueOp } = await import(\"../config/main-config-ops.js\");\n return () => ({});\n}")
NEW = OLD.replace("getConfigValueOp", "effectiveMainConfig").replace("main-config-ops", "shipped-defaults")
ARGS = {"file_path": "/x/src/builds/mirror-sync.ts", "old_string": OLD, "new_string": NEW}
JSON = json.dumps(ARGS)
HEAD = "<tool_call>\n<function=Edit>\n<arguments>\n"
CASES = {
"stray": HEAD + JSON + "\n</parameter>\n</function>\n</tool_call>",
"closed": HEAD + JSON + "\n</arguments>\n</function>\n</tool_call>",
"bare": HEAD + JSON + "\n</function>\n</tool_call>",
}
CUT = HEAD + JSON[:JSON.index("new_string") + 40]
TYPED = ('<tool_call>\n<function=Grep>\n<arguments>{"pattern": "p", "-n": "true", "head_limit": 20, "-A": "3"}'
'</arguments>\n</function>\n</tool_call>')
def run(text, step, stream=True, finish="stop", recover=True):
p = OutputParser(thinking=False, tools=SCHEMAS, stream_tools=stream, recover=recover)
evs = []
for k in range(0, len(text), step):
evs += p.feed(text[k:k + step])
return evs + p.finish(finish)
def check(case, evs, want, stream):
case.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"], want)
if stream:
for e in (x for x in evs if x.kind == "tool_call"):
streamed = "".join(x.text for x in evs if x.kind == "tool_args" and x.call is not None and x.call.id == e.call.id)
case.assertEqual(json.loads(streamed), e.call.arguments)
case.assertFalse([e for e in evs if e.kind in ("content", "reasoning") and e.text.strip()])
class JsonArgs(unittest.TestCase):
def test_each_closer(self):
for key, text in CASES.items():
for stream in (False, True):
for step in (1, 7, len(text)):
with self.subTest(key, stream=stream, step=step):
check(self, run(text, step, stream), [("Edit", ARGS)], stream)
def test_types_are_read(self):
want = {"pattern": "p", "-n": True, "head_limit": 20, "-A": 3}
for stream in (False, True):
for step in (1, len(TYPED)):
with self.subTest(stream=stream, step=step):
check(self, run(TYPED, step, stream), [("Grep", want)], stream)
def test_a_cut_object_is_never_a_call(self):
for finish in ("stop", "length"):
for stream in (False, True):
for step in (1, 7, len(CUT)):
with self.subTest(finish=finish, stream=stream, step=step):
evs = run(CUT, step, stream, finish)
self.assertEqual([e for e in evs if e.kind == "tool_call"], [])
def test_a_call_after_a_json_call(self):
text = CASES["stray"] + "\n<tool_call>\n<function=Read>\n<parameter=file_path>\n/a\n</parameter>\n</function>\n</tool_call>"
for stream in (False, True):
for step in (1, len(text)):
with self.subTest(stream=stream, step=step):
check(self, run(text, step, stream), [("Edit", ARGS), ("Read", {"file_path": "/a"})], stream)
def test_arguments_text_inside_a_value_stays(self):
content = "<arguments>\n{\"a\": 1}\n</arguments>"
text = ("<tool_call>\n<function=Write>\n<parameter=file_path>\nx\n</parameter>\n<parameter=content>\n" + content
+ "\n</parameter>\n</function>\n</tool_call>")
for stream in (False, True):
for step in (1, len(text)):
with self.subTest(stream=stream, step=step):
check(self, run(text, step, stream), [("Write", {"file_path": "x", "content": content})], stream)
def test_recovery_off_reads_no_json_body(self):
for stream in (False, True):
evs = run(CASES["closed"], len(CASES["closed"]), stream, recover=False)
self.assertNotIn(("Edit", ARGS), [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"])
if __name__ == "__main__":
unittest.main()