Repository navigation
Conversation
added 6 commits
September 14, 2026 21:46
DeepSeek streaming currently serializes partial DSML parameters and slices the final serialization by the number of bytes already sent. When a malformed non-string value changes serialization shape, that stale offset drops bytes from the completed arguments. Buffer each invoke until its closing tag, validate the complete body, and emit its name and serialized arguments together. Drop incomplete invokes at stream end while preserving preamble text. Accuracy: model output is unchanged. Valid streaming calls now match non-streaming parsing; malformed outer DSML is rejected instead of becoming an executable partial call. Speed: removes repeated partial JSON parsing and serialization. Tool-call arguments are delayed until the invoke closes. Tests: python3 -m pytest -q test/registered/unit/function_call/test_deepseekv4_detector.py
Exercise valid and malformed non-string values across every chunk width, complete-item emission, multiple calls, malformed outer syntax, and end-of-stream truncation. Update existing streaming expectations to one complete item per invoke.
Validate complete arguments before creating streaming bookkeeping, preserve completed calls when a later invoke is malformed, and reject non-standard JSON constants.
Verify malformed first calls leave no flush state, malformed later calls preserve completed calls, and direct JSON rejects non-standard constants.
Use the strict JSON constant parser for XML non-string parameters too, falling back to a JSON string instead of serializing NaN or infinity.
added 6 commits
September 15, 2026 18:33
Motivation: when a closed invoke could not be parsed, the detector returned the raw DSML block as assistant content and dropped the call. Production pods logged this branch for roughly 4-6% of tool-bearing requests, so agents received tool markup as text and no tool call. Whitespace between DSML tags could also leak as content when it arrived as its own delta. Modifications: - Drop a malformed invoke on its own and keep parsing; well-formed invokes before and after it still become calls, and the prose ahead of the block is still released. - On an unexpected parser error, emit only the prose ahead of the first DSML tag; never surface DSML as content. - finish() withholds everything from the first DSML tag onward. - Hold trailing whitespace in the buffer so the blank line ahead of a block is trimmed consistently regardless of chunk boundaries. Tests: test/registered/unit/function_call/test_deepseekv4_detector.py
Motivation: the malformed-parameter check rejected any non-whitespace text between or after parameter tags, which is stricter than the previous parser and drops recoverable calls (e.g. a note the model writes after the last parameter). Reported as a regression against main. Modifications: stray prose around parameter tags is ignored again. The invoke is still rejected when the leftover text contains a DSML fragment, meaning a parameter tag that did not match (unclosed, self-closing, missing `string=`), since emitting the call without that argument would be worse than emitting no call. A body with no parameter matches and non-blank text is not the parameter format and is rejected as well. Tests: test/registered/unit/function_call/test_deepseekv4_detector.py
…al tags Motivation: xgrammar's builtin tool-call structural tags forbid the model's think tokens in free text. When --reasoning-parser is configured SGLang already passes reasoning=False so the tag only describes the post-reasoning suffix, but the exclusion still applies from the first token in non-thinking requests. DeepSeek V4 sometimes emits an empty `</think>` before prose in that mode, and the grammar rejects it. In PD disaggregation the prefill side samples that token unconstrained and decode aborts the request with a 500 (`Grammar accept_token failed ... Tokens not accepted`). Modifications: after building a structural_tag constraint, strip the configured reasoning detector's think start/end tokens from every free-text `excludes` list. Other excludes (e.g. nested tool-call markers) are kept. Tests: test/registered/unit/function_call/test_structural_tag_excludes.py
kflansburg
marked this pull request as ready for review
September 16, 2026 16:43
…start Motivation: the DeepSeek V4 reasoning detector ends the reasoning block at the first `<|DSML|`. The system prompt shows the model that tag, so its reasoning sometimes mentions `<|DSML|tool_calls>` mid-sentence; the block was cut there and the rest of the reasoning, tag included, was returned as assistant content. Observed on 3 of 40 adversarial requests in production. Modifications: add `tool_start_at_line_start` to the base detector. When set, only a tool_start_token that begins a line interrupts reasoning; the streaming path remembers the last streamed reasoning character so a tag at the head of the buffer still counts when its newline streamed earlier. DeepSeek V4 uses the full `<|DSML|tool_calls>` tag with this anchor, matching the reference parser's `\n\n<|DSML|tool_calls` split. Tests: test/registered/unit/parser/test_reasoning_parser.py
Resolve the deepseekv32_detector.py conflict with sgl-project#39665 (dsv4.1 tool parsing): keep the parameterized tag-name class attributes from main and drop partial_parameter_regex / prefix_*_end_call, whose only consumer was the allow_partial streaming path this PR removes. Also align the remaining hardcoded DSML markers with the class attributes (_text_before_dsml, leftover-fragment check, streaming marker/prefix lists), and give the deepseek-v41 reasoning parser its own tool-start anchor: V4.1's calls block uses the spaced <|DSML| calls> tag, which the unspaced V4 anchor introduced here would never interrupt.
…k V4 tool-start With tool_start_at_line_start, a tool_calls block at absolute position 0 (force_reasoning with zero preceding reasoning chars) was not detected, so the whole DSML block flushed into reasoning_content and the tool call became invisible to the downstream tool parser on both streaming and non-streaming paths.
… leak - detect_and_parse now honors the invoke completion flag, so an invoke missing its closing tag inside a closed wrapper is dropped instead of executed (matching the streaming path). - Bare invokes without the outer tool_calls wrapper are parsed in non-streaming too, instead of leaking raw DSML as content; malformed ones fail closed. - A calls-block opener truncated at EOS (line start, generation cut before '>') is stripped from the reasoning flush on both the streaming finish() and one-shot paths, for V4 and V4.1.
Collaborator
|
/rerun-failed-ci |
Collaborator
|
/rerun-failed-ci |
4 of 5 tasks
Alex-Wengg
added a commit
to Alex-Wengg/sglang
that referenced
this pull request
Oct 14, 2026
…SML parser
DeepSeekV32Detector (and the V4 / V4.1 subclasses) pass tool-call parameters
through verbatim. When the model wraps the real parameters in a spurious
top-level "arguments"/"input" key -- {"arguments": {"path": "/x"}},
{"arguments": "cmd"}, {"input": {...}}, or the XML
<parameter name="arguments" ...> form -- the wrapper reaches the client in
function.arguments, so schema-validating clients reject the call.
Unwrap it back to the tool's declared parameters:
- _unwrap_wrapped_arguments() is a no-op unless the object is exactly one
wrapper key that is not itself a declared property. It unwraps a dict value
directly, decodes a JSON-object string (the double-encoded string="true"
sub-case), and remaps a bare scalar onto the tool's sole property. Ambiguous
cases are left untouched rather than guessed.
- Applied once per complete invoke in both detect_and_parse and
parse_streaming_increment. Since sgl-project#39632 the streaming path buffers a whole
invoke before emitting, so no partial-prefix handling is needed.
Fixes sgl-project#38924
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
DeepSeek V3.2/V4 streaming tool parsing can corrupt
function.argumentswhen a partial non-string parameter changes serialization shape. The current detector emits a common prefix of provisional serializations, then slices the final serialization using the number of bytes already sent. If malformed inner JSON changes from an array/object to the raw-string fallback, the emitted bytes are no longer a prefix of the final value and the slice drops bytes from the middle.This has been observed with large nested array arguments. It can produce syntactically invalid calls without raising an exception. vLLM avoids this class of failure by buffering a complete DSML invoke before parsing and serializing it.
A second problem surfaced once complete invokes were validated: when a closed invoke could not be parsed, the detector returned the raw DSML block as assistant content and dropped the call. In production this branch fired for roughly 4-6% of tool-bearing DeepSeek V4 requests, so agents received tool markup as text with no tool call, and that markup then poisoned the following turns. The detector now fails closed instead.
Supersedes the narrower partial-value fix in #36748 and provides a conservative alternative to #36339.
Modifications
</|DSML|invoke>arrives.ToolCallItemcontaining both the name and complete arguments.finish(), or the unexpected-exception path.string=), or when the body has no parameter tags at all. In those cases emitting the call would silently drop an argument, which main did; this PR drops the call instead.<|DSML|, so a mid-sentence mention of<|DSML|tool_calls>while thinking (the system prompt shows the model that tag) cut the block and returned the rest of the reasoning, tag included, as content. Add an opt-intool_start_at_line_startto the base reasoning detector; DeepSeek V4 now interrupts only on the full<|DSML|tool_calls>tag at a line start, matching the reference parser's\n\n<|DSML|tool_callssplit. Streaming remembers the last streamed reasoning character so a tag at the head of a chunk still counts. Replaces the previously "accepted divergence" test with a chunk-invariance test. Tradeoff: a block that neither follows</think>nor starts a line stays in reasoning; that double format violation is not tolerated by the reference parser either, and a test documents it.--reasoning-parseris configured, strip the reasoning detector's think start/end tokens from the free-textexcludesof any tool-call structural tag. xgrammar's builtin tags forbid<think>/</think>in free text, but DeepSeek V4 sometimes emits an empty</think>before prose in non-thinking requests; withSGLANG_TOOL_STRICT_LEVELset the grammar rejected that token, and under PD disaggregation (prefill samples unconstrained, decode enforces) the request aborted withGrammar accept_token failed. Observed in production. Consistent with the existing rule that the reasoning parser, not xgrammar, owns the reasoning prefix.Accuracy Tests
No model output changes. Valid streaming calls are required to match non-streaming parsing. Malformed non-string values retain the existing complete-parse fallback to JSON strings. Malformed invoke structure now yields no call and no DSML rather than raw markup.
Behavior on the shapes discussed in review, for the same input at every chunk width:
<parameter name="text" string="true">SF</parameter>followed by stray proseemit({"text": "SF"})emit({"text": "SF"})<parameter name="text">SF</parameter>(missingstring=)emit({}), argument silently lost<parameter name="text" string="true">SF(unclosed)emitwith truncated, invalidarguments{"text": "SFemit({})test_reasoning_parser.pycovers the DSML mention inside reasoning (one-shot and every chunk width), a mention followed by a real block, a line-start block without</think>, and the mid-line tradeoff case.test_structural_tag_excludes.pycovers stripping only think tokens across nested free-text sections and, when xgrammar builtin tags are available, that thedeepseek_v4auto tag no longer excludes them.CPU-only parser coverage includes valid nested arrays, malformed nested values, every fixed chunk width for both valid and malformed invokes, multiple invokes, malformed first and later invokes alongside valid ones, stray prose inside the body, unmatched parameter tags, direct JSON, incomplete stream finalization, unexpected parser exceptions, and non-standard constants.
Command:
Speed Tests and Profiling
No model-forward or GPU impact. The parser removes repeated partial JSON parsing, serialization, and common-prefix scans. Tool-call arguments are intentionally delayed until the invoke closes.
Checklist
Review and Merge Process
CI States
Latest PR Test (Base): ✅ Run #35691428058
Latest PR Test (Extra): ❌ Run #35691427677
Latest PR Test (AMD ROCm 10): ❌ Run #35691427923