Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 47 additions & 3 deletions serve/dsml.py
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,14 @@ def __init__(self, *, thinking: bool = False,
self._arg_string = True
self._arg_text = ""
self._in_param = False
# Content that may be the "\n\n<" in front of a tool-call block: held
# back until the next token says whether a block opens, so a client
# never streams text the final message drops.
self._held = ""
# Where the content after the last tool-call block begins. A stop
# string is matched only from here: text before a block is final
# once the block opens, and a match cannot span the block.
self.stop_floor = 0

@property
def finished(self) -> bool:
Expand Down Expand Up @@ -738,9 +746,15 @@ def finish(self) -> Delta:
delta = Delta()
if self._buf:
self._literal("", delta)
self._release(delta)
self._flush_call()
return delta

def drop_held(self) -> None:
"""The caller cut the content (a stop string): what is held back
comes after the cut, so it must not be released by finish()."""
self._held = ""

def openai_message(self) -> dict:
msg: dict[str, Any] = {"role": "assistant"}
msg["content"] = self.content if self.content else None
Expand All @@ -753,6 +767,8 @@ def openai_message(self) -> dict:
# ---- internals ------------------------------------------------------

def _marker(self, marker: str, delta: Delta) -> None:
if marker != DSML:
self._release(delta)
if marker == THINK_CLOSE:
self._in_think = False
return
Expand Down Expand Up @@ -792,8 +808,19 @@ def _literal(self, piece: str, delta: Delta) -> None:
self.reasoning += piece
delta.reasoning += piece
else:
self.content += piece
delta.content += piece
text = self._held + piece
keep = _lead_in_suffix(text)
self._held = text[len(text) - keep:]
out = text[:len(text) - keep]
self.content += out
delta.content += out

def _release(self, delta: Delta) -> None:
"""Send held-back content: whatever followed it was not a block."""
if self._held:
self.content += self._held
delta.content += self._held
self._held = ""

def _tag(self, delta: Delta) -> None:
"""A `|DSML|` was seen; decide what element this is once its name
Expand All @@ -808,15 +835,23 @@ def _tag(self, delta: Delta) -> None:
if not self._in_calls:
self._in_calls = True
# The two newlines before the block are prompt formatting,
# not content.
# not content. They are still held back, so they were never
# streamed; drop them there, and send anything else held.
if self._held.endswith("\n\n<"):
self._held = self._held[:-3]
elif self._held.endswith("<"):
self._held = self._held[:-1]
self._release(delta)
if self.content.endswith("\n\n<"):
self.content = self.content[:-3]
elif self.content.endswith("<"):
self.content = self.content[:-1]
self.stop_floor = len(self.content)
else:
self._in_calls = False
self._flush_call()
elif name.startswith(INVOKE_TAG.strip()):
self._release(delta)
if "name=" in head:
self._flush_call()
# `ns::name` is one namespaced tool. OpenAI has no field for
Expand Down Expand Up @@ -861,6 +896,15 @@ def _flush_call(self) -> None:
self._call = None


def _lead_in_suffix(text: str) -> int:
"""Length of the end of `text` that could still become the "\n\n<" (or
the bare "<") a tool-call block is written after."""
for lead in ("\n\n<", "\n\n", "<", "\n"):
if text.endswith(lead):
return len(lead)
return 0


def _attr(head: str, key: str) -> str:
"""The value of `key="..."` in a tag header. The header is the model's
own output, so this reads it rather than trusting it: a missing or
Expand Down
17 changes: 11 additions & 6 deletions serve/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1083,27 +1083,32 @@ def _run(self, slot, prompt, opts, stops, parser, on_delta):
stops = [s for s in stops if s]
state = {"n": 0, "stopped": False, "content_sent": 0}

def stop_at(text):
hits = [p for s in stops if (p := text.find(s)) >= 0]
def stop_at(text, floor):
hits = [p for s in stops if (p := text.find(s, floor)) >= 0]
return min(hits) if hits else None

def safe_content_end(text):
def safe_content_end(text, floor):
"""Exclude a suffix that may become a stop on the next token."""
end = len(text)
for s in stops:
limit = min(len(s) - 1, len(text))
limit = min(len(s) - 1, len(text) - floor)
for n in range(limit, 0, -1):
if text.endswith(s[:n]):
end = min(end, len(text) - n)
break
return end

def deliver(delta, *, final=False):
hit = stop_at(parser.content)
# A parser may mark where its content restarts after a tool-call
# block (DSML): a stop string is not matched across the block.
floor = getattr(parser, "stop_floor", 0)
hit = stop_at(parser.content, floor)
if hit is not None:
parser.content = parser.content[:hit]
# Text a parser still holds back follows the cut (DSML).
getattr(parser, "drop_held", lambda: None)()
end = len(parser.content) if final or hit is not None else safe_content_end(
parser.content)
parser.content, floor)
sent = state["content_sent"]
delta.content = parser.content[sent:end] if end >= sent else ""
state["content_sent"] = end
Expand Down
77 changes: 77 additions & 0 deletions tests/serve/test_dsml.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,5 +287,82 @@ def test_openai_message(self):
self.assertEqual(msg["reasoning_content"], "why")


