okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cded60248
main
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, 4none, other; 5* serve/frontend.py parser_for_template() maps that to a parser class: JSON templates get JsonOutputParser, everything else 6keeps 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 8one character at a time, with and without streamed arguments. 9 10python -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 : 56with gzip .open (FIXTURES / (name + ".json.gz" ),"rt" ,encoding = "utf-8" )as f : 57return json .load (f )["files" ][0 ]["metadata" ]["tokenizer.chat_template" ] 58 59 60def normalised (parser_cls ,raw :str ,thinking :bool ,chunk :int ,stream :bool )-> list : 61p = parser_cls (thinking = thinking ,tools = GOLDEN ["tools" ],stream_tools = stream ) 62events = [] 63for i in range (0 ,len (raw ),chunk ): 64events += p .feed (raw [i :i + chunk ]) 65events += p .finish () 66out :list = [] 67for e in events : 68if e .kind == "tool_call" : 69out .append (["tool_call" ,"" ,e .call .name ,e .call .arguments ]) 70elif e .kind in ("content" ,"reasoning" ): 71if out and out [- 1 ][0 ]== e .kind : 72out [- 1 ][1 ]+= e .text 73else : 74out .append ([e .kind ,e .text ,None ,None ]) 75return out 76 77 78class Detection (unittest .TestCase ): 79def test_every_template_strata_ships_is_xml (self ): 80self .assertEqual (toolformat .tool_format ((ROOT / "serve" / "chat_template.jinja" ).read_text (encoding = "utf-8" )),"xml" ) 81for name in ("fn_unsloth_ud_q4_k_xl" ,"fn_swift_iq3_s" ,"q36_ud_q4_k_xl" ): 82with self .subTest (name ): 83self .assertEqual (toolformat .tool_format (fixture_template (name )),"xml" ) 84 85def test_other_forms (self ): 86self .assertEqual (toolformat .tool_format (fixture_template ("ds41_ud_q8_k_xl" )),"dsml" ) 87self .assertEqual (toolformat .tool_format (HERMES ),"json" ) 88self .assertEqual (toolformat .tool_format (NO_TOOLS ),"none" ) 89self .assertEqual (toolformat .tool_format (ODD ),"other" ) 90self .assertEqual (toolformat .tool_format ("" ),"none" ) 91self .assertEqual (toolformat .tool_format (None ),"none" ) 92 93def 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 95src = (FIXTURES / "qwen3-0.6b.chat_template.jinja" ).read_text (encoding = "utf-8" ) 96self .assertEqual (toolformat .tool_format (src ),"json" ) 97self .assertIs (parser_for_template (src ),JsonOutputParser ) 98 99def test_thinking_tags (self ): 100t = toolformat .thinking_tags ((ROOT / "serve" / "chat_template.jinja" ).read_text (encoding = "utf-8" )) 101self .assertTrue (t ["has_think_tags" ]) 102self .assertTrue (t ["enable_thinking_switch" ]) 103self .assertFalse (toolformat .thinking_tags (HERMES )["has_think_tags" ]) 104 105 106class Selection (unittest .TestCase ): 107def test_shipped_templates_keep_the_class_they_had (self ): 108for 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" )), 110NO_TOOLS ,ODD ,"" ,None ]: 111self .assertIs (parser_for_template (src ),OutputParser ) 112 113def test_json_template_gets_the_json_parser (self ): 114self .assertIs (parser_for_template (HERMES ),JsonOutputParser ) 115self .assertTrue (issubclass (JsonOutputParser ,OutputParser )) 116 117def test_service_picks_by_template_and_the_family_still_wins (self ): 118from serve .server import ByteTokenizer ,MockEngine ,Service 119with tempfile .TemporaryDirectory ()as d : 120h = Path (d )/ "hermes.jinja" 121h .write_text (HERMES ,encoding = "utf-8" ) 122tok = ByteTokenizer () 123self .assertIs (Service (MockEngine (tok ,"ok" ),tok ,ChatTemplate (h )).parser_cls ,JsonOutputParser ) 124shipped = ChatTemplate (ROOT / "serve" / "chat_template.jinja" ) 125self .assertIs (Service (MockEngine (tok ,"ok" ),tok ,shipped ).parser_cls ,OutputParser ) 126ds = Service (MockEngine (tok ,"ok" ),tok ,ChatTemplate (h )) 127ds .set_family ("deepseek41" ) 128from serve import dsml 129self .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 134starts on the ones it has.""" 135 136def pack (self ,d :Path ,pre :str )-> Path : 137t = d / "tokenizer" 138t .mkdir () 139chars = [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" ) 144return t 145 146def test_unknown_pre_stops_with_a_line (self ): 147import contextlib 148import io 149from serve import server 150with tempfile .TemporaryDirectory ()as d : 151t = self .pack (Path (d ),"qwen4" ) 152err = io .StringIO () 153with contextlib .redirect_stderr (err ),self .assertRaises (SystemExit )as cm : 154server .main (["--engine" ,"mock" ,"--tokenizer" ,str (t ),"--port" ,"0" ]) 155self .assertEqual (cm .exception .code ,2 ) 156self .assertIn ("'qwen4'" ,err .getvalue ()) 157self .assertIn ("so it isn't loaded" ,err .getvalue ()) 158self .assertIn ("Strata doesn't have yet ('qwen4')" ,err .getvalue ()) 159self .assertIn ("the model's tokenizer (" ,err .getvalue ()) 160self .assertNotIn ("Traceback" ,err .getvalue ()) 161 162 163class Golden (unittest .TestCase ): 164def check (self ,cls_for_case ,cases ): 165for c in cases : 166raw = c ["input" ] 167for chunk in (len (raw ),5 ,1 ): 168for stream in (False ,True ): 169with self .subTest (case = c ["name" ],chunk = chunk ,stream_tools = stream ): 170self .assertEqual (normalised (cls_for_case ,raw ,c ["thinking" ],chunk ,stream ),c ["events" ]) 171 172def test_xml_form_through_the_class_every_shipped_template_selects (self ): 173for src in (fixture_template ("fn_unsloth_ud_q4_k_xl" ),fixture_template ("q36_ud_q4_k_xl" )): 174self .check (parser_for_template (src ),GOLDEN ["xml" ]) 175 176def test_json_form_through_the_class_a_json_template_selects (self ): 177self .check (parser_for_template (HERMES ),GOLDEN ["json" ]) 178 179def test_json_parser_reads_json_without_the_recovery_switch (self ): 180raw = GOLDEN ["json" ][0 ]["input" ] 181p = JsonOutputParser (thinking = False ,tools = GOLDEN ["tools" ],recover = False ) 182calls = [e .call for e in p .feed (raw )+ p .finish ()if e .kind == "tool_call" ] 183self .assertEqual ([(c .name ,c .arguments )for c in calls ], [("get_weather" , {"city" :"Paris" ,"days" :3 })]) 184p = OutputParser (thinking = False ,tools = GOLDEN ["tools" ],recover = False ) 185calls = [e .call for e in p .feed (raw )+ p .finish ()if e .kind == "tool_call" ] 186self .assertEqual (calls , [])# the XML parser alone leaves JSON as text, as it always did 187 188def test_xml_form_is_not_changed_by_the_json_parser_existing (self ): 189self .check (OutputParser ,GOLDEN ["xml" ]) 190 191 192if __name__ == "__main__" : 193unittest .main ()