Skip to content

Commit 82844df

Browse files
authored
[None][fix] DeepSeek DSML tool parsers: the layout newlines around tool calls are not content (#20873)
Signed-off-by: JunyiXu-nv <219237550+JunyiXu-nv@users.noreply.github.com>
1 parent 55649d1 commit 82844df

2 files changed

Lines changed: 242 additions & 3 deletions

File tree

‎tensorrt_llm/serve/tool_parser/deepseekv32_parser.py‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ class DeepSeekV32Parser(BaseToolParser):
6565

6666
_eos_token = "<|end▁of▁sentence|>" # nosec B105
6767

68+
# The encoders write a blank line between a reply's content and its tool-call
69+
# block: it belongs to the format, not to the content.
70+
_CALLS_SEPARATOR = "\n\n"
71+
6872
# Invoke header up to the function name, which is arbitrary text.
6973
_INVOKE_HEADER_PREFIX = '<|DSML|invoke name="' # nosec B105
7074
_INVOKE_BEGIN_TEMPLATE = '<|DSML|invoke name="{name}">' # nosec B105
@@ -80,6 +84,12 @@ def __init__(self):
8084
)
8185
self._last_arguments = ""
8286
self.current_tool_id = -1
87+
# Between a block's opening and closing tags, the newlines that separate
88+
# the invokes and precede the closing tag are the format's layout (the
89+
# checkpoint's encoder writes them), not content.
90+
self._in_calls_block = False
91+
# Set while an increment re-reads what its last invoke left behind.
92+
self._reading_rest = False
8393

8494
def has_tool_call(self, text: str) -> bool:
8595
"""Check if the text contains a deepseek v32 format tool call."""
@@ -132,7 +142,7 @@ def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult
132142
if self._eos_token in text:
133143
text = text.replace(self._eos_token, "")
134144
idx = text.find(self.bot_token)
135-
normal_text = text[:idx].strip() if idx != -1 else text
145+
normal_text = text[:idx].removesuffix(self._CALLS_SEPARATOR) if idx != -1 else text
136146
if self.bot_token not in text:
137147
return StreamingParseResult(normal_text=normal_text, calls=[])
138148

@@ -166,6 +176,27 @@ def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult
166176
# return the normal text if parsing fails
167177
return StreamingParseResult(normal_text=text)
168178