def stream(text, thinking=False):
"""drive(), keeping the content deltas a streaming client would receive."""
p = dsml.DSMLParser(thinking=thinking, markers=ID_MARKER)
streamed = []
i = 0
while i < len(text):
hit, at = None, len(text)
for m in dsml.MARKERS:
q = text.find(m, i)
if q != -1 and q < at:
at, hit = q, m
for ch in text[i:at]:
streamed.append(p.feed_token(-1, ch).content)
if hit is None:
break
streamed.append(p.feed_token(MARKER_ID[hit], hit).content)
i = at + len(hit)
streamed.append(p.finish().content)
return p, "".join(streamed)


class TestStreamedContent(unittest.TestCase):
"""The content a client streams is the content of the final message."""

def test_the_lead_in_to_a_tool_call_block_is_not_streamed(self):
d = dsml.DSML
call = (f"<{d} calls>\n<{d} invoke name=\"get\">\n"
f"<{d} parameter name=\"city\" string=\"true\">Rome</{d} parameter>\n"
f"</{d} invoke>\n</{d} calls>")
for lead in ("Let me check.\n\n", "Let me check.", ""):
with self.subTest(lead=lead):
p, streamed = stream(lead + call + dsml.EOS)
self.assertEqual(p.content, lead.rstrip("\n") if lead.endswith("\n\n") else lead)
self.assertEqual(streamed, p.content)
self.assertEqual(len(p.tool_calls), 1)

def test_text_that_only_looks_like_a_lead_in_is_streamed(self):
for text in ("a\n\nb", "x < y", "x <\n\ny", "ends with a newline\n",
"ends with two\n\n", "ends with <"):
for end in (dsml.EOS, ""):
with self.subTest(text=text, eos=bool(end)):
p, streamed = stream(text + end)
self.assertEqual(p.content, text)
self.assertEqual(streamed, text)

def test_a_cut_content_does_not_get_held_text_back(self):
"""server.py cuts the content at a stop string. A token that ends
the stop and starts a lead-in ("P\\n") leaves "\\n" held, after the
cut; finish() must not put it back."""
p = dsml.DSMLParser(markers=ID_MARKER)
for piece in ("abc STO", "P\n"):
p.feed_token(-1, piece)
self.assertEqual(p.content, "abc STOP")
p.content = p.content[:p.content.find("STOP")]
p.drop_held()
p.finish()
self.assertEqual(p.content, "abc ")

def test_the_stop_floor_moves_past_each_tool_call_block(self):
"""server.py matches a stop string only from stop_floor, so text
before a block is final once the block opens."""
d = dsml.DSML
call = (f"<{d} calls>\n<{d} invoke name=\"get\">\n</{d} invoke>\n"
f"</{d} calls>")
p, _ = stream("Let me check.\n\n" + dsml.EOS)
self.assertEqual(p.stop_floor, 0)
p, _ = stream("Let me check.\n\n" + call + "\nmore\n\n" + call + dsml.EOS)
self.assertEqual(p.content, "Let me check.\nmore")
self.assertEqual(p.stop_floor, len(p.content))
self.assertEqual(len(p.tool_calls), 2)

def test_reasoning_is_streamed_as_it_arrives(self):
p, _ = stream("why\n\n</think>because" + dsml.EOS, thinking=True)
self.assertEqual(p.reasoning, "why\n\n")
self.assertEqual(p.content, "because")


