okami.mom/strata

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

Niko1221Merge branch 'f-142-small' into f-142f5aa356f1

main
9.9 KiB189 linesraw
1"""serve/test_reasoning_tools.py - #804 (strict form of PR #787): a tool call the model writes inside its reasoning.
2
3A call inside the reasoning counts only when tools are declared and the name is one of them; anything else stays
4reasoning text.  Without tools the parser is byte-identical to before.
5
6    python -m unittest serve.test_reasoning_tools -v
7"""
8from __future__ import annotations
9
10import json
11import sys
12import unittest
13import unittest.mock
14import urllib.request
15from pathlib import Path
16
17sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18from serve.frontend import ChatTemplate, OutputParser  # noqa: E402
19from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
20from serve.test_server import CTX, UnfinishedToolCall  # noqa: E402
21
22ROOT = Path(__file__).resolve().parents[1]
23CALL = "<tool_call>\n<function=read_file>\n<parameter=limit>\n120\n</parameter>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n</tool_call>"
24OTHER = CALL.replace("read_file", "not_declared")
25TOOLS = [{"name": "read_file", "parameters": {"properties": {"limit": {"type": "integer"}, "path": {"type": "string"}}}}]
26
27
28def run(text, width, tools=TOOLS, thinking=True, stream_tools=True):
29    p = OutputParser(thinking=thinking, tools=tools, stream_tools=stream_tools)
30    evs = []
31    for i in range(0, len(text), width):
32        evs += p.feed(text[i:i + width])
33    return evs + p.finish()
34
35
36def joined(evs, kind):
37    return "".join(e.text for e in evs if e.kind == kind)
38
39
40class Parser(unittest.TestCase):
41    def test_a_declared_call_in_the_reasoning_is_a_call(self):
42        text = "before\n" + CALL + "\n</think>\n\nanswer"      # at a line start, nothing but whitespace after it (#1058)
43        for width in (1, 2, 7, 100_000):
44            with self.subTest(width=width):
45                evs = run(text, width)
46                calls = [e.call for e in evs if e.kind == "tool_call"]
47                self.assertEqual([(c.name, c.arguments) for c in calls],
48                                 [("read_file", {"limit": 120, "path": "file.txt"})])
49                self.assertEqual(joined(evs, "reasoning"), "before\n")
50                self.assertEqual(joined(evs, "content"), "answer")
51                self.assertFalse([e for e in evs if e.kind in ("tool_start", "tool_args")])   # never streamed
52
53    def test_an_undeclared_name_stays_reasoning(self):
54        text = "see " + OTHER + " done</think>\n\nanswer"
55        for width in (1, 5, 100_000):
56            with self.subTest(width=width):
57                evs = run(text, width)
58                self.assertFalse([e for e in evs if e.kind == "tool_call"])
59                self.assertEqual(joined(evs, "reasoning"), "see " + OTHER + " done")
60                self.assertEqual(joined(evs, "content"), "answer")
61
62    def test_no_tools_declared_is_unchanged(self):
63        text = "before\n" + CALL + "\n</think>\n\nanswer"
64        for tools in (None, []):
65            for width in (1, 7, 100_000):
66                with self.subTest(tools=tools, width=width):
67                    evs = run(text, width, tools=tools)
68                    self.assertFalse([e for e in evs if e.kind == "tool_call"])
69                    self.assertEqual(joined(evs, "reasoning"), "before\n" + CALL + "\n")
70                    self.assertEqual(joined(evs, "content"), "answer")
71
72    def test_an_unfinished_call_is_never_a_call(self):
73        for text in ("before<tool_call>\n<function=read_file>\n",
74                     "before<tool_call>\n<function=read_file>\n<parameter=path>\nfile.txt\n</parameter>\n"):
75            for width in (1, 100_000):
76                with self.subTest(text=text[-20:], width=width):
77                    evs = run(text, width)
78                    self.assertFalse([e for e in evs if e.kind == "tool_call"])
79                    self.assertEqual(joined(evs, "reasoning"), text)
80
81    def test_the_thinking_ending_inside_a_call_makes_it_text(self):
82        text = "a<tool_call>\n<function=read_file>\nhmm</think>\n\nthe answer"
83        for width in (1, 100_000):
84            with self.subTest(width=width):
85                evs = run(text, width)
86                self.assertFalse([e for e in evs if e.kind == "tool_call"])
87                self.assertEqual(joined(evs, "reasoning"), "a<tool_call>\n<function=read_file>\nhmm")
88                self.assertEqual(joined(evs, "content"), "the answer")
89
90    def test_a_call_in_the_answer_is_unchanged(self):
91        text = "think</think>\n\nok " + CALL
92        for width in (1, 100_000):
93            evs = run(text, width)
94            self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1)
95            self.assertEqual(joined(evs, "reasoning"), "think")
96
97    def test_a_tag_that_never_closes_does_not_hold_the_thinking_back(self):
98        from serve import frontend
99        text = "a\n<tool_call> " + "thinking on and on " * 3000 + "</think>\n\nanswer"
100        with unittest.mock.patch.object(frontend, "RCALL_MAX", 1000):
101            evs = run(text, 50)
102        first_reasoning_at = next(i for i, e in enumerate(evs) if e.kind == "reasoning" and len(e.text) > 100)
103        self.assertLess(first_reasoning_at, 100)                     # streamed, not kept until </think>
104        self.assertEqual(joined(evs, "reasoning"), text.split("</think>")[0])
105        self.assertEqual(joined(evs, "content"), "answer")
106
107    def test_a_partial_tag_is_held(self):
108        p = OutputParser(thinking=True, tools=TOOLS)
109        evs = p.feed("hello <tool_c")
110        self.assertEqual(joined(evs, "reasoning"), "hello ")
111        self.assertEqual(joined(p.feed("ats are nice</think>"), "reasoning"), "<tool_cats are nice")
112
113
114class QuotedThinkEnd(unittest.TestCase):
115    """#537: a `</think>` the model quotes while it thinks - right after a quote or backtick, with no line break after
116    it - is reasoning text; the end of the thinking is still a `</think>` with a line break after it."""
117
118    def test_a_quoted_tag_stays_reasoning(self):
119        for quote in ("in rcall, `</think>` could arrive inside the held body",
120                      'the mock engine returns "</think>\\n\\n2", no tool call',
121                      '```python\ntext = ("</think>\\n\\nI will use the tag now.")\n```',
122                      "split it on '</think>' first"):
123            text = "plan\n" + quote + "\ndone\n</think>\n\nanswer"
124            for width in (1, 7, 100_000):
125                with self.subTest(quote=quote[:24], width=width):
126                    evs = run(text, width)
127                    self.assertEqual(joined(evs, "reasoning"), "plan\n" + quote + "\ndone\n")
128                    self.assertEqual(joined(evs, "content"), "answer")
129
130    def test_a_call_quoted_after_it_is_not_run(self):
131        text = ('it returns "</think>\\n\\n2" here.\nThe call looks like this:\n' + CALL + " in the answer.\n"
132                "</think>\n\n" + CALL)
133        for width in (1, 7, 100_000):
134            with self.subTest(width=width):
135                evs = run(text, width)
136                self.assertEqual(len([e for e in evs if e.kind == "tool_call"]), 1)      # the answer's own call
137                self.assertIn(CALL + " in the answer.", joined(evs, "reasoning"))
138                self.assertEqual(joined(evs, "content"), "")
139
140    def test_the_end_after_a_quote_still_ends_the_thinking(self):
141        for thought in ('she said "yes"', "it is `x`", "it is 'x'"):
142            for width in (1, 100_000):
143                with self.subTest(thought=thought, width=width):
144                    evs = run(thought + "</think>\n\nanswer", width)
145                    self.assertEqual(joined(evs, "reasoning"), thought)
146                    self.assertEqual(joined(evs, "content"), "answer")
147
148    def test_an_output_that_ends_on_the_tag(self):
149        for width in (1, 100_000):
150            evs = run('say "</think>', width)
151            self.assertEqual(joined(evs, "reasoning"), 'say "')
152            self.assertEqual(joined(evs, "content"), "")
153
154
155class OverHttp(unittest.TestCase):
156    def test_finish_reasons_and_block_order(self):
157        helper = UnfinishedToolCall("test_parser")
158        helper.PROPS = {"path": {"type": "string"}}
159        script = "Let me look.\n<tool_call>\n<function=write>\n<parameter=path>\nfile.txt\n</parameter>\n</function>\n" \
160                 "</tool_call>\n</think>\n\ndone"
161        a = helper.answers(script)
162        self.assertEqual((a["openai", False][0], [json.loads(x) for x in a["openai", False][1]]),
163                         ("tool_calls", [{"path": "file.txt"}]))
164        self.assertEqual(a["anthropic", False], ("tool_use", [{"path": "file.txt"}]))
165        # the order of the Anthropic stream's blocks: thinking, the call, the answer
166        tok = ByteTokenizer()
167        svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
168        httpd = serve(svc, port=0)
169        try:
170            body = {"model": "x", "max_tokens": 500, "stream": True, "messages": [{"role": "user", "content": "hi"}],
171                    "tools": [{"name": "write", "input_schema": {"type": "object", "properties": helper.PROPS}}]}
172            req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/messages",
173                                         data=json.dumps(body).encode(), headers={"Content-Type": "application/json",
174                                                                                   "anthropic-version": "2023-06-01"})
175            with urllib.request.urlopen(req, timeout=30) as r:
176                raw = r.read().decode()
177            evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
178            order = [e["content_block"]["type"] for e in evs if e["type"] == "content_block_start"]
179            self.assertEqual(order, ["thinking", "tool_use", "text"])
180            tool = [e["delta"]["partial_json"] for e in evs if e["type"] == "content_block_delta"
181                    and e["delta"]["type"] == "input_json_delta"]
182            self.assertEqual(json.loads("".join(tool)), {"path": "file.txt"})
183        finally:
184            httpd.shutdown()
185            httpd.server_close()
186
187
188if __name__ == "__main__":
189    unittest.main()