okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
4.6 KiB94 linesraw
1"""A missing wrapper closer ends before a following call, but prose alone does not confirm a call.
2
3A call's own </function> separates it from the next wrapper without merging their arguments.
4Parameter values may still contain call-format tags; recovery batches stay opt-in.
5
6    python -m unittest serve.test_tool_call_unclosed -v
7"""
8import json
9import sys
10import unittest
11from pathlib import Path
12
13sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
15from serve.frontend import OutputParser  # noqa: E402
16
17TOOLS = [{"name": "read", "parameters": {"properties": {"path": {"type": "string"}}}},
18         {"name": "write", "parameters": {"properties": {"path": {"type": "string"}, "content": {"type": "string"}}}}]
19READ = "<function=read>\n<parameter=path>\na.py\n</parameter>\n</function>"
20WRITE = "<function=write>\n<parameter=path>\nb.py\n</parameter>\n<parameter=content>\nx = 1\n</parameter>\n</function>"
21
22
23def run(text, stream_tools, recover, step):
24    p = OutputParser(thinking=False, tools=TOOLS, stream_tools=stream_tools, recover=recover)
25    evs = []
26    for i in range(0, len(text), step):                # fed in small pieces, as a stream arrives
27        evs += p.feed(text[i:i + step])
28    evs += p.finish("stop")
29    calls = [(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"]
30    if stream_tools and not calls:
31        arguments = "".join(e.text for e in evs if e.kind == "tool_args")
32        if arguments:
33            try:
34                json.loads(arguments)
35            except ValueError:
36                pass
37            else:
38                raise AssertionError("an unconfirmed call has complete streamed arguments")
39    return calls, "".join(e.text for e in evs if e.kind == "content")
40
41
42class UnclosedCall(unittest.TestCase):
43    def check(self, text, want_calls, want_content=""):
44        for stream_tools in (False, True):
45            for recover in (False, True):
46                for step in (1, 3, 7, 4096):
47                    with self.subTest(stream_tools=stream_tools, recover=recover, step=step):
48                        calls, content = run(text, stream_tools, recover, step)
49                        self.assertEqual(calls, want_calls)
50                        self.assertEqual(content.strip(), want_content)
51
52    def test_closed_calls_are_unchanged(self):
53        self.check("<tool_call>\n" + READ + "\n</tool_call>\n<tool_call>\n" + WRITE + "\n</tool_call>",
54                   [("read", {"path": "a.py"}), ("write", {"path": "b.py", "content": "x = 1"})])
55
56    def test_a_second_call_after_an_unclosed_one_is_its_own_call(self):
57        self.check("<tool_call>\n" + READ + "\n<tool_call>\n" + WRITE + "\n</tool_call>",
58                   [("read", {"path": "a.py"}), ("write", {"path": "b.py", "content": "x = 1"})])
59
60    def test_quoted_incomplete_wrapper_stays_literal(self):
61        text = "Format: <tool_call>\n" + READ + "\nand then I explain it."
62        self.check(text, [], text)
63
64    def test_following_literal_marker_does_not_complete_an_unclosed_call(self):
65        text = "<tool_call>\n" + READ + "\n<tool_call> is a format marker."
66        self.check(text, [], text)
67
68    def test_omitted_wrapper_recovers_only_on_a_natural_stop(self):
69        for closed in (True, False):
70            text = "<tool_call>\n" + READ + ("\n</tool_call>" if closed else "")
71            for reason in (None, "stop", "length", "cancel", "disconnect"):
72                for step in (1, 7, 4096):
73                    with self.subTest(closed=closed, reason=reason, step=step):
74                        p = OutputParser(thinking=False, tools=TOOLS, stream_tools=True)
75                        events = []
76                        for offset in range(0, len(text), step):
77                            events += p.feed(text[offset:offset + step])
78                        events += p.finish(reason)
79                        calls = [e for e in events if e.kind == "tool_call"]
80                        complete = closed or reason in (None, "stop")
81                        self.assertEqual(len(calls), int(complete))
82                        if not complete:
83                            with self.assertRaises(ValueError):
84                                json.loads("".join(e.text for e in events if e.kind == "tool_args"))
85
86    def test_a_value_that_holds_the_tags_still_ends_at_the_calls_own_closer(self):
87        value = "a </function> and a <tool_call> in a string"
88        call = ("<tool_call>\n<function=write>\n<parameter=path>\nc.py\n</parameter>\n<parameter=content>\n" + value +
89                "\n</parameter>\n</function>\n</tool_call>")
90        self.check(call, [("write", {"path": "c.py", "content": value})])
91
92
93if __name__ == "__main__":
94    unittest.main()