okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""serve/dsml.py - DeepSeek-V4.1's tool-call text (DSML) for the server. 2 3DeepSeek-V4.1 writes a tool call as (the model's own chat template, the same bytes as DeepSeek's encoding.py) 4 5<|DSML| calls> 6<|DSML| invoke name="get_weather"> 7<|DSML| parameter name="city" string="true">Zagreb</|DSML| parameter> 8<|DSML| parameter name="days" string="false">3</|DSML| parameter> 9</|DSML| invoke> 10</|DSML| calls> 11 12`|DSML|` is one token (id 128825, a user-defined one, so it is also text when a request is tokenized). String 13values are written as they are; every other type is JSON (string="false"). 14 15The server's OutputParser (serve/frontend.py) reads the Qwen form `<tool_call><function=NAME><parameter=P>...`, with 16its streaming of tool arguments, its calls inside the thinking and its recovery rules. DsmlTranslator rewrites the 17DSML text into that form as it streams (holding back only a tag that is still arriving), and DsmlOutputParser is the 18OutputParser behind it. So the OpenAI and Anthropic paths, tool_choice, streaming arguments and the thinking/answer 19split behave for DeepSeek as they do for the other families, and there is one place that knows the DSML spelling. 20""" 21from __future__import annotations 22 23import re 24from pathlib import Path 25 26from serve .frontend import Event ,OutputParser 27 28DSML = "|DSML|" 29_OPEN = "<" + DSML 30_CLOSE = "</" + DSML 31_TAG_MAX = 600 # a tag (a tool name, a parameter name) longer than this is text, not held any further 32 33_CALLS = re .compile (r"<|DSML|\s*(?:tool_|function_)?calls\s*>" ) 34_CALLS_END = re .compile (r"</|DSML|\s*(?:tool_|function_)?calls\s*>" ) 35_INVOKE = re .compile (r'<|DSML|\s*invoke\s+name\s*=\s*"([^"]*)"\s*>' ) 36_INVOKE_END = re .compile (r"</|DSML|\s*invoke\s*>" ) 37_PARAM = re .compile (r'<|DSML|\s*parameter\s+name\s*=\s*"([^"]*)"(?:\s+string\s*=\s*"(true|false)")?\s*>' ) 38_PARAM_END = re .compile (r"</|DSML|\s*parameter\s*>" ) 39# a tag cut short is held while it can still become one of those: "<", "<|DS", '<|DSML| invoke name="get_we' 40_PARTIAL = re .compile (r"^</?(?:|(?:D(?:S(?:M(?:L(?:|[^<>]*)?)?)?)?)?)?$" ) 41 42 43def _could_still_be_a_tag (s :str )-> bool : 44"""`s` starts with '<' and has no '>' yet: it may be the start of a DSML tag.""" 45return len (s )<= _TAG_MAX and _PARTIAL .match (s )is not None 46 47 48class DsmlTranslator : 49"""DSML text -> the Qwen tool-call text, a delta at a time. Text outside a call passes through unchanged. 50 51on_param(tool, name, is_string) is called when a parameter tag is read, before its text is returned, so the parser 52behind it can treat a string="true" value as the string it is.""" 53 54def __init__ (self ,on_param = None ): 55self .buf = "" 56self .state = "text" # text | calls (inside the block) | invoke | param (inside a value) 57self .tool = None 58self .on_param = on_param 59 60@property 61def held (self )-> str : 62"""Text held back because it may be the start of a tag.""" 63return self .buf 64 65def feed (self ,delta :str )-> str : 66self .buf += delta 67return self ._run (final = False ) 68 69def flush (self )-> str : 70"""The end of the output: whatever is held is text.""" 71return self ._run (final = True ) 72 73# ------------------------------------------------------------------------------------------------ 74def _run (self ,final :bool )-> str : 75out :list [str ]= [] 76while self .buf : 77lt = self .buf .find ("<" ) 78if lt < 0 : 79self ._text (self .buf ,out ) 80self .buf = "" 81break 82if lt : 83self ._text (self .buf [:lt ],out ) 84self .buf = self .buf [lt :] 85tag = self ._tag (out ) 86if tag == "wait" : 87if final : 88self ._text (self .buf ,out ) 89self .buf = "" 90break 91if tag is None :# an ordinary '<' 92self ._text ("<" ,out ) 93self .buf = self .buf [1 :] 94return "" .join (out ) 95 96def _text (self ,text :str ,out :list [str ])-> None : 97if self .state in ("calls" ,"invoke" ): 98if text .strip ()== "" : 99return # the layout between tags 100# stray text inside the block: it is shown as text, and the block goes on 101out .append (text ) 102 103def _tag (self ,outl :list [str ]): 104"""Handle the tag at the start of self.buf. Returns True (a tag was consumed), "wait" (it may still become 105one) or None (it is not one).""" 106s = self .buf 107gt = s .find (">" ) 108if gt < 0 : 109return "wait" if _could_still_be_a_tag (s )else None 110head = s [:gt + 1 ] 111if not (head .startswith (_OPEN )or head .startswith (_CLOSE )): 112return None 113out = outl .append 114m = _PARAM_END .fullmatch (head ) 115if m : 116if self .state == "param" : 117self .buf = s [gt + 1 :] 118self .state = "invoke" 119out ("\n</parameter>\n" ) 120return True 121return None 122m = _INVOKE_END .fullmatch (head )or _CALLS_END .fullmatch (head ) 123if m : 124closing_invoke = bool (_INVOKE_END .fullmatch (head )) 125if self .state == "param" :# the value's closing tag was left out 126out ("\n</parameter>\n" ) 127self .state = "invoke" 128if closing_invoke and self .state == "invoke" : 129self .buf = s [gt + 1 :] 130self .state = "calls" 131out ("</function>\n</tool_call>\n" ) 132return True 133if not closing_invoke and self .state in ("calls" ,"invoke" ): 134if self .state == "invoke" : 135out ("</function>\n</tool_call>\n" ) 136self .buf = s [gt + 1 :] 137self .state = "text" 138return True 139return None 140if self .state == "param" : 141return None # inside a value only a closing tag means anything 142m = _CALLS .fullmatch (head ) 143if m : 144self .buf = s [gt + 1 :] 145self .state = "calls" 146return True 147m = _INVOKE .fullmatch (head ) 148if m : 149if self .state == "invoke" :# the previous call's closing tag was left out 150out ("</function>\n</tool_call>\n" ) 151self .buf = s [gt + 1 :] 152self .state ,self .tool = "invoke" ,m .group (1 ) 153out (f"<tool_call>\n<function= { m . group ( 1 ) } >\n" ) 154return True 155m = _PARAM .fullmatch (head ) 156if m and self .state in ("calls" ,"invoke" ): 157self .buf = s [gt + 1 :] 158self .state = "param" 159if self .on_param is not None : 160self .on_param (self .tool ,m .group (1 ),m .group (2 )!= "false" ) 161out (f"<parameter= { m . group ( 1 ) } >\n" ) 162return True 163return None 164 165 166class DsmlOutputParser (OutputParser ): 167"""OutputParser for DeepSeek-V4.1: the model's DSML calls are read as the template-form calls they are.""" 168 169def __init__ (self ,* args ,** kwargs ): 170super ().__init__ (* args ,** kwargs ) 171self .dsml = DsmlTranslator (self ._on_param ) 172# The 2-bit sets often write the whole answer after <think> and stop (EOS) without </think>: everything would be reasoning and 173# the reply empty (P2003 install test, 4 of 4 prompts). The reasoning text is kept here; finish() hands it over as the answer 174# when the turn ended on a stop with no answer and no call. 175self ._reasoning :list [str ]= [] 176self ._answered = False 177 178def _watch (self ,evs ): 179for ev in evs : 180if ev .kind == "reasoning" : 181self ._reasoning .append (ev .text ) 182elif ev .kind in ("tool_start" ,"tool_call" )or (ev .kind == "content" and ev .text .strip ()): 183self ._answered = True 184return evs 185 186def _on_param (self ,tool ,name ,is_string )-> None : 187"""string="true": the value is a string whatever it looks like ("123", "true"), as the template wrote it.""" 188if not is_string : 189return 190spec = self .schemas .get (tool ) 191if spec is None : 192return 193params = dict (spec .get ("parameters" )or {}) 194props = dict (params .get ("properties" )or {}) 195if (props .get (name )or {}).get ("type" )!= "string" : 196props [name ]= {** (props .get (name )or {}),"type" :"string" } 197params ["properties" ]= props 198self .schemas [tool ]= {** spec ,"parameters" :params } 199if self .scall is not None and self .scall .name == tool : 200self .sdeclared [name ]= "string" 201 202def feed (self ,delta :str ): 203return self ._watch (super ().feed (self .dsml .feed (delta ))) 204 205def finish (self ,reason :str | None = None ): 206rest = self .dsml .flush () 207out = self ._watch (super ().feed (rest )if rest else []) 208out += self ._watch (super ().finish (reason )) 209text = "" .join (self ._reasoning ).strip () 210if reason in (None ,"stop" )and text and not self ._answered : 211# no </think> and no answer: the text IS the answer. A streaming client has already seen it as reasoning and now gets 212# it as content; the non-streaming collectors (server.py) drop the identical reasoning. 213self ._answered = True 214out .append (Event ("content" ,text )) 215return out 216 217@property 218def clean (self )-> bool : 219"""No tag is held back anywhere: a clean point to stop the thinking at.""" 220return not self .buf and not self .dsml .held 221 222 223FIXTURE_TEMPLATE = Path (__file__ ).resolve ().parent / "fixtures" / "deepseek41" / "chat_template.jinja" 224 225 226def v41_template_ok (text :str )-> bool : 227"""The V4.1 model writes its call block as `<|DSML| calls>` / `<|DSML| invoke ...` (a space after the DSML token). 228Packs made from another GGUF ship the V4-Flash template (`<|DSML|tool_calls>`, no space): the model then sees one 229spelling in the prompt and writes another, and only 2 of 11 tool-call tries came back as real calls (P2003 install 230test; 0 of 4 vs 6 of 6 with this template on the same pack).""" 231return " calls>" in text 232 233 234def pick_template (pack_template :Path | None )-> tuple [Path ,bool ]: 235"""(the template file to render with, True when it replaced a pack template that spells the call block otherwise).""" 236if pack_template is not None and pack_template .exists (): 237try : 238if v41_template_ok (pack_template .read_text (encoding = "utf-8" )): 239return pack_template ,False 240except OSError : 241return pack_template ,False 242return FIXTURE_TEMPLATE ,True 243return FIXTURE_TEMPLATE ,False 244 245 246def to_dsml_force (force :str | None )-> str | None : 247"""forced_call's opening of a call in the Qwen form -> the same opening in DSML (the model's own spelling).""" 248if not force : 249return force 250head = _OPEN + " calls>\n" 251marker = "<function=" 252at = force .find (marker ) 253name = force [at + len (marker ):]if at >= 0 else "" 254if name .endswith (">\n" ): 255return head + f' { _OPEN } invoke name=" { name [: - 2 ] } ">\n' 256return head + f' { _OPEN } invoke name=" { name } '