okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
42.5 KiB793 linesraw
1"""DeepSeek-V4.1 through the server: its tokenizer, its chat template, the DSML tool calls, the effort words, the end
2token and the model-card defaults, over both APIs against a fake engine (no GPU, no pack, no model).
3
4    python -m unittest serve.test_dsv41 -v
5
6STRATA_DSV41_PACK=<dir> (the pack's tokenizer folder: vocab.json, merges.txt, token_type.json, tokenizer.json) adds
7the check of the real tokenizer against the ids llama.cpp (PR 30817 b72050d0) made of the same rendered prompts.
8"""
9from __future__ import annotations
10
11import json
12import os
13import sys
14import unittest
15import urllib.error
16import urllib.request
17from pathlib import Path
18
19ROOT = Path(__file__).resolve().parents[1]
20sys.path.insert(0, str(ROOT))
21sys.path.insert(0, str(ROOT / "tools"))
22import strata_tokenizer as ST  # noqa: E402
23from serve import frontend, server  # noqa: E402
24from serve.dsml import DsmlOutputParser, DsmlTranslator, to_dsml_force  # noqa: E402
25from serve.frontend import ChatTemplate, OutputParser, openai_to_messages  # noqa: E402
26from serve.server import (FAMILY_MODEL_NAMES, MockEngine, REASONING_WRAP_UP, Service, default_model_name, model_card_sampling,  # noqa: E402
27                          serve)
28
29FIX = ROOT / "serve" / "fixtures" / "deepseek41"
30TEMPLATE = FIX / "chat_template.jinja"
31GOLDEN = json.loads((FIX / "golden.json").read_text(encoding="utf-8"))
32
33BOS, EOS_TEXT = "<|begin▁of▁sentence|>", "<|end▁of▁sentence|>"
34SPECIALS = [(BOS, 3), (EOS_TEXT, 3), ("<|User|>", 3), ("<|Assistant|>", 3), ("<|System|>", 3),
35            ("<|latest_reminder|>", 3), ("<think>", 4), ("</think>", 4), ("|DSML|", 4), ("<|deepseek_image|>", 3)]
36EOS = 1
37
38
39def mini_tokenizer() -> ST.Tokenizer:
40    """The real Tokenizer class over a tiny vocabulary: DeepSeek's special tokens, then the 256 byte tokens, no merges."""
41    b2u = ST.bytes_to_unicode()
42    tokens = [s for s, _ in SPECIALS] + [b2u[b] for b in range(256)]
43    types = [t for _, t in SPECIALS] + [1] * 256
44    return ST.Tokenizer(tokens, [], types, "deepseek3", {"bos": 0, "eos": EOS})
45
46
47class DsEngine(MockEngine):
48    """Replays scripted completions as ids, then DeepSeek's end token; keeps what it was asked."""
49
50    def __init__(self, tok, script, max_context=8192):
51        super().__init__(tok, script, max_context=max_context)
52        self.scripts = [tok.encode(x, parse_special=True) + [EOS] for x in ([script] if isinstance(script, str) else script)]
53        self.script = self.scripts[0]
54        self.last_sampling = None
55        self.last = {}
56
57    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
58        self.last_sampling = dict(sampling or {})
59        got = 0
60        try:
61            for t in super().generate(ids, max_new, sampling, cancel, embeddings):
62                got += 1
63                yield t
64        finally:      # (the server stops reading at the end token: the engine's DONE comes while it is closed)
65            self.last = {"generated": got, "prompt_tokens": len(ids), "prompt_ms": 50.0, "decode_ms": got * 10.0,
66                         "finish": "stop"}
67
68
69def call(*invokes, string="true") -> str:
70    """The text DeepSeek writes for calls: [(name, [(param, value, is_string)...])...]."""
71    out = ["\n\n<|DSML| calls>"]
72    for name, params in invokes:
73        out.append(f'<|DSML| invoke name="{name}">')
74        for p, v, is_str in params:
75            out.append(f'<|DSML| parameter name="{p}" string="{"true" if is_str else "false"}">{v}</|DSML| parameter>')
76        out.append("</|DSML| invoke>")
77    out.append("</|DSML| calls>")
78    return "\n".join(out)
79
80
81WEATHER = {"type": "function", "function": {"name": "get_weather", "description": "weather",
82                                              "parameters": {"type": "object", "properties": {
83                                                  "city": {"type": "string"}, "days": {"type": "integer"}},
84                                                  "required": ["city"]}}}
85
86
87class Pre(unittest.TestCase):
88    """The pre-tokenizer is llama.cpp's DEEPSEEK3_LLM list: a sequence of splits, not one pattern."""
89
90    def split(self, text):
91        return ST._sequence_findall([ST.regex.compile(p) for p in ST.DEEPSEEK3_PATTERNS], text)
92
93    def test_digits_in_runs_of_three(self):
94        self.assertEqual(self.split("a12345678b"), ["a", "123", "456", "78", "b"])
95
96    def test_cjk_runs(self):
97        self.assertEqual(self.split("你好, world"), ["你好", ",", " world"])
98
99    def test_punctuation_then_letters_and_whitespace(self):
100        self.assertEqual(self.split("x_y.z  \n\nq"), ["x", "_y", ".z", "  \n\n", "q"])
101
102    def test_every_character_is_kept(self):
103        text = "Hello, 世界! 123\t\r\n  é \U0001f600 |DSML|"
104        self.assertEqual("".join(self.split(text)), text)
105
106
107class Tokenizer(unittest.TestCase):
108    def test_a_special_token_decodes_to_its_text(self):
109        tok = mini_tokenizer()
110        ids = tok.encode("<|User|>hi|DSML|", parse_special=True)
111        self.assertEqual(ids[0], 2)
112        self.assertEqual(tok.decode(ids), "<|User|>hi|DSML|")
113        self.assertEqual(tok.token_bytes(8), "|DSML|".encode())
114
115    def test_the_dsml_token_is_matched_without_parse_special_and_a_control_token_is_not(self):
116        tok = mini_tokenizer()
117        self.assertEqual(tok.encode("|DSML|").__len__(), 1)
118        self.assertGreater(len(tok.encode("<|User|>")), 1)
119
120    def test_qwen_tokens_are_unchanged(self):
121        b2u = ST.bytes_to_unicode()
122        tok = ST.Tokenizer([b2u[b] for b in range(256)] + ["<|im_end|>"], [], [1] * 256 + [3])
123        self.assertEqual(tok.token_bytes(256), b"<|im_end|>")
124        self.assertEqual(tok.encode("a<|im_end|>", parse_special=True), [97, 256])
125
126    @unittest.skipUnless(os.environ.get("STRATA_DSV41_PACK"), "STRATA_DSV41_PACK (the pack's tokenizer folder) not set")
127    def test_the_real_tokenizer_makes_the_ids_llama_cpp_made(self):
128        d = Path(os.environ["STRATA_DSV41_PACK"])
129        vocab = json.loads((d / "vocab.json").read_text(encoding="utf-8"))
130        tokens = [None] * len(vocab)
131        for t, i in vocab.items():
132            tokens[i] = t
133        cfg = json.loads((d / "tokenizer.json").read_text())
134        tok = ST.Tokenizer(tokens, (d / "merges.txt").read_text(encoding="utf-8").split("\n"),
135                           json.loads((d / "token_type.json").read_text()), cfg["pre"], cfg["special_ids"])
136        for case in GOLDEN:
137            self.assertEqual(tok.encode(case["text"], parse_special=True), case["ids"], case["id"] + " " + case["mode"])
138
139
140class Template(unittest.TestCase):
141    """The GGUF's own chat template (the same bytes as DeepSeek's encoding.py on the cases checked), through the
142    server's request reader and renderer: the text llama.cpp tokenized for the reference run."""
143
144    @classmethod
145    def setUpClass(cls):
146        cls.tpl = ChatTemplate(TEMPLATE)
147
148    def test_the_golden_prompts(self):
149        for case in GOLDEN:
150            messages, tools, kw = openai_to_messages(case["request"])
151            self.assertEqual(self.tpl.render(messages, tools=tools, **kw), case["text"], case["id"] + " " + case["mode"])
152
153    def test_thinking_is_the_default(self):
154        text = self.tpl.render([{"role": "user", "content": "hi"}])
155        self.assertTrue(text.endswith("<|Assistant|><think>"))
156        text = self.tpl.render([{"role": "user", "content": "hi"}], enable_thinking=False)
157        self.assertTrue(text.endswith("<|Assistant|></think>"))
158
159    def test_a_tool_call_and_its_result_render_in_dsml(self):
160        msgs = [{"role": "user", "content": "weather?"},
161                {"role": "assistant", "content": "", "reasoning_content": "call it",
162                 "tool_calls": [{"function": {"name": "get_weather", "arguments": {"city": "Zagreb", "days": 3}}}]},
163                {"role": "tool", "content": "sunny"}]
164        text = self.tpl.render(msgs, tools=[WEATHER["function"]], enable_thinking=False)
165        self.assertIn('<|DSML| invoke name="get_weather">', text)
166        self.assertIn('<|DSML| parameter name="city" string="true">Zagreb</|DSML| parameter>', text)
167        self.assertIn('<|DSML| parameter name="days" string="false">3</|DSML| parameter>', text)
168        self.assertIn("<tool_result>sunny</tool_result>", text)
169
170
171class Translator(unittest.TestCase):
172    RAW = call(("get_weather", [("city", "Zagreb", True), ("days", "3", False)]), ("ping", []))
173
174    def all_at_once(self, text):
175        t = DsmlTranslator()
176        return t.feed(text) + t.flush()
177
178    def test_a_call_becomes_the_qwen_form(self):
179        got = self.all_at_once("Sure." + self.RAW)
180        self.assertEqual(got, "Sure.\n\n<tool_call>\n<function=get_weather>\n<parameter=city>\nZagreb\n</parameter>\n"
181                              "<parameter=days>\n3\n</parameter>\n</function>\n</tool_call>\n"
182                              "<tool_call>\n<function=ping>\n</function>\n</tool_call>\n")
183
184    def test_the_split_of_the_stream_changes_nothing(self):
185        want = self.all_at_once("a < b and 1<2" + self.RAW + "tail")
186        for step in (1, 2, 3, 5, 8, 13):
187            t = DsmlTranslator()
188            text = "a < b and 1<2" + self.RAW + "tail"
189            got = "".join(t.feed(text[i:i + step]) for i in range(0, len(text), step)) + t.flush()
190            self.assertEqual(got, want, step)
191
192    def test_text_with_angle_brackets_passes(self):
193        text = "x <div> y </|DSML| nope> <|User|> <|DSML| unknown>"
194        self.assertEqual(self.all_at_once(text), text)
195
196    def test_the_end_of_the_output_inside_a_tag_is_text(self):
197        t = DsmlTranslator()
198        got = t.feed("ok <|DSML| inv") + t.flush()
199        self.assertEqual(got, "ok <|DSML| inv")
200
201    def test_a_value_that_looks_like_a_tag(self):
202        raw = call(("write", [("text", "<b>bold</b> and < 3", True)]))
203        self.assertIn("<parameter=text>\n<b>bold</b> and < 3\n</parameter>", self.all_at_once(raw))
204
205    def test_a_missing_closing_tag_is_closed(self):
206        raw = '<|DSML| calls>\n<|DSML| invoke name="f">\n<|DSML| parameter name="a" string="true">x</|DSML| invoke>'
207        self.assertEqual(self.all_at_once(raw),
208                         "<tool_call>\n<function=f>\n<parameter=a>\nx\n</parameter>\n</function>\n</tool_call>\n")
209
210
211class Parser(unittest.TestCase):
212    TOOLS = [WEATHER["function"], {"name": "lookup", "description": "", "parameters": {
213        "type": "object", "properties": {"id": {}}}}]
214
215    def run_parser(self, text, thinking=True, step=7, cls=DsmlOutputParser):
216        p = cls(thinking=thinking, tools=self.TOOLS, stream_tools=True)
217        evs = []
218        for i in range(0, len(text), step):
219            evs += p.feed(text[i:i + step])
220        evs += p.finish("stop")
221        return evs
222
223    def test_reasoning_then_two_calls(self):
224        raw = call(("get_weather", [("city", "Zagreb", True), ("days", "3", False)]), ("lookup", [("id", "123", True)]))
225        for step in (1, 4, 1000):
226            evs = self.run_parser("Think < ok.</think>" + raw, step=step)
227            self.assertEqual("".join(e.text for e in evs if e.kind == "reasoning"), "Think < ok.")
228            calls = [e.call for e in evs if e.kind == "tool_call"]
229            self.assertEqual([(c.name, c.arguments) for c in calls],
230                             [("get_weather", {"city": "Zagreb", "days": 3}), ("lookup", {"id": "123"})])
231            self.assertEqual("".join(e.text for e in evs if e.kind == "tool_args"),
232                             '{"city":"Zagreb","days":3}{"id":"123"}')
233
234    def test_a_string_value_stays_a_string_even_when_the_schema_says_nothing(self):
235        evs = self.run_parser(call(("lookup", [("id", "007", True)])), thinking=False)
236        self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": "007"}])
237        evs = self.run_parser(call(("lookup", [("id", "7", False)])), thinking=False)
238        self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": 7}])
239
240    def test_a_non_string_value_is_json(self):
241        evs = self.run_parser(call(("lookup", [("id", '{"a": [1, 2]}', False)])), thinking=False)
242        self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": {"a": [1, 2]}}])
243
244    def test_content_before_the_call_and_none_after(self):
245        evs = self.run_parser("Checking.\n\n" + call(("lookup", [("id", "x", True)]))[2:], thinking=False)
246        self.assertEqual("".join(e.text for e in evs if e.kind == "content").strip(), "Checking.")
247        self.assertEqual(sum(e.kind == "tool_call" for e in evs), 1)
248
249    def test_a_call_cut_off_by_the_length_limit_is_not_a_call(self):
250        raw = call(("get_weather", [("city", "Zagr", True)]))
251        raw = raw[:raw.index("Zagr") + 4]
252        p = DsmlOutputParser(thinking=False, tools=self.TOOLS, stream_tools=True)
253        evs = p.feed(raw) + p.finish("length")
254        self.assertEqual(sum(e.kind == "tool_call" for e in evs), 0)
255
256    def test_the_plain_parser_is_unchanged(self):
257        p = OutputParser(thinking=False, tools=self.TOOLS)
258        evs = p.feed("<tool_call>\n<function=lookup>\n<parameter=id>\n5\n</parameter>\n</function>\n</tool_call>") + p.finish("stop")   # #4701: the end of the turn settles a closed call
259        self.assertEqual([e.call.arguments for e in evs if e.kind == "tool_call"], [{"id": 5}])
260        self.assertTrue(p.clean)
261
262    def test_clean_counts_a_held_tag(self):
263        p = DsmlOutputParser(thinking=False, tools=self.TOOLS)
264        p.feed("hello <|DS")
265        self.assertFalse(p.clean)
266        p.feed("ML| calls>")
267        self.assertTrue(p.clean)
268
269    def test_forced_opening(self):
270        self.assertEqual(to_dsml_force("<tool_call>\n<function=get_weather>\n"),
271                         '<|DSML| calls>\n<|DSML| invoke name="get_weather">\n')
272        self.assertEqual(to_dsml_force("<tool_call>\n<function="), '<|DSML| calls>\n<|DSML| invoke name="')
273        self.assertIsNone(to_dsml_force(None))
274        # the opening and the model's continuation are one call
275        p = DsmlOutputParser(thinking=False, tools=self.TOOLS, stream_tools=True)
276        evs = p.feed(to_dsml_force("<tool_call>\n<function=get_weather>\n"))
277        evs += p.feed('<|DSML| parameter name="city" string="true">Rome</|DSML| parameter>\n</|DSML| invoke>\n</|DSML| calls>')
278        evs += p.finish("stop")
279        self.assertEqual([(e.call.name, e.call.arguments) for e in evs if e.kind == "tool_call"],
280                         [("get_weather", {"city": "Rome"})])
281
282
283class ReadyTimeout(unittest.TestCase):
284    """A 300+ GB model read from a slow disk needs more than the default 900 s before READY: the config's "engine_ready_s"."""
285
286    def test_the_config_sets_it_and_a_bad_value_is_said(self):
287        from serve import server
288        before = server.ENGINE_READY_S
289        self.addCleanup(setattr, server, "ENGINE_READY_S", before)
290        server.apply_ready_timeout({})
291        self.assertEqual(server.ENGINE_READY_S, before)
292        server.apply_ready_timeout({"engine_ready_s": 3600})
293        self.assertEqual(server.ENGINE_READY_S, 3600.0)
294        for bad in (0, -5, "soon", True):
295            with self.assertRaises(ValueError):
296                server.apply_ready_timeout({"engine_ready_s": bad})
297
298
299class ApiBase(unittest.TestCase):
300    """Both APIs against a fake engine that replays scripted DeepSeek text (the helpers; Api has the tests)."""
301
302    @classmethod
303    def setUpClass(cls):
304        cls.tok = mini_tokenizer()
305
306    def start(self, script):
307        tok = self.tok
308        engine = DsEngine(tok, script)
309        svc = Service(engine, tok, ChatTemplate(TEMPLATE), model_name=default_model_name({"arch": "deepseek41"}))
310        svc.model_arch = "deepseek41"
311        svc.set_family("deepseek41")
312        httpd = serve(svc, port=0)
313        self.addCleanup(httpd.server_close)
314        self.addCleanup(httpd.shutdown)
315        self.addCleanup(frontend.use_family, None)
316        self.engine, self.svc = engine, svc
317        self.base = f"http://127.0.0.1:{httpd.server_address[1]}"
318        return engine
319
320    def post(self, path, body, raw=False):
321        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
322                                     headers={"Content-Type": "application/json"})
323        try:
324            with urllib.request.urlopen(req, timeout=30) as r:
325                data = r.read().decode()
326                return r.status, (data if raw else json.loads(data))
327        except urllib.error.HTTPError as e:
328            return e.code, json.loads(e.read().decode())
329
330    def prompt(self):
331        return self.tok.decode(self.engine.last_prompt)
332
333    def chat(self, **extra):
334        body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 400, **extra}
335        return self.post("/v1/chat/completions", body)
336
337
338class Api(ApiBase):
339    # -- thinking --------------------------------------------------------------------------------
340    def test_thinking_by_default(self):
341        self.start("The user greets me.</think>\n\nHello!")
342        status, r = self.chat()
343        self.assertEqual(status, 200, r)
344        self.assertTrue(self.prompt().endswith("<|User|>hi<|Assistant|><think>"))
345        msg = r["choices"][0]["message"]
346        self.assertEqual(msg["reasoning_content"], "The user greets me.")
347        self.assertEqual(msg["content"].strip(), "Hello!")
348        self.assertEqual(r["choices"][0]["finish_reason"], "stop")
349
350    ANSWER = "17 x 23 = 391. The answer is 391."
351
352    def test_no_closing_think_tag_makes_the_text_the_answer(self):
353        """The 2-bit sets write the answer after <think> and stop without </think>: it must not arrive as reasoning only (P2003)."""
354        for effort in (None, "low", "medium", "high"):
355            with self.subTest(effort=effort, api="openai"):
356                self.start(self.ANSWER)
357                status, r = self.chat(**({"reasoning_effort": effort} if effort else {}))
358                self.assertEqual(status, 200, r)
359                msg = r["choices"][0]["message"]
360                self.assertEqual(msg["content"].strip(), self.ANSWER)
361                self.assertFalse(msg.get("reasoning_content"))
362                self.assertEqual(r["choices"][0]["finish_reason"], "stop")
363            with self.subTest(effort=effort, api="anthropic"):
364                self.start(self.ANSWER)
365                status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 400,
366                                                       "messages": [{"role": "user", "content": "hi"}],
367                                                       **({"output_config": {"effort": effort}} if effort else {})})
368                self.assertEqual(status, 200, r)
369                self.assertEqual([b["type"] for b in r["content"]], ["text"])
370                self.assertEqual(r["content"][0]["text"].strip(), self.ANSWER)
371
372    def test_no_closing_think_tag_streaming_ends_with_the_answer_as_content(self):
373        self.start(self.ANSWER)
374        status, raw = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 400,
375                                                         "stream": True}, raw=True)
376        self.assertEqual(status, 200)
377        chunks = [json.loads(l[6:]) for l in raw.splitlines() if l.startswith("data: ") and l != "data: [DONE]"]
378        content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c["choices"])
379        self.assertEqual(content.strip(), self.ANSWER)
380        status, raw = self.post("/v1/messages", {"model": "x", "max_tokens": 400, "stream": True,
381                                                 "messages": [{"role": "user", "content": "hi"}]}, raw=True)
382        self.assertEqual(status, 200)
383        self.assertIn('"text_delta"', raw)
384        self.assertIn("391", raw)
385
386    def test_a_turn_cut_by_max_tokens_is_not_turned_into_an_answer(self):
387        self.start(self.ANSWER * 30)
388        status, r = self.chat(max_tokens=8)
389        msg = r["choices"][0]["message"]
390        self.assertEqual(r["choices"][0]["finish_reason"], "length")
391        self.assertFalse(msg.get("content"))
392        self.assertTrue(msg.get("reasoning_content"))
393
394    def test_a_normal_closed_think_is_unchanged(self):
395        self.start("Reasoning here.</think>The answer.")
396        status, r = self.chat()
397        msg = r["choices"][0]["message"]
398        self.assertEqual((msg["reasoning_content"], msg["content"].strip()), ("Reasoning here.", "The answer."))
399
400    def test_thinking_off(self):
401        self.start("Hello!")
402        for extra in ({"chat_template_kwargs": {"enable_thinking": False}}, {"reasoning_effort": "none"}):
403            status, r = self.chat(**extra)
404            self.assertEqual(status, 200, r)
405            self.assertTrue(self.prompt().endswith("<|User|>hi<|Assistant|></think>"), extra)
406            msg = r["choices"][0]["message"]
407            self.assertEqual(msg["content"].strip(), "Hello!")
408            self.assertFalse(msg.get("reasoning_content"))
409
410    def test_the_end_token_is_deepseeks_not_qwens(self):
411        self.start("one<|im_end|>two")                # (not a token here: just text, like any other)
412        status, r = self.chat(chat_template_kwargs={"enable_thinking": False})
413        self.assertEqual(r["choices"][0]["message"]["content"], "one<|im_end|>two")
414
415    def test_model_name_and_card_sampling(self):
416        self.start("ok")
417        self.assertEqual(FAMILY_MODEL_NAMES["deepseek41"], "deepseek-v4.1-flash")
418        self.assertEqual(default_model_name({"arch": "deepseek41"}), "deepseek-v4.1-flash")
419        self.assertEqual(model_card_sampling("deepseek41", True), {"temperature": 1.0, "top_p": 1.0})
420        self.chat()
421        self.assertEqual(self.engine.last_sampling.get("temperature"), 1.0)
422
423    # -- effort ------------------------------------------------------------------------------------
424    def test_effort_words(self):
425        self.start("ok")
426        for given, line in (("low", "Reasoning Effort: 50 "), ("medium", "Reasoning Effort: 62 "),
427                            ("high", "Reasoning Effort: 75 "), ("max", "Reasoning Effort: 100 "),
428                            ("xhigh", "Reasoning Effort: 100 "), (40, "Reasoning Effort: 40 ")):
429            status, r = self.chat(reasoning_effort=given)
430            self.assertEqual(status, 200, (given, r))
431            self.assertIn(line, self.prompt(), given)
432        status, r = self.chat()
433        self.assertIn("Reasoning Effort: 75 ", self.prompt())
434        status, r = self.chat(reasoning_effort="extreme")
435        self.assertEqual(status, 400)
436
437    def test_anthropic_budget_picks_the_effort(self):
438        self.start("ok")
439        status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 300, "thinking": {"type": "enabled", "budget_tokens": 1000},
440                                               "messages": [{"role": "user", "content": "hi"}]})
441        self.assertEqual(status, 200, r)
442        self.assertIn("Reasoning Effort: 50 ", self.prompt())
443
444    # -- tool calls -------------------------------------------------------------------------------
445    def test_openai_tool_call(self):
446        self.start("Need the weather.</think>" + call(("get_weather", [("city", "Zagreb", True), ("days", "2", False)])))
447        status, r = self.chat(tools=[WEATHER])
448        self.assertEqual(status, 200, r)
449        self.assertIn('"name": "get_weather"', self.prompt())
450        ch = r["choices"][0]
451        self.assertEqual(ch["finish_reason"], "tool_calls")
452        tc = ch["message"]["tool_calls"][0]
453        self.assertEqual(tc["function"]["name"], "get_weather")
454        self.assertEqual(json.loads(tc["function"]["arguments"]), {"city": "Zagreb", "days": 2})
455        self.assertEqual(ch["message"]["reasoning_content"], "Need the weather.")
456
457    def test_two_calls_in_one_turn(self):
458        self.start("</think>" + call(("get_weather", [("city", "A", True)]), ("get_weather", [("city", "B", True)])))
459        status, r = self.chat(tools=[WEATHER])
460        names = [json.loads(c["function"]["arguments"])["city"] for c in r["choices"][0]["message"]["tool_calls"]]
461        self.assertEqual(names, ["A", "B"])
462
463    def test_streamed_tool_call(self):
464        self.start("</think>" + call(("get_weather", [("city", "Zagreb", True)])))
465        status, text = self.post("/v1/chat/completions", {"messages": [{"role": "user", "content": "w?"}], "tools": [WEATHER],
466                                                          "stream": True, "max_tokens": 300}, raw=True)
467        self.assertEqual(status, 200)
468        chunks = [json.loads(x[6:]) for x in text.split("\n\n") if x.startswith("data: ") and x != "data: [DONE]"]
469        calls = [tc for c in chunks for tc in c["choices"][0]["delta"].get("tool_calls", [])]
470        self.assertEqual(calls[0]["function"]["name"], "get_weather")
471        self.assertEqual(json.loads("".join(tc["function"].get("arguments", "") for tc in calls)), {"city": "Zagreb"})
472        self.assertEqual([c["choices"][0]["finish_reason"] for c in chunks if c["choices"][0].get("finish_reason")],
473                         ["tool_calls"])
474
475    def test_a_tool_result_turn_renders_for_the_model(self):
476        self.start("The weather is sunny.")
477        msgs = [{"role": "user", "content": "weather in Zagreb?"},
478                {"role": "assistant", "content": None, "tool_calls": [{"id": "c1", "type": "function", "function": {
479                    "name": "get_weather", "arguments": "{\"city\": \"Zagreb\"}"}}]},
480                {"role": "tool", "tool_call_id": "c1", "content": "sunny, 21C"}]
481        status, r = self.post("/v1/chat/completions", {"messages": msgs, "tools": [WEATHER], "max_tokens": 200,
482                                                       "chat_template_kwargs": {"enable_thinking": False}})
483        self.assertEqual(status, 200, r)
484        p = self.prompt()
485        self.assertIn('<|DSML| parameter name="city" string="true">Zagreb</|DSML| parameter>', p)
486        self.assertIn("<tool_result>sunny, 21C</tool_result>", p)
487        self.assertEqual(r["choices"][0]["message"]["content"].strip(), "The weather is sunny.")
488
489    def test_forced_tool_choice(self):
490        self.start('<|DSML| parameter name="city" string="true">Rome</|DSML| parameter>\n</|DSML| invoke>\n</|DSML| calls>')
491        status, r = self.chat(tools=[WEATHER], tool_choice={"type": "function", "function": {"name": "get_weather"}},
492                              chat_template_kwargs={"enable_thinking": False})
493        self.assertEqual(status, 200, r)
494        self.assertTrue(self.prompt().endswith('<|Assistant|></think><|DSML| calls>\n<|DSML| invoke name="get_weather">\n'), self.prompt()[-120:])
495        tc = r["choices"][0]["message"]["tool_calls"][0]
496        self.assertEqual((tc["function"]["name"], json.loads(tc["function"]["arguments"])), ("get_weather", {"city": "Rome"}))
497
498    # -- anthropic ---------------------------------------------------------------------------------
499    def test_anthropic_tool_use(self):
500        self.start("Weather needed.</think>" + call(("get_weather", [("city", "Oslo", True), ("days", "1", False)])))
501        status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 400,
502                                               "tools": [{"name": "get_weather", "description": "w", "input_schema":
503                                                          WEATHER["function"]["parameters"]}],
504                                               "messages": [{"role": "user", "content": "Oslo?"}]})
505        self.assertEqual(status, 200, r)
506        kinds = [b["type"] for b in r["content"]]
507        self.assertEqual(kinds, ["thinking", "tool_use"])
508        self.assertEqual(r["content"][1]["input"], {"city": "Oslo", "days": 1})
509        self.assertEqual(r["stop_reason"], "tool_use")
510
511    def test_anthropic_text_without_thinking(self):
512        self.start("Hello there.")
513        status, r = self.post("/v1/messages", {"model": "x", "max_tokens": 100, "thinking": {"type": "disabled"},
514                                               "messages": [{"role": "user", "content": "hi"}]})
515        self.assertEqual(status, 200, r)
516        self.assertTrue(self.prompt().endswith("<|Assistant|></think>"))
517        self.assertEqual([b["type"] for b in r["content"]], ["text"])
518        self.assertEqual(r["content"][0]["text"], "Hello there.")
519        self.assertEqual(r["stop_reason"], "end_turn")
520
521    # -- metrics -----------------------------------------------------------------------------------
522    def test_metrics_use_the_one_answer_speed(self):
523        self.start("</think>Hello, how are you today?")
524        self.chat()
525        status = urllib.request.urlopen(self.base + "/metrics", timeout=10)
526        m = json.loads(status.read().decode())
527        last = m["requests"][-1]
528        # produced tokens over the engine's decode time (10 ms a token in the fake), never over the prompt's time
529        self.assertEqual(last["decode_tok_s"], 100.0)
530
531
532    # -- the shared start of an agent's and its sub-agents' prompts (the engine keeps its state there) ------------
533    def test_the_system_prompt_and_tools_are_the_shared_start(self):
534        self.start("ok")
535        self.auto_pin("1")
536        sysmsg = {"role": "system", "content": "You are an agent. " * 20}
537        body = {"messages": [sysmsg, {"role": "user", "content": "task one"}], "tools": [WEATHER], "max_tokens": 40}
538        self.assertEqual(self.post("/v1/chat/completions", body)[0], 200)
539        n = self.engine.last_sampling["strata_prefix"]["tokens"]
540        ids = self.engine.last_prompt
541        self.assertTrue(0 < n < len(ids) - 1)
542        self.assertIn("get_weather", self.tok.decode(ids[:n]))            # the tools are in the shared start
543        self.assertNotIn("task one", self.tok.decode(ids[:n]))            # the first user message is not
544        # another agent behind the same system prompt and tools, another task: the same boundary, the same start
545        body["messages"] = [sysmsg, {"role": "user", "content": "a different task for the sub-agent"}]
546        self.assertEqual(self.post("/v1/chat/completions", body)[0], 200)
547        self.assertEqual(self.engine.last_sampling["strata_prefix"]["tokens"], n)
548        self.assertEqual(self.engine.last_prompt[:n], ids[:n])
549
550    def auto_pin(self, value):
551        old = os.environ.get("STRATA_DS4_AUTO_PIN")
552        if value is None:
553            os.environ.pop("STRATA_DS4_AUTO_PIN", None)
554        else:
555            os.environ["STRATA_DS4_AUTO_PIN"] = value
556        self.addCleanup(lambda: os.environ.pop("STRATA_DS4_AUTO_PIN", None) if old is None
557                        else os.environ.__setitem__("STRATA_DS4_AUTO_PIN", old))
558
559    def test_no_shared_start_without_a_system_prompt_or_when_switched_off(self):
560        self.start("ok")
561        self.auto_pin("1")
562        self.chat()
563        self.assertNotIn("strata_prefix", self.engine.last_sampling)     # no system message
564        body = {"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], "max_tokens": 40}
565        self.auto_pin("0")                                                # switched off
566        self.post("/v1/chat/completions", body)
567        self.assertNotIn("strata_prefix", self.engine.last_sampling)
568        self.auto_pin(None)                                               # on by default
569        self.post("/v1/chat/completions", body)
570        self.assertIn("strata_prefix", self.engine.last_sampling)
571
572    def test_a_clients_own_prefix_wins(self):
573        self.start("ok")
574        self.auto_pin("1")
575        body = {"messages": [{"role": "system", "content": "s " * 30}, {"role": "user", "content": "u"}],
576                "max_tokens": 40, "strata_prefix": {"tokens": 7}}
577        self.post("/v1/chat/completions", body)
578        self.assertEqual(self.engine.last_sampling["strata_prefix"], {"tokens": 7})
579
580    def test_the_qwen_path_asks_for_no_prefix(self):
581        # the same request on a server that is not DeepSeek's: nothing is added (Qwen keeps its own cache logic)
582        svc = Service(MockEngine(self.tok, "ok"), self.tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
583        req = {}
584        svc.prepare([{"role": "system", "content": "s"}, {"role": "user", "content": "u"}], None, {}, 16, req=req)
585        self.assertEqual(req, {})
586
587
588class SlotEnv(unittest.TestCase):
589    """The engine's kept conversations: the folder and the switch reach the DeepSeek engine only."""
590
591    KEYS = ("STRATA_DS4_SLOT_KEEP", "STRATA_DS4_SLOT_DIR")
592
593    def env(self, cfg):
594        saved = {k: os.environ.pop(k, None) for k in self.KEYS}
595        try:
596            return server.child_env(cfg)
597        finally:
598            for k, v in saved.items():
599                if v is not None:
600                    os.environ[k] = v
601
602    def test_deepseek_gets_a_folder_in_the_data_folder_and_the_default_switch(self):
603        env = self.env({"arch": "deepseek41", "log": str(Path("data") / "strata-deepseek.log"), "args": []})
604        self.assertEqual(Path(env["STRATA_DS4_SLOT_DIR"]), Path("data") / "ds4-slots")
605        self.assertEqual(env["STRATA_DS4_SLOT_KEEP"], "1")
606        self.assertEqual(env["STRATA_DS4_SLOT_GB"], "2")
607
608    def test_the_configs_own_settings_win(self):
609        env = self.env({"arch": "deepseek41", "log": "x/y.log",
610                        "env": {"STRATA_DS4_SLOT_KEEP": "1", "STRATA_DS4_SLOT_DIR": "elsewhere"}})
611        self.assertEqual((env["STRATA_DS4_SLOT_KEEP"], env["STRATA_DS4_SLOT_DIR"]), ("1", "elsewhere"))
612
613    def test_other_families_get_nothing(self):
614        for arch in ("qwen4exp", None, "gyro"):
615            env = self.env({"arch": arch, "log": "x/y.log"} if arch else {"log": "x/y.log"})
616            self.assertFalse([k for k in env if k.startswith("STRATA_DS4_")], arch)
617
618class ThinkForever(DsEngine):
619    """Thinks without end (random letters) until the thinking is closed in the prompt, then answers."""
620
621    ANSWER = "Four."
622
623    def __init__(self, tok):
624        super().__init__(tok, "")
625        self.prompts = []
626
627    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
628        self.prompts.append(list(ids))
629        self.last_prompt = list(ids)
630        got = 0
631        try:
632            if self.tok.decode(list(ids[-14:])).endswith("</think>\n\n"):
633                out = self.tok.encode(self.ANSWER) + [EOS]
634            else:
635                import random
636                rng = random.Random(len(ids))          # (no repeated token: the server's loop guard would end it)
637                out = self.tok.encode("".join(chr(97 + rng.randrange(26)) for _ in range(max_new)))
638            for t in out[:max_new]:
639                if cancel.is_set():
640                    return
641                got += 1
642                yield t
643        finally:
644            self.last = {"generated": got, "prompt_tokens": len(ids), "prompt_ms": 50.0, "decode_ms": got * 10.0,
645                         "finish": "stop"}
646
647
648class SmallCap(ApiBase):
649    """A short max_tokens (200-600) with the thinking on: it was all spent on the thinking and no text block came.
650    With no budget of the client's own the thinking is capped at half of max_tokens (this family only)."""
651
652    def start_forever(self):
653        self.start("")
654        engine = ThinkForever(self.tok)
655        self.svc.engine = engine
656        self.engine = engine
657        return engine
658
659    def text_of(self, r):
660        return "".join(c.get("text", "") for c in r["content"] if c["type"] == "text")
661
662    def test_every_short_cap_gets_an_answer_on_both_apis(self):
663        for cap in (200, 400, 600):
664            for api in ("anthropic", "openai"):
665                with self.subTest(cap=cap, api=api):
666                    self.start_forever()
667                    if api == "anthropic":
668                        status, r = self.post("/v1/messages", {"model": "x", "max_tokens": cap, "thinking": {"type": "enabled"},
669                                                               "messages": [{"role": "user", "content": "2+2?"}]})
670                        self.assertEqual(status, 200, r)
671                        self.assertEqual(self.text_of(r), ThinkForever.ANSWER)
672                        self.assertLessEqual(r["usage"]["output_tokens"], cap)
673                    else:
674                        status, r = self.chat(max_tokens=cap)
675                        self.assertEqual(status, 200, r)
676                        self.assertEqual(r["choices"][0]["message"]["content"], ThinkForever.ANSWER)
677                        self.assertLessEqual(r["usage"]["completion_tokens"], cap)
678                    first = self.engine.prompts[0]
679                    self.assertEqual(len(self.engine.prompts), 2)          # the thinking was wrapped up, then answered
680                    self.assertEqual(len(self.engine.prompts[1]) - len(first), cap // 2 - 0 + len(self.tok.encode(
681                        REASONING_WRAP_UP, parse_special=True)))
682
683    def test_thinking_off_is_untouched(self):
684        for cap in (200, 400, 600):
685            with self.subTest(cap=cap):
686                self.start("Plain answer.")
687                status, r = self.chat(max_tokens=cap, reasoning_effort="none")
688                self.assertEqual(status, 200, r)
689                self.assertEqual(r["choices"][0]["message"]["content"], "Plain answer.")
690                status, r = self.post("/v1/messages", {"model": "x", "max_tokens": cap, "thinking": {"type": "disabled"},
691                                                       "messages": [{"role": "user", "content": "hi"}]})
692                self.assertEqual(self.text_of(r), "Plain answer.")
693
694    def test_a_client_budget_wins(self):
695        self.start_forever()
696        status, r = self.chat(max_tokens=600, reasoning_budget_tokens=20)
697        self.assertEqual(status, 200, r)
698        self.assertEqual(len(self.engine.prompts[1]) - len(self.engine.prompts[0]), 20 + len(self.tok.encode(
699            REASONING_WRAP_UP, parse_special=True)))
700
701    def test_a_tool_call_under_a_short_cap_still_parses(self):
702        for cap in (200, 400, 600):
703            with self.subTest(cap=cap):
704                self.start("Need it.</think>" + call(("f", [("a", "1", True)])))
705                status, r = self.chat(max_tokens=cap, tools=[{"type": "function", "function": {
706                    "name": "f", "description": "f", "parameters": {"type": "object", "properties": {"a": {"type": "string"}}}}}])
707                self.assertEqual(status, 200, r)
708                calls = r["choices"][0]["message"]["tool_calls"]
709                self.assertEqual(calls[0]["function"]["name"], "f")
710                self.assertEqual(json.loads(calls[0]["function"]["arguments"]), {"a": "1"})
711                self.assertEqual(len(self.engine.last_prompt) > 0, True)
712
713    def test_the_family_default_thinking_budget(self):
714        """DeepSeek-V4.1 only, as Maya ships it: 32768 thinking tokens when neither the request nor the config names a budget."""
715        self.start("ok")
716        self.assertEqual(self.svc.reasoning_budget({}), 32768)
717        self.assertIsNone(self.svc.reasoning_budget({"reasoning_budget_tokens": 0}))        # a request turns it off
718        self.assertEqual(self.svc.reasoning_budget({"reasoning_budget_tokens": 50}), 50)    # and its own wins
719        self.assertEqual(self.svc.reasoning_budget({"thinking_budget_tokens": 70}), 70)
720        self.svc.reasoning_budget_tokens, self.svc.reasoning_budget_configured = 90, True
721        self.assertEqual(self.svc.reasoning_budget({}), 90)                                 # the config's wins
722        self.svc.reasoning_budget_tokens = 0                                                # the config says none
723        self.assertIsNone(self.svc.reasoning_budget({}))
724        self.svc.reasoning_budget_configured = False
725        self.svc.set_family(None)
726        self.assertIsNone(self.svc.reasoning_budget({}))                                    # other families: none
727
728    def test_the_default_budget_closes_a_long_thinking(self):
729        self.start_forever()
730        status, r = self.chat(max_tokens=5000)
731        self.assertEqual(status, 200, r)
732        self.assertEqual(r["choices"][0]["message"]["content"], ThinkForever.ANSWER)
733        status, r = self.chat(max_tokens=300, reasoning_effort="none")                      # thinking off: no budget, no wrap-up
734        self.assertEqual(len(self.engine.prompts), 3)
735
736    def test_other_families_keep_the_old_behaviour(self):
737        self.start_forever()
738        self.svc.set_family(None)
739        status, r = self.chat(max_tokens=300)
740        self.assertEqual(len(self.engine.prompts), 1)                       # no wrap-up: Qwen's serving is as it was
741
742
743class PickTemplateTests(unittest.TestCase):
744    """A pack made from another GGUF can ship the V4-Flash template (`tool_calls`, no space): the V4.1 model then
745    writes malformed calls (P2003 install test).  The server swaps in the V4.1 template for such a pack."""
746
747    def test_v4flash_pack_template_is_replaced(self):
748        import tempfile
749        from serve import dsml
750        with tempfile.TemporaryDirectory() as d:
751            old = Path(d) / "old.jinja"
752            old.write_text("{%- set dsml_token = '|DSML|' -%}{{ '<' + dsml_token + 'tool_calls>' }}", encoding="utf-8")
753            self.assertEqual(dsml.pick_template(old), (dsml.FIXTURE_TEMPLATE, True))
754            same = Path(d) / "same.jinja"
755            same.write_text(dsml.FIXTURE_TEMPLATE.read_text(encoding="utf-8"), encoding="utf-8")
756            self.assertEqual(dsml.pick_template(same), (same, False))
757            self.assertEqual(dsml.pick_template(Path(d) / "none.jinja"), (dsml.FIXTURE_TEMPLATE, False))
758
759    def test_fixture_is_accepted(self):
760        from serve import dsml
761        self.assertTrue(dsml.v41_template_ok(dsml.FIXTURE_TEMPLATE.read_text(encoding="utf-8")))
762
763
764class ArchFromTokenizer(unittest.TestCase):
765    """#4137: a config without "arch" (serve/server.py run on its own) must not serve DeepSeek with the Qwen stop ids."""
766
767    def test_a_deepseek_tokenizer_without_an_arch_is_deepseek41(self):
768        self.assertEqual(server.arch_from_tokenizer(None, "deepseek3"), "deepseek41")
769        self.assertEqual(server.arch_from_tokenizer("", "deepseek3"), "deepseek41")
770
771    def test_an_arch_the_config_names_is_kept(self):
772        self.assertEqual(server.arch_from_tokenizer("qwen4exp", "deepseek3"), "qwen4exp")
773        self.assertEqual(server.arch_from_tokenizer("deepseek41", "qwen35"), "deepseek41")
774
775    def test_a_qwen_tokenizer_names_nothing(self):
776        self.assertIsNone(server.arch_from_tokenizer(None, "qwen35"))
777        self.assertIsNone(server.arch_from_tokenizer(None, None))
778
779    def test_without_the_family_the_pieces_of_im_end_are_not_stop_ids_and_the_end_token_is(self):
780        # what the reporter's config got (#4137, #4576): the DeepSeek tokenizer splits <|im_end|> into pieces, so "|", ">" and "im" (Nerazim)
781        # stopped a reply, and the end token (id 1) did not stop it at all
782        tok = mini_tokenizer()
783        wrong = Service(DsEngine(tok, "x"), tok, ChatTemplate(TEMPLATE))
784        self.assertIn(EOS, wrong.stop_ids)
785        self.assertFalse(wrong.stop_ids & set(tok.encode("|", parse_special=True)))
786        right = Service(DsEngine(tok, "x"), tok, ChatTemplate(TEMPLATE))
787        right.set_family("deepseek41")
788        self.addCleanup(frontend.use_family, None)
789        self.assertEqual(right.stop_ids, {EOS})
790
791
792if __name__ == "__main__":
793    unittest.main()