179+
def _separator_prefix_at_end(self, text: str) -> str:
180+
"""The tail of ``text`` that could still begin the blank line before a calls block."""
181+
for size in range(len(self._CALLS_SEPARATOR), 0, -1):
182+
if text.endswith(self._CALLS_SEPARATOR[:size]):
183+
return text[-size:]
184+
return ""
185+
186+
def finish(self, tools: List[Tool]) -> StreamingParseResult:
187+
"""Emit, as content, what the stream ended while holding back.
188+
189+
That is a trailing blank line no tool-call block followed, or a tail that
190+
never completed into a delimiter. Inside an unfinished calls block nothing
191+
is emitted.
192+
"""
193+
if self._in_calls_block:
194+
return StreamingParseResult()
195+
held, self._buffer = self._buffer, ""
196+
for e_token in [self.eot_token, self.invoke_end_token, self._eos_token]:
197+
held = held.replace(e_token, "")
198+
return StreamingParseResult(normal_text=held)
199+
169200
def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> StreamingParseResult:
170201
"""Streaming incremental parsing tool calls for DeepSeekV32 format.
171202
@@ -191,9 +222,28 @@ def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> Streami
191222
self._ends_with_partial_token(current_text, token) for token in partial_tokens
192223
)
193224

225+
if self._in_calls_block and not has_tool_call:
226+
closing = current_text.find(self.eot_token)
227+
layout = current_text if closing == -1 else current_text[:closing]
228+
if not layout.strip():
229+
if closing == -1:
230+
# Still layout until the next invoke or the closing tag.
231+
return StreamingParseResult()
232+
self._in_calls_block = False
233+
current_text = current_text[closing + len(self.eot_token) :]
234+
self._buffer = current_text
235+
ends_with_partial_token = any(
236+
self._ends_with_partial_token(current_text, token) for token in partial_tokens
237+
)
238+
194239
if not has_tool_call and not ends_with_partial_token:
195240
normal_text = current_text
196-
self._buffer = ""
241+
# Trailing newlines may begin the blank line before a tool-call block,
242+
# which is not content: hold them until the next increment, or
243+
# finish(), shows what follows.
244+
held = "" if self._in_calls_block else self._separator_prefix_at_end(normal_text)
245+
self._buffer = held
246+
normal_text = normal_text[: len(normal_text) - len(held)]
197247
for e_token in [self.eot_token, self.invoke_end_token, self._eos_token]:
198248
normal_text = normal_text.replace(e_token, "")
199249
return StreamingParseResult(normal_text=normal_text)
@@ -205,11 +255,19 @@ def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> Streami
205255
if normal_text:
206256
current_text = current_text[prefix_len:]
207257
self._buffer = current_text
258+
if has_tool_call:
259+
if self._in_calls_block and not normal_text.strip():
260+
# The separator before the next invoke.
261+
normal_text = ""
262+
elif not self._in_calls_block and current_text.startswith(self.bot_token):
263+
normal_text = normal_text.removesuffix(self._CALLS_SEPARATOR)
264+
self._in_calls_block = True
208265

209266
if not hasattr(self, "_tool_indices"):
210267
self._tool_indices = self._get_tool_indices(tools)
211268

212269
all_calls: list[ToolCallItem] = []
270+
invokes_exhausted = False
213271
try:
214272
# Loop to handle multiple consecutive invoke blocks
215273
while True:
@@ -226,6 +284,7 @@ def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> Streami
226284
)
227285

228286
if not invoke_match:
287+
invokes_exhausted = True
229288
break
230289

231290
func_name = invoke_match.group(1).strip()
@@ -310,7 +369,23 @@ def parse_streaming_increment(self, new_text: str, tools: List[Tool]) -> Streami
310369
# Wait for more chunks until we see </|DSML|invoke>
311370
break
312371

313-
# No more invoke blocks found
372+
# The rest of this increment may close the block and carry text after
373+
# it. Read it now: a later increment may never come, and nothing
374+
# flushes this parser when the stream ends.
375+
if (
376+
invokes_exhausted
377+
and self._in_calls_block
378+
and not self._reading_rest
379+
and self.eot_token in self._buffer
380+
and not any(token in self._buffer for token in start_tokens)
381+
):
382+
self._reading_rest = True
383+
try:
384+
rest = self.parse_streaming_increment("", tools)
385+
finally:
386+
self._reading_rest = False
387+
normal_text += rest.normal_text
388+
all_calls.extend(rest.calls)
314389
return StreamingParseResult(normal_text=normal_text, calls=all_calls)
315390

316391
except Exception as e:

‎tests/unittest/llmapi/apps/test_tool_parsers.py‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7399,3 +7399,167 @@ def test_parse_base_json_reports_the_name_as_emitted(sample_tools):
73997399

74007400
assert [(c.name, c.tool_index)
74017401
for c in calls] == [("functions.get_weather", -1)]
7402+
7403+
7404+
# ============================================================================
7405+
# DeepSeek DSML layout: the newlines inside a tool-call block are not content
7406+
# ============================================================================
7407+
7408+
_DSML_FORMATS = [
7409+
(DeepSeekV32Parser, "function_calls", "invoke", "parameter"),
7410+
(DeepSeekV4Parser, "tool_calls", "invoke", "parameter"),
7411+
(DeepSeekV41Parser, " calls", " invoke", " parameter"),
7412+
]
7413+
7414+
7415+
def _dsml_block(calls_tag: str, invoke_tag: str, parameter_tag: str) -> str:
7416+
"""Two calls laid out as the checkpoint encoders write them: one per line."""
7417+
dsml = "|DSML|"
7418+
7419+
def invoke(name: str, key: str, value: str) -> str:
7420+
return (f'<{dsml}{invoke_tag} name="{name}">\n'
7421+
f'<{dsml}{parameter_tag} name="{key}" string="true">{value}'
7422+
f"</{dsml}{parameter_tag}>\n"
7423+
f"</{dsml}{invoke_tag}>")
7424+
7425+
return (f"<{dsml}{calls_tag}>\n" +
7426+
invoke("get_weather", "location", "NYC") + "\n" +
7427+
invoke("search_web", "query", "AI") + "\n" +
7428+
f"</{dsml}{calls_tag}>")
7429+
7430+
7431+
def _stream(parser,
7432+
text: str,
7433+
chunk_size: int,
7434+
tools: list[ChatCompletionToolsParam],
7435+
*,
7436+
finish: bool = True):
7437+
results = [
7438+
parser.parse_streaming_increment(text[i:i + chunk_size], tools)
7439+
for i in range(0, len(text), chunk_size)
7440+
]
7441+
if finish:
7442+
results.append(parser.finish(tools))
7443+
content = "".join(result.normal_text for result in results)
7444+
calls = [call for result in results for call in result.calls]
7445+
return content, calls
7446+
7447+
7448+
@pytest.mark.parametrize("parser_cls, calls_tag, invoke_tag, parameter_tag",
7449+
_DSML_FORMATS)
7450+
@pytest.mark.parametrize("chunk_size", [1, 3, 7, 10_000])
7451+
def test_dsml_newlines_between_calls_are_not_content(
7452+
sample_tools: list[ChatCompletionToolsParam],
7453+
parser_cls: type[BaseToolParser], calls_tag: str, invoke_tag: str,
7454+
parameter_tag: str, chunk_size: int) -> None:
7455+
"""The newline after each invoke is the block's layout, however it is chunked.
7456+
7457+
Streamed as text, it became content after every tool call: over Anthropic
7458+
Messages, a whitespace-only text block followed each tool_use, and a client
7459+
that drops such blocks sent back a turn that no longer matched what was
7460+
served.
7461+
"""
7462+
text = "Let me check.\n\n" + _dsml_block(calls_tag, invoke_tag,
7463+
parameter_tag)
7464+
7465+
content, calls = _stream(parser_cls(), text, chunk_size, sample_tools)
7466+
7467+
assert content == "Let me check."
7468+
assert [call.name for call in calls
7469+
if call.name] == ["get_weather", "search_web"]
7470+
arguments = [
7471+
json.loads(call.parameters) for call in calls
7472+
if not call.name and call.parameters
7473+
]
7474+
assert arguments == [{"location": "NYC"}, {"query": "AI"}]
7475+
7476+
7477+
@pytest.mark.parametrize("parser_cls, calls_tag, invoke_tag, parameter_tag",
7478+
_DSML_FORMATS)
7479+
@pytest.mark.parametrize("chunk_size", [5, 10_000])
7480+
def test_dsml_text_after_the_block_is_still_content(
7481+
sample_tools: list[ChatCompletionToolsParam],
7482+
parser_cls: type[BaseToolParser], calls_tag: str, invoke_tag: str,
7483+
parameter_tag: str, chunk_size: int) -> None:
7484+
"""Only the layout inside the block is dropped; text after it is kept.
7485+
7486+
In one increment, the closing tag and the text after it follow the last
7487+
invoke; that text must come out of that increment.
7488+
"""
7489+
text = _dsml_block(calls_tag, invoke_tag, parameter_tag) + " Done."
7490+
7491+
parser = parser_cls()
7492+
content, calls = _stream(parser,
7493+
text,
7494+
chunk_size,
7495+
sample_tools,
7496+
finish=False)
7497+
7498+
assert content == " Done."
7499+
finish_result = parser.finish(sample_tools)
7500+
assert finish_result.normal_text == ""
7501+
assert finish_result.calls == []
7502+
assert [call.name for call in calls
7503+
if call.name] == ["get_weather", "search_web"]
7504+
7505+
7506+
@pytest.mark.parametrize("parser_cls, calls_tag, invoke_tag, parameter_tag",
7507+
_DSML_FORMATS)
7508+
@pytest.mark.parametrize("chunk_size", [1, 2, 3, 7, 10_000])
7509+
def test_dsml_blank_line_before_the_block_is_not_content(
7510+
sample_tools: list[ChatCompletionToolsParam],
7511+
parser_cls: type[BaseToolParser], calls_tag: str, invoke_tag: str,
7512+
parameter_tag: str, chunk_size: int) -> None:
7513+
"""The encoders write a blank line between the content and the block.
7514+
7515+
The content keeps its own whitespace; only that blank line is dropped, on
7516+
both paths.
7517+
"""
7518+
content_in = " Indented first line.\nLast line.\n"
7519+
text = content_in + "\n\n" + _dsml_block(calls_tag, invoke_tag,
7520+
parameter_tag)
7521+
7522+
content, calls = _stream(parser_cls(), text, chunk_size, sample_tools)
7523+
7524+
assert content == content_in
7525+
assert parser_cls().detect_and_parse(text,
7526+
sample_tools).normal_text == content_in
7527+
assert [call.name for call in calls
7528+
if call.name] == ["get_weather", "search_web"]
7529+
7530+
7531+
@pytest.mark.parametrize("parser_cls, calls_tag, invoke_tag, parameter_tag",
7532+
_DSML_FORMATS)
7533+
@pytest.mark.parametrize("chunk_size", [1, 3, 10_000])
7534+
def test_dsml_trailing_blank_lines_without_a_block_are_content(
7535+
sample_tools: list[ChatCompletionToolsParam],
7536+
parser_cls: type[BaseToolParser], calls_tag: str, invoke_tag: str,
7537+
parameter_tag: str, chunk_size: int) -> None:
7538+
"""Newlines held back in case a block follows come out when none does."""
7539+
text = "Done.\n\n"
7540+
7541+
content, calls = _stream(parser_cls(), text, chunk_size, sample_tools)
7542+
7543+
assert content == text
7544+
assert calls == []
7545+
7546+
7547+
@pytest.mark.parametrize("parser_cls, calls_tag, invoke_tag, parameter_tag",
7548+
_DSML_FORMATS)
7549+
@pytest.mark.parametrize("chunk_size", [1, 3, 10_000])
7550+
def test_dsml_stream_cut_inside_the_block_keeps_only_the_content(
7551+
sample_tools: list[ChatCompletionToolsParam],
7552+
parser_cls: type[BaseToolParser], calls_tag: str, invoke_tag: str,
7553+
parameter_tag: str, chunk_size: int) -> None:
7554+
"""A stream cut short inside the block ends with its content.
7555+
7556+
The non-streaming path reads the same text the same way.
7557+
"""
7558+
block = _dsml_block(calls_tag, invoke_tag, parameter_tag)
7559+
text = "Checking.\n\n" + block[:block.index("</|DSML|")]
7560+
7561+
content, _ = _stream(parser_cls(), text, chunk_size, sample_tools)
7562+
7563+
assert content == "Checking."
7564+
assert parser_cls().detect_and_parse(text,
7565+
sample_tools).normal_text == content

0 commit comments

Comments
 (0)