okami.mom/strata

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

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
8.8 KiB193 linesraw
1"""serve/test_tool_format.py - the tool-call parser is chosen from the chat template (Qwen4 prep, P4).
2
3  * serve/toolformat.py names the form a template documents: xml (every template Strata ships), json (Qwen3 / Hermes), dsml,
4    none, other;
5  * serve/frontend.py parser_for_template() maps that to a parser class: JSON templates get JsonOutputParser, everything else
6    keeps OutputParser, so every model that runs today gets the class it always had;
7  * serve/tool_parser_golden.json holds the events each parser gives for fixed model outputs, fed whole, in 5-character pieces and
8    one character at a time, with and without streamed arguments.
9
10    python -m unittest serve.test_tool_format
11"""
12from __future__ import annotations
13
14import gzip
15import json
16import tempfile
17import unittest
18from pathlib import Path
19
20from serve import toolformat
21from serve.frontend import ChatTemplate, JsonOutputParser, OutputParser, parser_for_template
22
23ROOT = Path(__file__).resolve().parents[1]
24GOLDEN = json.loads((ROOT / "serve" / "tool_parser_golden.json").read_text(encoding="utf-8"))
25FIXTURES = ROOT / "tools" / "qwen4_intake_fixtures"
26
27HERMES = """{%- if tools %}<|im_start|>system
28# Tools
29
30You may call one or more functions to assist with the user query.
31
32<tools>
33{%- for tool in tools %}
34{{ tool | tojson }}
35{%- endfor %}
36</tools>
37
38For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
39<tool_call>
40{"name": <function-name>, "arguments": <args-json-object>}
41</tool_call><|im_end|>
42{%- endif %}
43{%- for m in messages %}
44<|im_start|>{{ m.role }}
45{{ m.content }}<|im_end|>
46{%- endfor %}
47{%- if add_generation_prompt %}
48<|im_start|>assistant
49{%- endif %}"""
50
51NO_TOOLS = "{%- for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{%- endfor %}"
52ODD = "{%- if tools %}Call a tool by writing [TOOL name(args)] and nothing else.{%- endif %}{{ messages }}"
53
54
55def fixture_template(name: str) -> str:
56    with gzip.open(FIXTURES / (name + ".json.gz"), "rt", encoding="utf-8") as f:
57        return json.load(f)["files"][0]["metadata"]["tokenizer.chat_template"]
58
59
60def normalised(parser_cls, raw: str, thinking: bool, chunk: int, stream: bool) -> list:
61    p = parser_cls(thinking=thinking, tools=GOLDEN["tools"], stream_tools=stream)
62    events = []
63    for i in range(0, len(raw), chunk):
64        events += p.feed(raw[i:i + chunk])
65    events += p.finish()
66    out: list = []
67    for e in events:
68        if e.kind == "tool_call":
69            out.append(["tool_call", "", e.call.name, e.call.arguments])
70        elif e.kind in ("content", "reasoning"):
71            if out and out[-1][0] == e.kind:
72                out[-1][1] += e.text
73            else:
74                out.append([e.kind, e.text, None, None])
75    return out
76
77
78class Detection(unittest.TestCase):
79    def test_every_template_strata_ships_is_xml(self):
80        self.assertEqual(toolformat.tool_format((ROOT / "serve" / "chat_template.jinja").read_text(encoding="utf-8")), "xml")
81        for name in ("fn_unsloth_ud_q4_k_xl", "fn_swift_iq3_s", "q36_ud_q4_k_xl"):
82            with self.subTest(name):
83                self.assertEqual(toolformat.tool_format(fixture_template(name)), "xml")
84
85    def test_other_forms(self):
86        self.assertEqual(toolformat.tool_format(fixture_template("ds41_ud_q8_k_xl")), "dsml")
87        self.assertEqual(toolformat.tool_format(HERMES), "json")
88        self.assertEqual(toolformat.tool_format(NO_TOOLS), "none")
89        self.assertEqual(toolformat.tool_format(ODD), "other")
90        self.assertEqual(toolformat.tool_format(""), "none")
91        self.assertEqual(toolformat.tool_format(None), "none")
92
93    def test_the_real_qwen3_template_is_json(self):
94        # recorded from unsloth/Qwen3-0.6B-GGUF (Apache-2.0): the form this parser exists for
95        src = (FIXTURES / "qwen3-0.6b.chat_template.jinja").read_text(encoding="utf-8")
96        self.assertEqual(toolformat.tool_format(src), "json")
97        self.assertIs(parser_for_template(src), JsonOutputParser)
98
99    def test_thinking_tags(self):
100        t = toolformat.thinking_tags((ROOT / "serve" / "chat_template.jinja").read_text(encoding="utf-8"))
101        self.assertTrue(t["has_think_tags"])
102        self.assertTrue(t["enable_thinking_switch"])
103        self.assertFalse(toolformat.thinking_tags(HERMES)["has_think_tags"])
104
105
106class Selection(unittest.TestCase):
107    def test_shipped_templates_keep_the_class_they_had(self):
108        for src in [(ROOT / "serve" / "chat_template.jinja").read_text(encoding="utf-8"),
109                    *(fixture_template(n) for n in ("fn_unsloth_ud_q4_k_xl", "fn_swift_iq3_s", "q36_ud_q4_k_xl", "ds41_ud_q8_k_xl")),
110                    NO_TOOLS, ODD, "", None]:
111            self.assertIs(parser_for_template(src), OutputParser)
112
113    def test_json_template_gets_the_json_parser(self):
114        self.assertIs(parser_for_template(HERMES), JsonOutputParser)
115        self.assertTrue(issubclass(JsonOutputParser, OutputParser))
116
117    def test_service_picks_by_template_and_the_family_still_wins(self):
118        from serve.server import ByteTokenizer, MockEngine, Service
119        with tempfile.TemporaryDirectory() as d:
120            h = Path(d) / "hermes.jinja"
121            h.write_text(HERMES, encoding="utf-8")
122            tok = ByteTokenizer()
123            self.assertIs(Service(MockEngine(tok, "ok"), tok, ChatTemplate(h)).parser_cls, JsonOutputParser)
124            shipped = ChatTemplate(ROOT / "serve" / "chat_template.jinja")
125            self.assertIs(Service(MockEngine(tok, "ok"), tok, shipped).parser_cls, OutputParser)
126            ds = Service(MockEngine(tok, "ok"), tok, ChatTemplate(h))
127            ds.set_family("deepseek41")
128            from serve import dsml
129            self.assertIs(ds.parser_cls, dsml.DsmlOutputParser)
130
131
132class UnknownPreTokenizerAtStart(unittest.TestCase):
133    """The server stops at start on a tokenizer pack whose pre-tokenizer it has no rule for (one clear line, exit status 2), and still
134    starts on the ones it has."""
135
136    def pack(self, d: Path, pre: str) -> Path:
137        t = d / "tokenizer"
138        t.mkdir()
139        chars = [chr(i) for i in range(32, 127)]
140        (t / "vocab.json").write_text(json.dumps({c: i for i, c in enumerate(chars)}), encoding="utf-8")
141        (t / "merges.txt").write_text("", encoding="utf-8")
142        (t / "token_type.json").write_text(json.dumps([1] * len(chars)), encoding="utf-8")
143        (t / "tokenizer.json").write_text(json.dumps({"pre": pre, "special_ids": {}}), encoding="utf-8")
144        return t
145
146    def test_unknown_pre_stops_with_a_line(self):
147        import contextlib
148        import io
149        from serve import server
150        with tempfile.TemporaryDirectory() as d:
151            t = self.pack(Path(d), "qwen4")
152            err = io.StringIO()
153            with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm:
154                server.main(["--engine", "mock", "--tokenizer", str(t), "--port", "0"])
155            self.assertEqual(cm.exception.code, 2)
156            self.assertIn("'qwen4'", err.getvalue())
157            self.assertIn("so it isn't loaded", err.getvalue())
158            self.assertIn("Strata doesn't have yet ('qwen4')", err.getvalue())
159            self.assertIn("the model's tokenizer (", err.getvalue())
160            self.assertNotIn("Traceback", err.getvalue())
161
162
163class Golden(unittest.TestCase):
164    def check(self, cls_for_case, cases):
165        for c in cases:
166            raw = c["input"]
167            for chunk in (len(raw), 5, 1):
168                for stream in (False, True):
169                    with self.subTest(case=c["name"], chunk=chunk, stream_tools=stream):
170                        self.assertEqual(normalised(cls_for_case, raw, c["thinking"], chunk, stream), c["events"])
171
172    def test_xml_form_through_the_class_every_shipped_template_selects(self):
173        for src in (fixture_template("fn_unsloth_ud_q4_k_xl"), fixture_template("q36_ud_q4_k_xl")):
174            self.check(parser_for_template(src), GOLDEN["xml"])
175
176    def test_json_form_through_the_class_a_json_template_selects(self):
177        self.check(parser_for_template(HERMES), GOLDEN["json"])
178
179    def test_json_parser_reads_json_without_the_recovery_switch(self):
180        raw = GOLDEN["json"][0]["input"]
181        p = JsonOutputParser(thinking=False, tools=GOLDEN["tools"], recover=False)
182        calls = [e.call for e in p.feed(raw) + p.finish() if e.kind == "tool_call"]
183        self.assertEqual([(c.name, c.arguments) for c in calls], [("get_weather", {"city": "Paris", "days": 3})])
184        p = OutputParser(thinking=False, tools=GOLDEN["tools"], recover=False)
185        calls = [e.call for e in p.feed(raw) + p.finish() if e.kind == "tool_call"]
186        self.assertEqual(calls, [])                      # the XML parser alone leaves JSON as text, as it always did
187
188    def test_xml_form_is_not_changed_by_the_json_parser_existing(self):
189        self.check(OutputParser, GOLDEN["xml"])
190
191
192if __name__ == "__main__":
193    unittest.main()