Repository navigation
[Tool Call] Fix DeepSeekV32Detector streaming corrupting tool-call arguments - #36339
Xiang-Wang-Panda wants to merge 1 commit into
Conversation
…guments parse_streaming_increment() rebuilds the whole arguments string on every chunk and emits common_prefix(current, previous)[sent_len:], then current_params[sent_len:] once the closing tag arrives. That is only sound if every byte already emitted is still a prefix of the finished serialisation, and it is not: a non-string parameter serialises as a structure while _partial_json_loads succeeds and as a quote-escaped JSON string when it falls back to value.strip(). The two shapes diverge from the first byte of the value and have different lengths, so when the fallback fires at a different moment than it did on the previous chunk, sent_len no longer indexes the same string and the closing-tag slice starts too far in — dropping a run of bytes out of the middle and handing the client invalid JSON. Measured on DeepSeek-V4 with --tool-call-parser deepseekv4 (which inherits this detector) over 433 calls: 0/80 malformed with stream=false, 4/80 with stream=true, and 13.8% on the one tool whose arguments are a nested array. Pinning tool_choice does not help, because the arguments string is built here rather than generated by the model. Stop emitting bytes that can still change. _streamable_prefix() returns the longest prefix of the final arguments JSON that is settled: parameters whose closing tag has arrived, plus the in-flight one only when it is a string type, whose serialisation grows by appending because json.dumps escapes character by character. Non-string parameters are held until their tag closes. The emit is then guarded by current.startswith(sent), which logs instead of corrupting the payload if the invariant is ever broken again. Argument streaming is preserved for string parameters, so this does not reintroduce sgl-project#11888. Also replaces the two rstrip() tail trims: str.rstrip takes a character set, not a suffix, so rstrip("oke") ate any trailing run of "o", "k" and "e" — a parameter value ending in "note" came back as "not". _strip_partial_tag_suffix() matches a real prefix of the closing tag, and runs before whitespace is stripped, because the other order lets the tag's leading "<" shield whitespace that is then streamed and later vanishes. Tests: 970 subtests over 5 fixtures x 9 chunk boundary sets assert that streamed arguments parse and equal the non-streaming result, and that at every truncation point the bytes streamed so far are a prefix of what the finished stream produces. 480 of them fail before this change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Xiang-Wang-Panda
left a comment
There was a problem hiding this comment.
@JustinTong0323 CODEOWNERS for srt/function_call — tagging you for review.
From our production practice , Streaming half of #14695: parse_streaming_increment() assumed every byte it had
already emitted was still a prefix of the finished arguments JSON. A non-string
parameter breaks that, so the closing-tag slice starts at a stale offset and drops
a run out of the middle. stream=false is clean on the same prompts.
python3 -m pytest -q test/registered/unit/function_call/test_deepseekv4_detector.py
480 subtests fail on main, 970 pass here. String params still stream
incrementally, so #11888 isn't reintroduced.
pr-gate failures are the gate, not the tests — can someone run /tag-and-rerun-ci?
|
Thanks @Xiang-Wang-Panda. Closing this because it has had no updates in 92 days. Reopen it if the work is still relevant. Some directories moved recently, so an older branch may need retargeting: |
Motivation
With
--tool-call-parser deepseekv32(ordeepseekv4, which subclasses the samedetector) in streaming mode,
function.argumentsintermittently arrives asinvalid JSON with a run of bytes missing out of the middle. Measured on
DeepSeek-V4 over 433 calls through a production gateway:
stream=falsestream=truestream=true,temperature=0.7stream=true, ~30k-token promptstream=true,tool_choicepinned to the functionSame weights, same prompts — only
streammatters. Per tool it concentrateswhere the arguments are biggest: 13.8% of calls to a planner tool whose argument
is a nested array of objects, 0% on a single-string search tool. Pinning
tool_choice, which puts the grammar backend in the loop, does not help, becausethe arguments string the client receives is not generated by the model at all —
the detector builds it out of the DSML tags.
A representative broken payload, with the seam visible mid-string:
plus stray
\"escapes stranded inside an otherwise structural blob.Root cause
parse_streaming_increment()re-serialises the whole arguments object on everychunk and emits
common_prefix(current, previous)[sent_len:], thencurrent_params[sent_len:]once the closing tag arrives. That is sound only ifevery byte already emitted is still a prefix of the finished serialisation,
and it is not: a parameter has two possible serialised shapes, and which one you
get depends on how much of it has arrived.
The structural shape
{"tasks": [{…}]}and the string shape{"tasks": "[{\"…\"}]"}diverge from the first byte of the value and havedifferent lengths. When the fallback fires at a different moment than it did on
the previous chunk,
sent_lenno longer indexes the same string, so theclosing-tag slice starts too far in and drops exactly the bytes that were
over-sent.
The trigger is the model writing slightly invalid JSON inside a parameter,
which nothing constrains — the structural tag pins the DSML tags and the function
name, not the parameter interior. A trailing comma, an unescaped quote or a
single-quoted key is enough.
Modifications
Stop emitting bytes that can still change, rather than trying to reconcile
two partial serialisations after the fact.
_streamable_prefix()returns thelongest prefix of the final arguments JSON that is settled:
because its shape is only decided once the whole value is in hand — stop before
its value;
json.dumpsescapes characterby character, so the serialisation only grows by appending. Stream its content,
minus the closing quote.
The emit is then
current[len(sent):]guarded bycurrent.startswith(sent),which logs a warning rather than corrupting the payload if the invariant is ever
broken again.
Argument streaming is preserved. This deliberately does not buffer everything
until the closing tag — string parameters keep flowing incrementally, so it does
not reintroduce #11888. A 3000-char string parameter still arrives in 154 deltas.
Also replaces the two
rstrip()tail trims.str.rstriptakes a character set,not a suffix, so
rstrip("oke")ate any trailing run ofo,kande— aparameter value ending in
notecame back asnot._strip_partial_tag_suffix()matches a real prefix of the closing tag, and runsbefore whitespace is stripped, because the other order lets the tag's leading
<shield whitespace that then gets streamed and later vanishes when the tagcompletes (an off-by-one-byte prefix violation).
_direct_json_body()and_complete_parameters()are extraction, not newbehaviour: they exist so
_streamable_prefix()and_parse_parameters_from_xml()cannot drift apart.
_parse_parameters_from_xml()'s own behaviour is unchanged;it now has no caller inside the class and is kept for subclasses, with a
docstring note that its partial result is not prefix-safe.
Deliberately out of scope
does not parse, both paths store the blob as one JSON string, so the client
gets syntactically valid JSON whose array-typed parameter is a string. This PR
makes streaming and non-streaming agree; it does not change what they agree
on, which is a separate decision.
{and never closes still yieldsarguments: "{}". Changing that changes what a client receives on that path.non-streaming path re-serialises compactly via
parse_base_json. Both parse tothe same value.
Accuracy Tests
Not applicable — no model output changes; this is a serialisation-path fix.
Verified separately that the same 433-call probe that produced the table above
returns 0/433 malformed against a patched engine, with reasoning parsing,
tool calling, streaming framing and prefix caching all unchanged.
Speed Tests and Profiling
No measurable effect. Per chunk the work is the same regex scan plus one
json.dumpsof the settled parameters; the code being replaced did ajson.dumpsplus a_find_common_prefixover the whole string. Nothing new runsper token, and non-string parameters now serialise less often, not more.
Checklist
Tests
Added to
test/registered/unit/function_call/test_deepseekv4_detector.py, thefile that already covers this detector's streaming behaviour: 5 fixtures x 9
chunk boundary sets (per-char and 8 fixed widths), asserting that streamed
arguments parse and equal the non-streaming result, and that at every
truncation point the bytes streamed so far are a prefix of what the finished
stream produces — the invariant the old code assumed but did not hold to. Plus a
guard that a long string parameter still arrives in many deltas, and a unit test
for the
rstripfix.Run without a GPU:
CI States
Latest PR Test (Base): ❌ Run #32864233420
Latest PR Test (Extra): ❌ Run #32864232953
Latest PR Test (AMD ROCm 7.2): ❌ Run #32864233177