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
11.0 KiB256 linesraw
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."""
45    return 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
51    on_param(tool, name, is_string) is called when a parameter tag is read, before its text is returned, so the parser
52    behind it can treat a string="true" value as the string it is."""
53
54    def __init__(self, on_param=None):
55        self.buf = ""
56        self.state = "text"        # text | calls (inside the block) | invoke | param (inside a value)
57        self.tool = None
58        self.on_param = on_param
59
60    @property
61    def held(self) -> str:
62        """Text held back because it may be the start of a tag."""
63        return self.buf
64
65    def feed(self, delta: str) -> str:
66        self.buf += delta
67        return self._run(final=False)
68
69    def flush(self) -> str:
70        """The end of the output: whatever is held is text."""
71        return self._run(final=True)
72
73    # ------------------------------------------------------------------------------------------------
74    def _run(self, final: bool) -> str:
75        out: list[str] = []
76        while self.buf:
77            lt = self.buf.find("<")
78            if lt < 0:
79                self._text(self.buf, out)
80                self.buf = ""
81                break
82            if lt:
83                self._text(self.buf[:lt], out)
84                self.buf = self.buf[lt:]
85            tag = self._tag(out)
86            if tag == "wait":
87                if final:
88                    self._text(self.buf, out)
89                    self.buf = ""
90                break
91            if tag is None:                     # an ordinary '<'
92                self._text("<", out)
93                self.buf = self.buf[1:]
94        return "".join(out)
95
96    def _text(self, text: str, out: list[str]) -> None:
97        if self.state in ("calls", "invoke"):
98            if text.strip() == "":
99                return                          # the layout between tags
100            # stray text inside the block: it is shown as text, and the block goes on
101        out.append(text)
102
103    def _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
105        one) or None (it is not one)."""
106        s = self.buf
107        gt = s.find(">")
108        if gt < 0:
109            return "wait" if _could_still_be_a_tag(s) else None
110        head = s[:gt + 1]
111        if not (head.startswith(_OPEN) or head.startswith(_CLOSE)):
112            return None
113        out = outl.append
114        m = _PARAM_END.fullmatch(head)
115        if m:
116            if self.state == "param":
117                self.buf = s[gt + 1:]
118                self.state = "invoke"
119                out("\n</parameter>\n")
120                return True
121            return None
122        m = _INVOKE_END.fullmatch(head) or _CALLS_END.fullmatch(head)
123        if m:
124            closing_invoke = bool(_INVOKE_END.fullmatch(head))
125            if self.state == "param":           # the value's closing tag was left out
126                out("\n</parameter>\n")
127                self.state = "invoke"
128            if closing_invoke and self.state == "invoke":
129                self.buf = s[gt + 1:]
130                self.state = "calls"
131                out("</function>\n</tool_call>\n")
132                return True
133            if not closing_invoke and self.state in ("calls", "invoke"):
134                if self.state == "invoke":
135                    out("</function>\n</tool_call>\n")
136                self.buf = s[gt + 1:]
137                self.state = "text"
138                return True
139            return None
140        if self.state == "param":
141            return None                         # inside a value only a closing tag means anything
142        m = _CALLS.fullmatch(head)
143        if m:
144            self.buf = s[gt + 1:]
145            self.state = "calls"
146            return True
147        m = _INVOKE.fullmatch(head)
148        if m:
149            if self.state == "invoke":          # the previous call's closing tag was left out
150                out("</function>\n</tool_call>\n")
151            self.buf = s[gt + 1:]
152            self.state, self.tool = "invoke", m.group(1)
153            out(f"<tool_call>\n<function={m.group(1)}>\n")
154            return True
155        m = _PARAM.fullmatch(head)
156        if m and self.state in ("calls", "invoke"):
157            self.buf = s[gt + 1:]
158            self.state = "param"
159            if self.on_param is not None:
160                self.on_param(self.tool, m.group(1), m.group(2) != "false")
161            out(f"<parameter={m.group(1)}>\n")
162            return True
163        return 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
169    def __init__(self, *args, **kwargs):
170        super().__init__(*args, **kwargs)
171        self.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.
175        self._reasoning: list[str] = []
176        self._answered = False
177
178    def _watch(self, evs):
179        for ev in evs:
180            if ev.kind == "reasoning":
181                self._reasoning.append(ev.text)
182            elif ev.kind in ("tool_start", "tool_call") or (ev.kind == "content" and ev.text.strip()):
183                self._answered = True
184        return evs
185
186    def _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."""
188        if not is_string:
189            return
190        spec = self.schemas.get(tool)
191        if spec is None:
192            return
193        params = dict(spec.get("parameters") or {})
194        props = dict(params.get("properties") or {})
195        if (props.get(name) or {}).get("type") != "string":
196            props[name] = {**(props.get(name) or {}), "type": "string"}
197            params["properties"] = props
198            self.schemas[tool] = {**spec, "parameters": params}
199        if self.scall is not None and self.scall.name == tool:
200            self.sdeclared[name] = "string"
201
202    def feed(self, delta: str):
203        return self._watch(super().feed(self.dsml.feed(delta)))
204
205    def finish(self, reason: str | None = None):
206        rest = self.dsml.flush()
207        out = self._watch(super().feed(rest) if rest else [])
208        out += self._watch(super().finish(reason))
209        text = "".join(self._reasoning).strip()
210        if 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.
213            self._answered = True
214            out.append(Event("content", text))
215        return out
216
217    @property
218    def clean(self) -> bool:
219        """No tag is held back anywhere: a clean point to stop the thinking at."""
220        return 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).
228    Packs made from another GGUF ship the V4-Flash template (`<|DSML|tool_calls>`, no space): the model then sees one
229    spelling in the prompt and writes another, and only 2 of 11 tool-call tries came back as real calls (P2003 install
230    test; 0 of 4 vs 6 of 6 with this template on the same pack)."""
231    return " 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)."""
236    if pack_template is not None and pack_template.exists():
237        try:
238            if v41_template_ok(pack_template.read_text(encoding="utf-8")):
239                return pack_template, False
240        except OSError:
241            return pack_template, False
242        return FIXTURE_TEMPLATE, True
243    return 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)."""
248    if not force:
249        return force
250    head = _OPEN + " calls>\n"
251    marker = "<function="
252    at = force.find(marker)
253    name = force[at + len(marker):] if at >= 0 else ""
254    if name.endswith(">\n"):
255        return head + f'{_OPEN} invoke name="{name[:-2]}">\n'
256    return head + f'{_OPEN} invoke name="{name}'