okami.mom/strata

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

Niko1221serve: a tool call inside a code fence or inline code in the visible answer is text (#1058)82f46a8c8

main
13.8 KiB287 linesraw
1"""serve/test_reasoning_rescue.py - #804 / #1058: when a `<tool_call>` written inside the reasoning is a real call.
2
3A call inside the reasoning counts only when ALL hold: tools are declared and the name is one of them; the opener is
4at the start of a line; it is outside a Markdown code fence and outside inline code; the call closes with
5</tool_call> and nothing but whitespace (or more calls) follows it before the end of the turn or `</think>`; and the
6turn did not end by max tokens (or a cancel or an error).  Anything else stays reasoning text.
7
8The corpus in serve/fixtures/rcall_specimens.json holds 25 entries from PR #525's corpus and the 12 live strandings
9recovered by 47Hunter47 (gist 4abcd3a8...): 16 act, 21 must not (the reporter's 20 negative controls
10plus the live one cut by max tokens).
11
12    python -m unittest serve.test_reasoning_rescue -v
13"""
14from __future__ import annotations
15
16import json
17import random
18import sys
19import unittest
20import urllib.request
21from pathlib import Path
22
23sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
24from serve.frontend import ChatTemplate, OutputParser  # noqa: E402
25from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
26from serve.test_server import CTX  # noqa: E402
27
28ROOT = Path(__file__).resolve().parents[1]
29SPECIMENS = json.loads((ROOT / "serve/fixtures/rcall_specimens.json").read_text(encoding="utf-8"))["specimens"]
30CALL = "<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>"
31RM = CALL.replace("file.txt", "rm -rf build")
32PROPS = {"path": {"type": "string"}}
33SCHEMA = [{"name": "write", "parameters": {"properties": PROPS}}]
34
35
36def parse(text, width, tools=SCHEMA, finish=None, stream_tools=True):
37    """Events for `text` fed `width` characters at a time (0 = random 1-9, seeded)."""
38    p = OutputParser(thinking=True, tools=tools, stream_tools=stream_tools)
39    evs, rnd, i = [], random.Random(7), 0
40    while i < len(text):
41        k = width or rnd.randint(1, 9)
42        evs += p.feed(text[i:i + k])
43        i += k
44    return evs + p.finish(finish)
45
46
47def calls(evs):
48    return [e.call.name for e in evs if e.kind == "tool_call"]
49
50
51def reasoning(evs):
52    return "".join(e.text for e in evs if e.kind == "reasoning")
53
54
55WIDTHS = (1, 2, 3, 7, 0, 100_000)
56
57
58class Corpus(unittest.TestCase):
59    def test_every_specimen_whole_and_in_chunks(self):
60        for sp in SPECIMENS:
61            tools = [{"name": n, "parameters": {"properties": {}}} for n in sp["tools"]]
62            seen = set()
63            for width in WIDTHS:
64                for st in (True, False):
65                    with self.subTest(name=sp["name"], width=width, stream_tools=st):
66                        evs = parse(sp["input"], width, tools, sp["finish"], st)
67                        self.assertEqual(calls(evs), sp["calls"])
68                        seen.add((reasoning(evs), tuple(e.call.name for e in evs if e.kind == "tool_call")))
69            self.assertEqual(len(seen), 1, sp["name"])        # streamed and whole agree
70
71    def test_the_corpus_has_the_reported_split(self):
72        self.assertEqual((len(SPECIMENS), sum(bool(s["calls"]) for s in SPECIMENS)), (37, 16))
73
74
75class Gates(unittest.TestCase):
76    def check(self, text, expect, finish=None, tools=SCHEMA):
77        for width in WIDTHS:
78            with self.subTest(text=text[:40], width=width):
79                evs = parse(text, width, tools, finish)
80                self.assertEqual(len(calls(evs)), expect)
81                if not expect:
82                    self.assertEqual(reasoning(evs), text)       # nothing lost, nothing turned into content
83
84    def test_a_stranded_call_is_recovered(self):
85        self.check("I will write it now.\n\n" + CALL, 1)
86        self.check(CALL, 1)
87        self.check("Hmm.\n  " + CALL + "\n", 1)                    # indented opener and trailing blank lines
88        self.check("Two steps.\n" + CALL + "\n\n" + CALL, 2)
89        self.check("Two steps.\n" + CALL + "\n</think>\n\ndone", 1)
90
91    def test_recovered_call_keeps_the_text_before_it(self):
92        evs = parse("Let me think.\n\n" + CALL, 3)
93        self.assertEqual(reasoning(evs), "Let me think.\n\n")
94
95    def test_the_reporters_negative_controls(self):
96        self.check("I could run\n" + RM + "\nbut first let me check what build holds...", 0)
97        self.check("I could run\n" + RM, 0, finish="length")             # cut by max tokens: the destructive one
98        self.check("Example:\n```xml\n" + RM + "\n```\nok", 0)
99        self.check("Example:\n~~~\n" + RM + "\n~~~\nok", 0)
100        self.check("The format is " + RM + " ok.", 0)
101        self.check("I must emit `<tool_call>` then more", 0)
102        self.check("Use `\n" + RM, 0)                                       # inside inline code spanning a line
103        self.check("> " + RM, 0)
104        self.check("Plan: " + RM, 0)
105
106    def test_a_length_cut_keeps_even_a_clean_stranded_call_as_text(self):
107        for finish in ("length", "cancel", "error", "disconnect"):
108            self.check("Now.\n" + CALL, 0, finish=finish)
109        self.check("Now.\n" + CALL, 1, finish="stop")
110
111    def test_after_a_closed_fence_a_call_counts_again(self):
112        self.check("```\nx\n```\n" + CALL, 1)
113        self.check("~~~\nx\n~~~\n" + CALL, 1)
114        self.check("a `b` c\n" + CALL, 1)
115
116    def test_a_fence_needs_the_same_marker_to_close(self):
117        self.check("~~~\n```\n" + CALL, 0)
118
119    def test_fence_split_across_chunks(self):
120        text = "Format:\n```xml\n" + CALL + "\n```\n"
121        for cut in range(1, len(text)):
122            with self.subTest(cut=cut):
123                p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
124                evs = p.feed(text[:cut]) + p.feed(text[cut:]) + p.finish()
125                self.assertEqual(calls(evs), [])
126                self.assertEqual(reasoning(evs), text)
127
128    def test_opener_split_across_chunks(self):
129        text = "Go.\n" + CALL
130        for cut in range(1, len(text)):
131            with self.subTest(cut=cut):
132                p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
133                evs = p.feed(text[:cut]) + p.feed(text[cut:]) + p.finish("stop")
134                self.assertEqual(calls(evs), ["write"])
135        quoted = "Go " + CALL
136        for cut in range(1, len(quoted)):
137            with self.subTest(cut=cut, quoted=True):
138                p = OutputParser(thinking=True, tools=SCHEMA, stream_tools=True)
139                evs = p.feed(quoted[:cut]) + p.feed(quoted[cut:]) + p.finish("stop")
140                self.assertEqual(calls(evs), [])
141
142    def test_the_end_of_the_turn_splits_a_held_tail(self):
143        p = OutputParser(thinking=True, tools=SCHEMA)
144        evs = p.feed("ok\n" + CALL + "\n<tool_c")           # a half opener after the call: it was prose
145        evs += p.finish("stop")
146        self.assertEqual(calls(evs), [])
147        self.assertEqual(reasoning(evs), "ok\n" + CALL + "\n<tool_c")
148
149    def test_a_call_waits_and_is_not_streamed_early(self):
150        p = OutputParser(thinking=True, tools=SCHEMA)
151        evs = p.feed("go\n" + CALL + "\n")
152        self.assertEqual(calls(evs), [])                    # not yet: the turn could still say it was a quote
153        self.assertEqual(calls(p.finish("stop")), ["write"])
154
155    def test_no_tools_declared_is_unchanged(self):
156        text = "before\n" + CALL + "\n</think>\n\nanswer"
157        for tools in (None, []):
158            evs = parse(text, 5, tools)
159            self.assertEqual(calls(evs), [])
160            self.assertEqual(reasoning(evs), "before\n" + CALL + "\n")
161
162    def test_an_undeclared_name_stays_reasoning(self):
163        self.check("go\n" + CALL.replace("write", "other"), 0)
164
165    def test_the_counters(self):
166        p = OutputParser(thinking=True, tools=SCHEMA)
167        p.feed("go\n" + CALL)
168        p.finish("length")
169        self.assertEqual((p.rescued, p.refused), (0, 1))
170        p = OutputParser(thinking=True, tools=SCHEMA)
171        p.feed("go\n" + CALL)
172        p.finish("stop")
173        self.assertEqual((p.rescued, p.refused), (1, 0))
174
175
176class VisibleAnswer(unittest.TestCase):
177    """#1058: the same fence / inline-code rule for a call in the visible answer (after </think>)."""
178    HEAD = "ok</think>\n\n"
179
180    def run_all(self, text, finish=None):
181        res = set()
182        for width in WIDTHS:
183            evs = parse(text, width, SCHEMA, finish)
184            res.add((tuple(calls(evs)), "".join(e.text for e in evs if e.kind == "content")))
185        self.assertEqual(len(res), 1, res)               # every chunking agrees
186        return res.pop()
187
188    def test_quoted_calls_stay_text(self):
189        for body in ("Format:\n```xml\n" + RM + "\n```\nDone.", "Format:\n~~~\n" + RM + "\n~~~\nDone.",
190                     "Use `" + RM + "` like this.", "Use `x`, then `\n" + RM + "`", "```\n" + RM,
191                     "Text\n\n```python\nx = 1\n```\n```\n" + CALL):
192            with self.subTest(body=body[:30]):
193                got, text = self.run_all(self.HEAD + body)
194                self.assertEqual(got, ())
195                self.assertEqual(text, body)             # nothing lost
196
197    def test_real_calls_still_fire(self):
198        for body in (CALL, "Let me do it.\n\n" + CALL, "Let me do it. " + CALL, "```\ncode\n```\n" + CALL,
199                     "`a` and `b` " + CALL, "~~~\nx\n~~~\n\n" + CALL):
200            with self.subTest(body=body[:30]):
201                self.assertEqual(self.run_all(self.HEAD + body)[0], ("write",))
202        self.assertEqual(self.run_all(self.HEAD + CALL + "\n" + CALL)[0], ("write", "write"))
203
204    def test_a_closed_call_in_a_length_cut_answer_stays_a_call(self):
205        self.assertEqual(self.run_all(self.HEAD + "Now.\n" + CALL, finish="length")[0], ("write",))
206
207    def test_without_thinking(self):
208        p = OutputParser(thinking=False, tools=SCHEMA)
209        evs = p.feed("```\n" + RM + "\n```") + p.finish()
210        self.assertEqual(calls(evs), [])
211
212
213class OverHttp(unittest.TestCase):
214    """The same rules through the real server: OpenAI chat (whole and streamed), Anthropic and Responses."""
215
216    def ask(self, script, max_tokens=800):
217        tok = ByteTokenizer()
218        svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
219        httpd = serve(svc, port=0)
220        base = f"http://127.0.0.1:{httpd.server_address[1]}"
221        msgs = [{"role": "user", "content": "save my notes"}]
222        reqs = {
223            "openai": ("/v1/chat/completions", {"tools": [{"type": "function", "function": {
224                "name": "write", "parameters": {"type": "object", "properties": PROPS}}}], "messages": msgs,
225                "max_tokens": max_tokens}),
226            "anthropic": ("/v1/messages", {"tools": [{"name": "write", "input_schema": {
227                "type": "object", "properties": PROPS}}], "messages": msgs, "max_tokens": max_tokens}),
228            "responses": ("/v1/responses", {"tools": [{"type": "function", "name": "write", "parameters": {
229                "type": "object", "properties": PROPS}}], "input": "save my notes", "max_output_tokens": max_tokens}),
230        }
231        out = {}
232        try:
233            for api, (path, body) in reqs.items():
234                for stream in (False, True):
235                    req = urllib.request.Request(base + path, data=json.dumps(dict(body, model="x", stream=stream)).encode(),
236                                                 headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
237                    with urllib.request.urlopen(req, timeout=30) as r:
238                        raw = r.read().decode()
239                    out[api, stream] = self.tool_uses(api, stream, raw)
240        finally:
241            httpd.shutdown()
242            httpd.server_close()
243        return out
244
245    @staticmethod
246    def tool_uses(api, stream, raw):
247        """How many tool calls the answer carries."""
248        if not stream:
249            m = json.loads(raw)
250            if api == "openai":
251                return len(m["choices"][0]["message"].get("tool_calls") or [])
252            if api == "anthropic":
253                return sum(b["type"] == "tool_use" for b in m["content"])
254            return sum(o["type"] == "function_call" for o in m["output"])
255        evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
256        if api == "openai":
257            return len({tc["index"] for e in evs for c in e["choices"] for tc in c["delta"].get("tool_calls") or []})
258        if api == "anthropic":
259            return sum(e["type"] == "content_block_start" and e["content_block"]["type"] == "tool_use" for e in evs)
260        return sum(e["type"] == "response.output_item.added" and e["item"]["type"] == "function_call" for e in evs)
261
262    def test_a_stranded_call_is_a_call_in_every_api(self):
263        a = self.ask("Writing the file now.\n\n" + CALL)
264        self.assertEqual(set(a.values()), {1}, a)
265
266    def test_quotes_and_cuts_are_not(self):
267        for name, script, tokens in (
268                ("fence", "Format:\n```xml\n" + RM + "\n```\nand that is all.", 800),
269                ("midsentence", "I could run " + RM + " but no.", 800),
270                ("prose after", "I could run\n" + RM + "\nbut first let me check what build holds.", 800),
271                ("cut", "I could run\n" + RM + "\nthen more thinking " * 40, len("I could run\n" + RM)),
272                ("cut exactly at the call", "Now.\n" + CALL + "\nmore thought " * 40, len("Now.\n" + CALL))):
273            with self.subTest(name):
274                a = self.ask(script, max_tokens=tokens)
275                self.assertEqual(set(a.values()), {0}, a)
276
277    def test_visible_answer_fences_on_all_three_apis(self):
278        for name, body, want in (("fence", "Format:\n```xml\n" + RM + "\n```\nDone.", 0),
279                                 ("inline", "Use `" + RM + "` here.", 0),
280                                 ("real", "Doing it.\n\n" + CALL, 1)):
281            with self.subTest(name):
282                a = self.ask( "ok</think>\n\n" + body)
283                self.assertEqual(set(a.values()), {want}, a)
284
285
286if __name__ == "__main__":
287    unittest.main()