ISSUE DESCRIPTION Streaming drops XML tool-call output that non-streaming parses…
- User
ISSUE DESCRIPTION
Streaming drops XML tool-call output that non-streaming parses correctly
Streaming must emit the same recovered XML tool calls as non-streaming, including calls split across chunks and multiple calls, and finish with
tool_calls. Reasoning mode and request tool selection must not alter recovery. Plain text or malformed markup must not create calls or abort the stream.Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /Rapid-MLX, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand what we're working with.
Assistant
Let me explore the repository structure further to understand the codebase.
Assistant
The issue is about streaming dropping XML tool-call output. Let me look at the tool_parsers directory since that's likely where XML tool-call parsing happens.
Assistant
Now I understand the structure. The issue mentions "XML tool-call output". Let me look at the various XML-based tool parsers and the abstract tool parser.
Assistant
Let me look at the XML-based parsers and the tests directory to understand the testing setup.
Assistant
Let me look at the test_tool_parsers.py file to understand the testing structure, particularly the streaming tests for XML.
Assistant
Let me look at the QwenToolParser and other XML-based parsers.
Assistant
Let me look at the xLAM, granite, nemotron parsers - these handle XML-style tool calls.
Assistant
Let me look at the seed_oss, granite, nemotron, and llama parsers - they use XML format.
Assistant
Let me look at the nemotron, granite, and seed_oss parsers.
Assistant
The issue mentions "XML tool-call output". Let me look at the seed_oss parser which is likely the one with the actual XML format (with
<parameter>tags). Let me also check the granite parser. Let me look at the seed_oss parser.Assistant
Let me look at the granite parser which is one of the XML parsers. Let me also look at the qwen3coder
Assistant
Now let me look at the tests more closely. The issue specifically says "Streaming drops XML tool-call output that non-streaming parses correctly." Let me find the tests related to streaming and XML. Let me look at the streaming tests for hermes and the qwen3coder parser.
Assistant
Now let me run the existing tool parser tests to see which ones pass and which fail currently.
Assistant
All existing tests pass. Now let me understand the issue better. The issue is about streaming dropping XML tool-call output that non-streaming parses correctly. Let me write a reproduction script to compare streaming vs non-streaming for various parsers.
Assistant
Now let me write a reproduction script that compares streaming vs non-streaming output for the XML-based parsers. Let me focus on the parsers that the issue is about. Let me check how the streaming pipeline works and what "finish with
tool_calls" means.Assistant
Now let me understand the key part. The issue is "Streaming drops XML tool-call output that non-streaming parses correctly". Let me write a reproduction script to compare streaming vs non-streaming for all XML-based parsers, with realistic chunked input.'), "hermes_nemotron_xml": (HermesToolParser(), ''), "hermes_bare_function": (HermesToolParser(), '<function=get_weather>\n<parameter=city>Paris\n'), "hermes_multi_xml": (HermesToolParser(), '\n'), "qwen_json": (QwenToolParser(), ''), "qwen_multi_json": (QwenToolParser(), ''), "qwen3coder_xml": (Qwen3CoderToolParser(), ''), "qwen3coder_multi": (Qwen3CoderToolParser(), '\n'), "seed_oss": (SeedOssToolParser(), 'seed:tool_call\n<function=get_weather>\n<parameter=city>Paris\n\n</seed:tool_call>'), "llama": (LlamaToolParser(), '<function=multiply>{"x": 3, "y": 4}'), "nemotron": (NemotronToolParser(), ''), }
Assistant
Let me write the reproduction script to a file first.>'), "hermes_nemotron": (HermesToolParser(), '<>'), "hermes_bare": (HermesToolParser(), '<function=get_weather>\n<parameter=city>Paris\n'), "qwen_json": (QwenToolParser(), '<>'), "qwen3coder": (Qwen3CoderToolParser(), '<>'), "seed_oss": (SeedOssToolParser(), 'seed:tool_call\n<function=get_weather>\n<parameter=city>Paris\n\n</seed:tool_call>'), "llama": (LlamaToolParser(), '<function=multiply>{"x": 3, "y": 4}'), "nemotron": (NemotronToolParser(), '<>'), }
print("=" * 80) for name, (parser, text) in tests.items(): parser.reset() emitted = simulate_streaming(parser, text) parser.reset() result = parser.extract_tool_calls(text, request={"tools": []}) merged = merge_streaming(emitted) ns_names = [tc["name"] for tc in result.tool_calls] s_names = [merged[i]["function"]["name"] for i in sorted(merged)] ns_args = [tc["arguments"] for tc in result.tool_calls] s_args = [merged[i]["function"]["arguments"] for i in sorted(merged)] ok = (len(ns_names) == len(s_names) and ns_names == s_names) if ok: for a, b in zip(ns_args, s_args): try: if json.loads(a) != json.loads(b): ok = False except Exception: if a != b: ok = False status = "OK" if ok else "MISMATCH" print(f"{name:25s} {status}") print(f" non-stream: {ns_names} {ns_args}") print(f" stream : {s_names} {s_args}") print(f" deltas: {len(emitted)}") print() PYEOF python /tmp/repro.py</arg_value>
Assistant
The issue is that my reproduction text contains characters that are being interpreted as tool calls. Let me create the script file properly instead.
Assistant
I found the mismatches. Let me debug each failing parser. Let me first look at why the stateful parsers (qwen3coder, seed_oss) emit nothing, and why llama/nemotron fail.
Assistant
Both llama and nemotron emit nothing because they check for closing tags in
delta_text(which gets split across chunks). Now let me debug the stateful qwen3coder parser.Assistant
Assistant
Let me look at the remaining parsers to understand the full scope.
Assistant
Let me check the deepseek, functionary, and mistral parsers' streaming logic.
Assistant
- XML
- llama: <function=name>{json} - XML-ish
- qwen3coder: [..., <function=..>...., ..] - XML
- seed_oss: seed:tool_call...<function=..>......</seed:tool_call> - XML
- glm47:
Assistant
This is a separate filter. Let me now look at the postprocessor tests and understand the finalize fallback behavior. Let me search for postprocessor tests.
Assistant
Let me look at the
_process_with_reasoningmethod which handles reasoning mode.Assistant
and the last chunk is justEND. So END is in a single chunk. But what if END is split? The hermes parser handles this because it checkscurrent_text.count(END)vsprevious_text.count(END), notdelta_text`.OK so I think the issue is clear: the streaming parsers that use
delta_textto detect completion markers are buggy when markers are split across chunks. The fix is to usecurrent_textvsprevious_textcomparison (like hermes does) instead ofdelta_textcontainment checks.Assistant
The issue is that the heredoc contains text that looks like tool calls. Let me write the file differently using Python directly.
Assistant
Confirmed. With chunk_size=5, the start token `
Assistant
Confirmed. Now let me understand the full picture. The bug is clear:
- Non-stateful parsers use
delta_textto detect closing markers → fails when markers split. - Stateful parsers use
delta_textto detect start token → fails when start splits.
Now let me implement the fix. I'll start with the non-stateful XML parsers, making them detect completion via
current_textvsprevious_textcomparison. Let me begin withllama_tool_parser.py.- Non-stateful parsers use
Assistant
Let me open the file and edit it.
Assistant
Now let me fix the nemotron parser similarly.
Assistant
The heredoc had issues because the content contains the actual tool call markers. Let me use a Python script to do the edits instead, to avoid the heredoc/markers problem.
Assistant
Now let me fix the glm47 parser. It checks
if "`` in delta_text. Let me look at its structure more carefully.Assistant
Let me look at the full glm47 streaming method.
Assistant
Now let me fix the kimi parser. Let me look at its streaming method and the markers it uses.
Assistant
Now the harmony parser (
if "<|call|>" in delta_text):Assistant
Now the functionary parser (
if any(m in delta_text for m in end_markers)):Assistant
The xLAM parser is JSON-array based, not XML. But the issue says "XML tool-call". Let me focus on the XML parsers. However, for consistency and robustness, let me also fix xLAM since it has the same delta_text bug. Actually, let me reconsider — the issue specifically says "XML tool-call output". Let me be careful about scope.
The xLAM, mistral, granite, deepseek, deepseekv31 are JSON-based, not XML. The issue is about XML. But the requirement "Plain text or malformed markup must not create calls or abort the stream" applies to all.
Let me focus on the XML parsers that are clearly broken: nemotron, llama, qwen3coder, seed_oss, glm47, kimi, functionary, harmony. I've fixed nemotron, llama, glm47, kimi, functionary, harmony, deepseek.
Actually, let me reconsider deepseek — it's not XML. But it had the same delta_text bug. The fix I made is consistent with the issue's intent ("Streaming must emit the same recovered XML tool calls as non-streaming"). Actually deepseek is not XML. Let me reconsider whether to keep the deepseek change.
Assistant
I see the issue. The key line is:
) or self.tool_call_start_token in delta_text: self.is_tool_call_started = TrueWhen the start token is split across chunks, this check fails, so
is_tool_call_startednever becomes True and everything is emitted as content. The fix is to checkcurrent_textinstead ofdelta_textfor the start token presence.Let me fix the qwen3coder parser's start detection to use
current_text.Assistant
Now let me apply the same fix to the seed_oss parser. Let me look at its start detection logic.
Assistant
Now let me re-run my reproduction script to see if the fixes work.
Assistant
All mismatches are now fixed. Now let me test with more challenging cases: multiple tool calls, calls split across chunks, reasoning mode (think tags), and malformed markup. Let me write a more comprehensive test.
Assistant
All cases pass. Now let me verify the "finish with
tool_calls" requirement and the "Reasoning mode and request tool selection must not alter recovery" requirement at the postprocessor level. Let me test the full postprocessor pipeline with realistic streaming.But first, let me run the existing tests to make sure I didn't break anything.
Assistant
All pass. Let me run the broader streaming and tool calling test suites.
Assistant
Some tests require mlx (not available in this environment). Let me run only the tests that don't require mlx.
Assistant
Let me run all the test files that don't require mlx to check for regressions broadly.
Assistant
I broke a harmony test. Let me look at the test.
Assistant
I see. The harmony test expects that when the second
<|call|>arrives (delta contains<|call|>), it emits ALL tool calls found so far (both func_a and func_b) — i.e.,len == 2. My change made it only emit the NEW tool call (the second one), via thenew_calls = result.tool_calls[prev_closed:]slice.Assistant
These tests are for
extract_tool_calls(non-streaming), not streaming. Let me check if there are streaming-specific tests for these parsers (llama, deepseek, kimi, functionary, nemotron, granite, xlam) that might test emit-all vs emit-new.Assistant
Assistant
There are upstream regression tests for glm47 and seed_oss streaming. Let me look at the glm47 streaming tests.
Assistant
I see. The glm47 upstream test
test_streaming_multiple_tools_on_closeexpects emit-all: when the second</tool_call>arrives, it emits BOTH tool calls (len == 2). The comment says "Our GLM parser re-parses the full text on close, so both should appear".So glm47 also uses emit-all semantics, and there's an explicit test for it. My change to emit-new broke this. Let me run the upstream regression tests to confirm.
Assistant
Interesting — the glm47 upstream tests pass! Let me check why. The test
test_streaming_multiple_tools_on_closeconstructsprevious_textby replacing the FIRST `` and rsplitting. Let me trace through my glm47 change.The previous_text in that test is everything up to (but not including) the second
</arg_value>appears once in previous_text (the first one), and twice in current_text (both). Socur_closed (2) > prev_closed (1). My code then doesnew_calls = result.tool_calls[prev_closed:]=result.tool_calls[1:]= only the second call. That would givelen == 1, not 2.But the test passed! Let me check — maybe the test constructs previous_text differently. Let me trace.
<function=get_weather><parameter=city>Beijing</tool_call>
<function=get_weather><parameter=city>Shanghai''' prev = full.replace('</tool_call>', '', 1).rsplit('</tool_call>', 1)[0] print('PREV has', prev.count('</tool_call>'), 'close markers') print('FULL has', full.count('</tool_call>'), 'close markers') " 2>&1 | tail</arg_value>
Assistant
The tool call markers in my command text are being misinterpreted. Let me write a debug script to a file instead.
Assistant
Assistant
Now let me run the harmony tests again.
Assistant
Now let me run the upstream regression tests and all the tool parser tests again.
Assistant
Now let me re-run my reproduction to confirm everything still works after the harmony revert.
Assistant
Now let me test the full postprocessor pipeline to verify "finish with
tool_calls" and "reasoning mode and request tool selection must not alter recovery". Let me write a comprehensive postprocessor test.Assistant
Let me fix the make_output function.
Assistant
Excellent! Everything works perfectly at the postprocessor level:
- XML tool calls split across chunks are recovered (nemotron, llama, qwen3coder) ✓
- Multiple calls are all emitted with correct indices ✓
- Finish reason is
tool_calls✓ - Plain text → no calls, finish
stop, stream continues ✓ - Malformed markup (open never closes) → no calls, finish
stop, stream continues ✓
Now let me test the "Reasoning mode and request tool selection must not alter recovery" requirement. Let me test with reasoning mode enabled and with request tools selection.
Assistant
I found an issue. In reasoning mode (qwen3), the tool call IS recovered (get_weather), but the finish_reason is
stopinstead oftool_calls. The issue says "Reasoning mode ... must not alter recovery" and "finish withtool_calls".Let me investigate the reasoning mode path. The problem is in
_process_with_reasoning. Let me look at how the finish reason is computed there. The issue is that when reasoning parser is active, the tool call is detected during streaming (tool_calls_detected=True), but the finish event's finish_reason computation...Let me trace. In reasoning mode, the is called. When a tool_call event is emitted, it sets . But the final finished chunk has (empty delta), and the reasoning parser's may return content. Let me look more carefully.
Assistant
Now I understand the reasoning mode issue. In reasoning mode (qwen3 reasoning parser), EVERYTHING is classified as
reasoningcontent (because the qwen3 reasoning parser treats ambiguous tokens as reasoning until `). Thecontentis None (everything goes to reasoning), so_detect_tool_callsis never called with content. The tool call markup goes intoreasoning, notcontent`. So streaming detection never fires.Then finalize() catches it (FINALIZE event=tool_call), and sets
tool_calls_detected=True, with finish_reason=tool_calls. But the FINAL finish event was already emitted BEFORE finalize() with finish_reason=stop!Assistant
I see. The MiniMax redirect handles when tool call markup appears in
reasoning— it moves it tocontent. The check is:_check = self.tool_accumulated_text + reasoning if ("<minimax:tool_call>" in _check or "Assistant
The auto parser ALSO uses
delta_textfor completion detection (if any(m in delta_text for m in end_markers)). It's not strictly XML but it handles XML formats. Let me fix it too for consistency. But first, let me address the reasoning mode issue in the postprocessor.The reasoning mode issue: in reasoning mode, tool call markup gets classified as
reasoning, so_detect_tool_callsis never called with the markup, and streaming never detects the tool call. The finalize() catches it but emits after thestopfinish event.The fix should be in
_process_with_reasoning's MiniMax redirect. The redirect currently checks for<minimax:tool_call>, `Assistant
Now I understand the MiniMax redirect. It's meant to handle the case where tool calls are wrapped in
<thinkfrom the reasoning to content so_detect_tool_calls` can process it.But the issue says "Reasoning mode and request tool selection must not alter recovery." The current behavior in reasoning mode drops the streaming tool detection because:
- The redirect only checks for
<minimax:tool_call>, `
- The redirect only checks for
Assistant
The test
test_tool_xml_in_reasoning_redirecteduses `reasoning = "Assistant
Now I understand the redirect is meant for MiniMax specifically. The issue is that in reasoning mode, when the reasoning parser classifies ALL output as reasoning (because there's no
), and the content contains XML tool calls, the streaming detection never fires.
Now let me think about the right fix for the reasoning mode issue. The requirement is "Reasoning mode ... must not alter recovery" and "finish with tool_calls".
The cleanest fix: expand the MiniMax redirect check to also detect XML tool-call markup more broadly. When tool markup appears in
reasoning, redirect it tocontentso_detect_tool_callscan process it. The current check only catches<minimax:tool_call>, `Assistant
This test confirms that when a reasoning parser is active and there are no think tags, the reasoning parser classifies everything as reasoning during streaming, but
finalize_streamingcorrects to content. This is the expected behavior for plain text.But for tool calls, the issue is that the reasoning parser swallows the XML tool calls into
reasoning, and streaming never detects them as tool calls. The finalize() in the postprocessor catches them, but the finish event withstopis already emitted.Let me look at how the chat completion route handles the finalize events and finish reason. Let me check if there's a reconciliation step.
Assistant
I see. The chat route, on finalize, emits a tool_call chunk with
finish_reason="tool_calls". But this comes AFTER the main streaming loop which would have already emitted a finish chunk withstop. Let me check the main loop's finish handling.Assistant
I see the issue clearly now. The main loop processes the
finishevent (withstopfinish_reason) during the lastprocess_chunk. Thenfinalize()emits atool_callevent withfinish_reason="tool_calls". So the client gets:- A finish chunk with
stop - A tool_call chunk with
tool_calls
This is the bug in reasoning mode: the finish event is emitted with
stopbefore finalize detects the tool call.The fix should ensure that when
tool_calls_detectedcould still be set by finalize, the finish event shouldn't prematurely emitstop. OR, the finalize should run BEFORE the finish event is emitted.Actually, the cleaner fix per the issue ("Reasoning mode ... must not alter recovery"): in reasoning mode, the XML tool calls that get swallowed into
reasoningshould be detected during streaming sotool_calls_detectedis set before the finish event.Let me reconsider the MiniMax redirect. The redirect moves reasoning→content when it detects tool markup. But the issue is it only checks for specific markers. For a general XML tool call, the reasoning would contain , , , etc. None of these match the current redirect check (, `
- A finish chunk with
Assistant
Let me look at the default
has_pending_tool_callin the abstract parser and the nemotron one.Assistant
The nemotron parser doesn't override
has_pending_tool_call, so it uses the base which checks `"Now, for the reasoning mode fix. The cleanest approach that aligns with "Reasoning mode must not alter recovery":
In
_process_with_reasoning, the MiniMax redirect should detect ANY tool-call markup that the configured tool parser would recognize, not just MiniMax-specific markers. I can use the tool parser'shas_pending_tool_callmethod (or a broader marker check) to decide whether to redirect reasoning→content.But wait —
has_pending_tool_callfor nemotron (base) checks `"Actually, let me think about this differently. The simplest, most robust fix: in the MiniMax redirect, check for the broader set of XML tool-call markers that any parser might handle. Let me expand the check to include
<function=,</function>,<parameter=, , etc. But that's fragile.Assistant
Wait, `"
So the redirect DOES fire for the nemotron XML case (because `"
Hmm, but in my debug, the events were all
reasoningandtool_calls_detectedstayed False. Let me re-examine. The redirect fires (content gets reasoning), then_detect_tool_calls(content)is called. But in my debug, no tool_call events appeared. Let me check whether the redirect actually ran and whether_detect_tool_callswas called.Let me add more debugging.
Assistant
The
_detect_tool_callswas NEVER called! So the redirect didn't fire. Let me check — the redirect checks_check = self.tool_accumulated_text + reasoning. The reasoning from the qwen3 parser... let me check what the qwen3 reasoning parser returns.The qwen3 reasoning parser, during streaming with no think tags, classifies everything as
reasoning. Sodelta_msg.content = Noneanddelta_msg.reasoning = chunk. The redirect checksif self.tool_parser and reasoning:— reasoning is non-empty, so it enters. Then_check = tool_accumulated_text + reasoning.But
_detect_tool_callswas never called. That means the redirect'sifcondition was False. Let me check the_check— maybe the `"Wait, the issue might be that the qwen3 reasoning parser's
extract_reasoning_streamingreturnsdelta_msgwherecontentandreasoningare set differently. Let me check the qwen3 reasoning parser.Assistant
So during streaming (no think tags), the qwen3 parser classifies everything as
reasoning. Let me verify whatdelta_msg.contentanddelta_msg.reasoningare. Let me debug the redirect directly.Assistant
So
reasoning = chunkandcontent = None. The redirect check is:if self.tool_parser and reasoning: _check = self.tool_accumulated_text + reasoning if ("<minimax:tool_call>" in _check or "Assistant
Let me now look at the broader issue from the perspective of the chat route's finalize handling. Actually, let me reconsider the whole approach.
The core problem in reasoning mode: the finish event with
stopis emitted BEFORE finalize detects the tool call. So the stream hasstopthen . This means the LAST finish_reason the client sees is (from the finalize tool_call chunk), which is actually... correct? Let me re-check.Assistant
Let me write a test that simulates the chat streaming route's finalize behavior to check the final finish_reason.
Assistant
Assistant
Let me look at all the
has_pending_tool_callimplementations to understand the full marker set.Assistant
The
has_pending_tool_callmethod is exactly the right tool for the redirect — it tells us if the text contains tool-call markup that the configured parser recognizes. The redirect should useself.tool_parser.has_pending_tool_call(_check)instead of the hardcoded MiniMax markers.This is the cleanest, most general fix: delegate to the configured tool parser's
has_pending_tool_call. This way, ANY parser's tool-call format gets redirected from reasoning to content in reasoning mode, ensuring streaming detection fires andtool_calls_detectedis set before the finish event.Let me verify this works for the nemotron case. The nemotron parser uses the base
has_pending_tool_callwhich checks `"Wait — but the base
has_pending_tool_callalso checkshas_text_format_tool_call(the[Calling toolpattern). That's fine.Let me also check the kimi parser — it doesn't override
has_pending_tool_call, so it uses base which checks `"Let me check which parsers DON'T have a useful
has_pending_tool_callfor their format:- nemotron: base → "
- llama:
<function=✓ - kimi: base → "
Assistant
Some parsers return False for their format:
kimi: uses basehas_pending_tool_callwhich checks `"
The issue is these parsers use base
has_pending_tool_callwhich checks `"This means my redirect fix (using
has_pending_tool_call) wouldn't work for kimi, functionary, deepseek, xlam. I need to addhas_pending_tool_calloverrides for these parsers, OR use a broader marker check.Let me add
has_pending_tool_calloverrides for kimi, functionary, deepseek, xlam so they detect their own formats. Let me check their markers.Assistant
Now let me add
has_pending_tool_calloverrides for kimi, functionary, deepseek, and xlam. Let me do this.Assistant
The functionary anchor wasn't found. Let me check the exact text of functionary's extract_tool_calls.
Assistant
The docstring is "Extract tool calls from Functionary model output." not "from a complete Functionary". Let me fix the functionary, deepseek, xlam additions with the correct text. Let me check each.
Assistant
Now let me also add
has_pending_tool_callfor glm47 (it uses base which checks "Assistant
Only deepseek returns False now. The deepseek test text I used was
<\uff7c\uff9d\uff7d...which was a bad test string (I used wrong characters). Let me check the real deepseek markers.Assistant
Deepseek's
has_pending_tool_callworks correctly with the real markers. My test string was just wrong. Now all parsers have workinghas_pending_tool_call.Now let me update the postprocessor's MiniMax redirect to use
has_pending_tool_callinstead of the hardcoded markers. This makes the reasoning-mode redirect general for all XML/tool-call formats.Assistant
Now let me update the redirect to use
has_pending_tool_callfor generality. I'll keep the existing hardcoded markers as a fast-path but add thehas_pending_tool_calldelegation. Actually, the cleanest is to replace the hardcoded check with a call tohas_pending_tool_callplus a fallback for markers the parser might not cover.Let me think about the semantics. The redirect needs to detect whether the reasoning contains tool-call markup that should be re-routed to content. The
has_pending_tool_callmethod is exactly this. But I should also keep the hardcoded markers as a safety net for parsers whosehas_pending_tool_callmight not cover their streaming markers.Actually, since I've now added
has_pending_tool_callto all parsers, delegating to it should be sufficient. But let me keep the existing markers too for backward safety (the testtest_tool_xml_in_reasoning_redirectedchecks thattool_parser.extract_tool_calls_streamingis called when reasoning="Assistant
I see a duplication bug — lines 329-332 have the old content duplicated. Let me fix that.
Assistant
Now let me re-run the reasoning mode test.
Assistant
The
reasoningvariable is referenced before assignment. The linecontent = delta_msg.contentwas followed by my comment, but the originalreasoning = delta_msg.reasoningline was removed. Let me check.Assistant
The
reasoning = delta_msg.reasoningline was lost during my edit. Let me add it back aftercontent = delta_msg.content.Assistant
Still
['stop', 'tool_calls']in reasoning mode. The redirect still isn't firing early enough. Let me debug again.Assistant
_detect_tool_callsis still never called, andtool_accumulated_textis empty. So the redirect isn't firing. The issue:reasoningis the small chunk (e.g.'<fu'), andtool_accumulated_textis empty. So_check = '' + '<fu'='<fu'. The nemotronhas_pending_tool_call('<fu')checks"<to..." in '<fu'→ False. And<function=is not in'<fu'either. So the redirect doesn't fire on partial chunks.The problem is the redirect checks the small delta chunk, not the full accumulated text. The
tool_accumulated_textis empty because nothing was redirected yet. So the redirect only fires once enough of the marker accumulates... but it never accumulates because each chunk is checked independently with emptytool_accumulated_text.I need to check the full
accumulated_text(or reasoning accumulated), not just the current delta. Let me fix the redirect to check the accumulated reasoning text.Actually, the
_check = self.tool_accumulated_text + reasoningwas designed for MiniMax where the tool markup is wrapped in blocks and arrives together. But for the incremental case, I need to accumulate the reasoning.Assistant
Now reasoning mode has
['stop']with 0 tool_call_chunks — the redirect fires now (content gets reasoning), but_detect_tool_callsreturns content passthrough instead of tool_calls. Let me debug what's happening now.Assistant
Assistant
Assistant
Let me think about the catch-up more carefully. The issue is that
tool_accumulated_textdoesn't have the early reasoning chunks. When the redirect fires, I need to maketool_accumulated_textalign with the full accumulated text.The cleanest approach: when the redirect fires and
tool_accumulated_textis "behind"accumulated_text, catch it up. Specifically, settool_accumulated_texttoaccumulated_textminus the current content (so_detect_tool_calls's+= contentbrings it to the fullaccumulated_text).Let me implement this:
Assistant
Now reasoning mode emits
['tool_calls']with 1 tool_call_chunk and final finish_reasontool_calls. Let me verify the tool call content is correct in reasoning mode.Assistant
Excellent! Reasoning mode now correctly recovers all XML tool calls (single, multiple, llama, qwen3coder) with proper finish_reason
tool_calls.Now let me make sure I haven't broken the existing postprocessor and reasoning tests. Let me run them.
Assistant
All pass. Now let me run the broader test suite for tests that don't require mlx.
Assistant
The mlx-dependent tests can't run. Let me run the ones that don't require mlx.
Assistant
Let me run a broader set of tests that don't require mlx to check for regressions. Let me find all test files that can be collected without mlx.
Assistant
There are some test files requiring mlx or network. Let me run a focused set of relevant test files that I know can be collected.
Assistant
All 940 tests pass. Now let me also fix the auto_tool_parser's
delta_textcompletion check since it handles XML formats and has the same bug.Assistant
", "", ")]"] if any(m in delta_text for m in end_markers): result = self.extract_tool_calls(current_text) if result.tools_called: return { "tool_calls": [ { "index": i, "id": tc["id"], "type": "function", "function": { "name": tc["name"], "arguments": tc["arguments"], }, } for i, tc in enumerate(result.tool_calls) ] }
return None'''Assistant
The auto parser has the same
delta_textcompletion bug. Let me fix it using current_text vs previous_text comparison.", "", ")]"] if any(m in delta_text for m in end_markers): result = self.extract_tool_calls(current_text) if result.tools_called: return { "tool_calls": [ { "index": i, "id": tc["id"], "type": "function", "function": { "name": tc["name"], "arguments": tc["arguments"], }, } for i, tc in enumerate(result.tool_calls) ] }Assistant
The heredoc contains the tool call markers. Let me write the Python script to a file instead.
Assistant
Let me verify the auto parser fix and add a
has_pending_tool_calloverride for it (it uses base which checks "Assistant
The auto parser's
has_pending_tool_call(base) only detects "Assistant
Now let me verify the auto parser's has_pending works.
Assistant
Now let me run the tests again to make sure auto parser changes don't break anything.
Assistant
Let me check the mistral streaming tests for the auto parser to make sure I didn't break them.
Assistant
Now let me run my full reproduction script once more to confirm all parsers work, including auto.
Assistant
All passing. Now let me test the auto parser streaming with char-split chunks and the postprocessor pipeline with auto. Let me also test the "request tool selection must not alter recovery" requirement more thoroughly.
Let me test the auto parser in reasoning mode at the postprocessor level.
Assistant
Excellent! The auto parser works correctly in both standard and reasoning modes, recovers XML tool calls, finishes with
tool_calls, and plain text produces no calls withstop.Now let me verify the "request tool selection must not alter recovery" requirement. The concern is that passing
requestwith tools should not change whether a tool call is recovered. Let me test with various request tool selections.Assistant
Request tool selection does not alter recovery — all cases produce the same tool call with
tool_callsfinish.Now let me verify the edge case: "Plain text or malformed markup must not create calls or abort the stream." I tested plain text. Let me test malformed markup more thoroughly at the postprocessor level.
Assistant
Let me check the "nested_weird" case:
START + "\n<function=<weird>>\n</function>\n" + END. The nemotron parser extracts a tool call with name<weird(the>after weird closes the function name). Let me verify this matches non-streaming.Assistant
The nemotron and auto parsers (in non-streaming mode) DO extract a call from
<function=<weird>></function>(name=<weird). This is because the regex<function=([^>]+)>matches name=<weirdand then>closes it. So this is a pre-existing behavior of the non-streaming parser, and my streaming fix correctly matches it. The llama parser doesn't match because its regex requires{...}arguments. So the streaming and non-streaming are consistent — that's the requirement ("same recovered XML tool calls as non-streaming").So "nested_weird" producing a call in nemotron/auto is correct (matches non-streaming). This is not malformed markup creating a SPURIOUS call — it's the parser's existing behavior for that input. The requirement is "Plain text or malformed markup must not create calls" — but this particular markup
<function=...>...</function>IS a valid tool call format to the parser. So it's fine.Let me verify the streaming output matches non-streaming for this case (consistency check).
Assistant
Streaming matches non-streaming.
Now let me review all my changes via git diff to make sure everything is clean and correct.
Assistant
Let me review the full diff to verify correctness.
Assistant
Now let me reconsider a potential issue with the functionary and auto parsers: I re-parse
previous_textviaextract_tool_calls(previous_text, request)on every completion to computeprev_emitted. This could be expensive but is correct. However, the deepseek parser uses_end_count(previous_text)as the slice offset, which is different from the functionary/auto approach. Let me reconsider the deepseek dedup.For deepseek, I used
new_calls = result.tool_calls[(_end_count(previous_text)):]andindex=i(starting from 0). This is inconsistent with the functionary/auto approach. The deepseek format is JSON-based (not XML), and the_end_countmay not equal the number of parsed tool calls. But since deepseek isn't the focus (it's not XML), and the original emitted ALL calls, let me reconsider whether my dedup is even right for deepseek.Actually, let me reconsider. The original deepseek emitted ALL tool calls found. There's no existing streaming test for deepseek multi-call. Let me check if there's an upstream test.
Assistant
There's a deepseekv31 (different from deepseek) parser with streaming tests. The
deepseek_tool_parser(not v31) has no streaming tests. Let me check the deepseekv31 parser - I didn't modify it but let me check if it has the same delta_text bug.Assistant
The deepseekv31 parser is stateful and complex — it uses
delta_textchecks (TOOL_CALL_END in delta_text,'"' in delta_text) but also counts. It's a different, more sophisticated stateful parser. It has streaming tests. Since it's not XML (it's JSON/markup based) and has its own tests, and modifying it is risky, let me leave it. The issue is about XML tool calls.Now, let me reconsider the deepseek (non-v31) change. I changed it to dedup via
_end_count. But the deepseek parser is JSON-based, not XML. Let me reconsider whether my change is correct or could break. Since there are no streaming tests for it, and the change makes it robust to split markers (the core issue), let me keep it but make the dedup logic consistent and safe.Actually, let me reconsider: for deepseek, the original emitted ALL tool calls on each end marker. My change emits only NEW calls. For a single tool call (the common case),
_end_count(previous_text)would be 0 when the end marker arrives (assuming previous didn't have the end marker), so = all. That's fine for single call.Assistant
Now let me run the full relevant test suite again to confirm everything passes.
Assistant
All 940 tests pass. Now let me also run the deepseekv31 streaming tests specifically to ensure I didn't break them (I didn't touch deepseekv31, but let me confirm).
Assistant
Let me now run the deepseek streaming reproduction to verify the multi-call dedup works.
Assistant
Let me write the deepseek test to a file.
Assistant
Deepseek streaming now correctly emits both tool calls with proper indices (0, 1) when char-split.
Now let me verify the qwen3coder and seed_oss parsers handle the case where the start token is split AND there's content before the tool call. Let me test the existing tests for qwen3coder/seed_oss streaming once more, and add a content-before test.
Assistant
Assistant
So even hermes leaks
'Let me help.<tool_c'— the partial start token<tool_cleaks as content. This is a PRE-EXISTING behavior, not something I introduced. The issue says hermes "parses correctly" — but it leaks the partial start token too.So the partial-start-token leak is pre-existing across all parsers, including hermes. The issue is about tool calls being DROPPED entirely (emitted 0 tool calls), not about partial markup leaking as content. The tool call IS recovered (via finalize or streaming) in the postprocessor.
Wait — but the qwen3coder case showed
KeyError: 'name', meaning the qwen3coder emitted a tool_call delta WITHOUT a name (just arguments fragment). Let me check that. The qwen3coder emits incremental argument fragments. Let me check whether qwen3coder actually recovers the full tool call.Let me re-run the leak test but handle the tool_call structure properly.
Assistant
Now I see:
- hermes, nemotron, qwen3_coder_xml: recover the tool call correctly (
get_weatherwith{"city": "Paris"}), but leak'Let me help.<tool_c'as content (the partial start token). - seed_oss: recovers the tool call but leaks the ENTIRE markup as content.
The partial-start-token leak is pre-existing for hermes/nemotron (they had it before my changes too, since hermes wasn't changed and nemotron's behavior here is the same). So this is NOT a regression I introduced.
The seed_oss case is worse — it leaks the whole markup. But wait, seed_oss has
<seed:think>handling andis_thinking_endgating. Let me check whether seed_oss leaked the whole markup BEFORE my change. Let me check git stash.Actually, let me reconsider the scope. The issue says "Streaming must emit the same recovered XML tool calls as non-streaming". The tool calls ARE recovered (all 4 parsers recover ). The content leak is a separate, pre-existing issue (the partial start token leaks for hermes too, which the issue says works correctly).
- hermes, nemotron, qwen3_coder_xml: recover the tool call correctly (
Assistant
Assistant
Let me look at the seed_oss content-before streaming test to make sure my change to the content_before logic is consistent.
Assistant
Assistant
Let me write a final comprehensive verification script covering all the issue requirements.
Assistant
Interesting — llama and seed_oss fail at the postprocessor level for the single split XML case. Let me investigate. The llama case:
single = START + "...<function=get_weather>..." + END. But llama format is<function=name>{json}</function>— it expects JSON arguments{...}, not XML<parameter>tags. So llama'sextract_tool_calls(non-streaming) would NOT parse the nemotron-style<parameter>format. So the comparisonm[0]["function"]["arguments"]=={"city":"Paris"}fails because llama parses differently.Wait, let me check. The
singletext uses<parameter=city>Paris</parameter>which is the nemotron format, not llama's<function=name>{"city":"Paris"}</function>. So llama wouldn't parse it. My test is wrong — I used the nemotron format for llama. Let me fix the test to use llama's actual format.Let me re-examine the llama failures.
Assistant
My test was wrong:
- llama: The
singletext uses nemotron-style<parameter>format, which llama's non-streaming parser does NOT parse (it expects{json}). Sotools_called=Falsefor non-streaming. The test expectation was wrong — I should use llama's own format<function=multiply>{"x":3,"y":4}</function>. - seed_oss: The
singletext uses theSTART...ENDwrapper (qwen3coder format), but seed_oss expects<seed:tool_call>...</seed:tool_call>wrapper. So seed_oss non-streaming doesn't parse the qwen3coder-style wrapper. The test should use seed_oss's<seed:tool_call>format.
So my final_verify test was using the wrong format for llama and seed_oss. The parsers themselves are CORRECT — they parse their OWN format correctly. Let me fix the test to use each parser's correct format.
- llama: The
Assistant
All 32 checks pass. The earlier failures were due to my test using the wrong format for llama/seed_oss. Now with each parser's own format, everything works.
Let me clean up the temp file and run the full test suite one final time to confirm no regressions.
Assistant
All 940 tests pass with 6 skipped (mlx-dependent). Let me also run a couple more test files that might be affected by the postprocessor changes.
Assistant
Those require mlx. Let me run the ones that can be collected.
Assistant
All passing. Now let me do a final review of the complete diff to make sure everything is clean.
Assistant
All files compile and all tests pass. Let me do one final review of the glm47 and deepseek changes since those had upstream tests, to make sure the logic is sound.
Assistant
Now let me run the upstream glm47 multi-tool test specifically to confirm it still passes (it relies on prev_closed=0 giving all calls).
Assistant
All upstream regression tests pass.
Let me now review the complete final diff one more time to ensure correctness and clean code.
Assistant
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.