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