if __name__ == "__main__":
unittest.main()
90 changes: 90 additions & 0 deletions tests/serve/test_dsml_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""
test_dsml_server.py — a DeepSeek-V4.1 (DSML) container through the HTTP server.

A streamed reply and the same reply asked for whole must say the same thing:
the text a client streams is the content of the final message.
"""

import sys
import unittest
from pathlib import Path

REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO))

from serve import dsml # noqa: E402
from tests.serve.test_server import ServerTestCase # noqa: E402

D = dsml.DSML
CALL = (f"<{D} calls>\n<{D} invoke name=\"get\">\n"
f"<{D} parameter name=\"city\" string=\"true\">Rome</{D} parameter>\n"
f"</{D} invoke>\n</{D} calls>")
TOOLS = [{"type": "function", "function": {
"name": "get", "parameters": {"type": "object",
"properties": {"city": {"type": "string"}}}}}]


class TestDSMLStreaming(ServerTestCase):
engine_kwargs = {"no_markers": True,
"markers": {100 + i: m for i, m in enumerate(dsml.MARKERS)}}

def streamed_content(self, **body):
events = self.stream(**body)
return "".join(e["choices"][0]["delta"].get("content") or ""
for e in events if e != "[DONE]" and e.get("choices"))

def test_the_lead_in_to_a_tool_call_is_not_streamed(self):
self.engine.reply = "</think>Let me check.\n\n" + CALL + dsml.EOS
_, body = self.chat(tools=TOOLS)
message = body["choices"][0]["message"]
self.assertEqual(message["content"], "Let me check.")
self.assertEqual(message["tool_calls"][0]["function"]["name"], "get")
self.assertEqual(self.streamed_content(tools=TOOLS), "Let me check.")

def test_text_ending_in_newlines_is_delivered_whole(self):
self.engine.reply = "</think>a\n\nb\n\n" + dsml.EOS
_, body = self.chat()
self.assertEqual(body["choices"][0]["message"]["content"], "a\n\nb\n\n")
self.assertEqual(self.streamed_content(), "a\n\nb\n\n")

def test_a_stop_string_cuts_text_still_held_back(self):
self.engine.reply = "</think>abc STOP\nmore" + dsml.EOS
_, body = self.chat(stop="STOP")
self.assertEqual(body["choices"][0]["message"]["content"], "abc ")
self.assertEqual(self.streamed_content(stop="STOP"), "abc ")

def test_a_stop_string_does_not_match_the_lead_in_to_a_tool_call(self):
# The "\n\n<" before a block is formatting, not content, so a stop
# string cannot end the reply there and lose the call. A stop inside
# the content still cuts it.
self.engine.reply = "</think>Let me check.\n\n" + CALL + dsml.EOS
for stop in ("\n", "<"):
with self.subTest(stop=stop):
_, body = self.chat(tools=TOOLS, stop=stop)
choice = body["choices"][0]
self.assertEqual(choice["finish_reason"], "tool_calls")
self.assertEqual(choice["message"]["content"], "Let me check.")
self.assertEqual(
choice["message"]["tool_calls"][0]["function"]["name"], "get")
self.assertEqual(
self.streamed_content(tools=TOOLS, stop=stop), "Let me check.")

self.engine.reply = "</think>one\ntwo\n\n" + CALL + dsml.EOS
_, body = self.chat(tools=TOOLS, stop="\n")
self.assertEqual(body["choices"][0]["message"]["content"], "one")
self.assertNotIn("tool_calls", body["choices"][0]["message"])
self.assertEqual(self.streamed_content(tools=TOOLS, stop="\n"), "one")

def test_a_stop_string_does_not_match_across_a_tool_call(self):
self.engine.reply = ("</think>Let me check." + CALL + "\nmore"
+ dsml.EOS)
_, body = self.chat(tools=TOOLS, stop="check.\n")
message = body["choices"][0]["message"]
self.assertEqual(message["content"], "Let me check.\nmore")
self.assertEqual(message["tool_calls"][0]["function"]["name"], "get")
self.assertEqual(self.streamed_content(tools=TOOLS, stop="check.\n"),
"Let me check.\nmore")


if __name__ == "__main__":
unittest.main()