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
I'll start by exploring the repository to understand its structure and locate the relevant code. Let's first check what kind of project this is.
- Assistant
This looks like a Python repository related to MLX (Apple's machine learning framework) and vLLM. The issue mentions "XML tool-call output" which suggests there's some parsing of XML-formatted tool calls in the output of a model. The issue says streaming drops XML tool-call output that non-streaming parses correctly.
Let me explore the repository structure more to understand the codebase.
- Assistant
Let me explore the repository structure more, especially the code related to streaming and tool calls.
- Assistant
Let me look at the main source directory structure first.
- Assistant
Let me look at the streaming module and tool calling module more closely.
- Assistant
The issue is about streaming dropping XML tool-call output that non-streaming parses correctly. Let me explore the tool parsers and streaming code to understand the problem.
- Assistant
Let me first look at the tool parsers, especially the XML-based ones, to understand how tool calls are parsed in non-streaming mode.
- Assistant
Let me look at the streaming code and tool parsing infrastructure.
- Assistant
Let me look at the streaming code and the tool calling code. The issue is about streaming dropping XML tool-call output. I need to understand how tool calls are parsed during streaming vs non-streaming.
- Assistant
Let me look at the abstract tool parser and the streaming code to understand how tool calls are processed during streaming.
- Assistant
Let me look at the streaming code to understand how tool calls are processed during streaming.
- Assistant
Now let me look at the postprocessor.py to see how streaming is handled.
- Assistant
Now let me look at the chat completion route to see how streaming responses are handled.
- Assistant
Now let me look at the tool parsers to understand how they handle XML tool calls. Let me look at a specific XML-based tool parser.
- Assistant
Now let me look at other tool parsers that use XML to see how they handle streaming. Let me check the qwen3coder_tool_parser.py which is specifically for Qwen3 Coder and may have relevant XML parsing.
- Assistant
Now let me search for existing tests related to XML tool calls and streaming to understand the expected behavior.
- Assistant
Let me look at the test file for tool parsers to understand the expected behavior better.
- Assistant
Let me search for specific test cases that demonstrate the issue described in the issue.
- Assistant
Let me run the existing tests to see if they pass. First, let me check what test runner is used.
- Assistant
Let me run the existing tests to see if they pass:
- Assistant
The tests are passing so far. Let me continue to see if there are any failures.
- Assistant
All tests pass. Now let me look at the issue more carefully. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly". Let me search for existing test files that might be related to this issue. Let me also look at the test_postprocessor.py file since it seems to test the streaming postprocessor.
- Assistant
Let me continue reading the test_postprocessor.py file to see the test for fallback tool detection.
- Assistant
Let me run the existing tests to understand the issue better. Let me run the postprocessor tests to see if they pass:
- Assistant
All tests pass so far. Let me now look at the specific test for streaming XML tool calls to understand what the expected behavior should be. Let me also search for issues or documentation about this specific problem.
- Assistant
Let me look more carefully at the issue. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly". Let me understand the flow better by looking at the test cases and the actual code.
Let me look at the test_postprocessor.py more carefully, especially the test that says "Tool call XML in reasoning stream gets redirected to content."
- Assistant
Let me look more closely at the QwenToolParser which is used for qwen3_xml:
- Assistant
Let me look at the streaming tool filter test:
- Assistant
Now let me look at the
StreamingToolCallFilterclass invllm_mlx/api/utils.pyand understand how it works: - Assistant
Let me look at the StreamingToolCallFilter class.
- Assistant
Now I need to understand the issue better. Let me look at the chat route to see how streaming tool calls are handled:
- Assistant
Let me look at the stream_chat_completion function:
- Assistant
Let me look at the
_parse_tool_calls_with_parserfunction: - Assistant
Let me look at the full function:
- Assistant
Let me write a test to reproduce the issue. First, let me understand the expected behavior better:
- Assistant
Let me look at the postprocessor test for the #171 regression:
- Assistant
Let me look at the full test that specifically tests the qwen3_coder_streaming_with_request_extracts_tool_call:
- Assistant
Let me look at the non-streaming path for comparison:
- Assistant
Let me look at the non-streaming path more carefully:
- Assistant
- Assistant
- Assistant
I need to use the bash_terminal tool properly. Let me write a simpler test script first.
- Assistant
The test output is empty. Let me debug:' print(f"Input text: {text!r}")
codeevents = pp.process_chunk(_make_output(text)) print(f"After process_chunk: {len(events)} events") for e in events: print(f" event: type={e.type}, content={getattr(e, 'content', None)}, tool_calls={getattr(e, 'tool_calls', None)}") final_events = pp.finalize() print(f"After finalize: {len(final_events)} events") for e in final_events: print(f" event: type={e.type}, content={getattr(e, 'content', None)}, tool_calls={getattr(e, 'tool_calls', None)}") all_events = events + final_events tool_events = [e for e in all_events if e.type == "tool_call"] print(f"\nSummary:") print(f" tool_events: {len(tool_events)}") print(f" tool_calls_detected: {pp.tool_calls_detected}") print(f" tool_accumulated_text: {pp.tool_accumulated_text!r}") print(f" tool_markup_possible: {pp.tool_markup_possible}") if not tool_events: print("\nBUG: Streaming dropped XML tool call!") else: print("\nOK: Streaming correctly emitted tool call") - Assistant
Let me try a simpler approach:' print("Input:", repr(text)) events = pp.process_chunk(_make_output(text)) print("Events:", len(events)) for e in events: print(" type:", e.type, "content:", getattr(e, 'content', None), "tool_calls:", getattr(e, 'tool_calls', None)) print("tool_calls_detected:", pp.tool_calls_detected) print("tool_accumulated_text:", repr(pp.tool_accumulated_text))
final = pp.finalize() print("Finalize:", len(final)) for e in final: print(" type:", e.type) PYEOF python /tmp/test_issue2.py </tool_call>
- Assistant
' print("Input:", repr(text)) events = pp.process_chunk(_make_output(text)) print("Events:", len(events)) for e in events: print(" type:", e.type, "content:", getattr(e, 'content', None), "tc:", getattr(e, 'tool_calls', None)) print("tool_calls_detected:", pp.tool_calls_detected) print("tool_accumulated_text:", repr(pp.tool_accumulated_text))
final = pp.finalize() print("Finalize events:", len(final)) for e in final: print(" type:", e.type, "tc:", getattr(e, 'tool_calls', None)) PYEOF python /tmp/test_issue2.py </tool_call>
- Assistant
Let me try a much simpler command - just running a basic echo first to see if the tool works.
- Assistant
Good, now let me write a test file and run it:' print('Input:', repr(text)) events = pp.process_chunk(_make_output(text)) print('Events:', len(events)) for e in events: print(' type:', e.type, 'content:', getattr(e, 'content', None), 'tc:', getattr(e, 'tool_calls', None)) print('tool_calls_detected:', pp.tool_calls_detected) print('tool_accumulated_text:', repr(pp.tool_accumulated_text)) final = pp.finalize() print('Finalize events:', len(final)) for e in final: print(' type:', e.type, 'tc:', getattr(e, 'tool_calls', None)) " </tool_call>
- Assistant
I'm having trouble with multi-line commands. Let me try writing the test file first using a different approach, then running it.
- Assistant
I see the text was empty in the test. Let me write a proper test file:' print("Input text:", repr(xml_text))
events = pp.process_chunk(_make_output(xml_text)) print("Events after process_chunk:", len(events)) for e in events: print(" type:", e.type, "content:", getattr(e, 'content', None), "tc:", getattr(e, 'tool_calls', None))
print("tool_calls_detected:", pp.tool_calls_detected) print("tool_accumulated_text:", repr(pp.tool_accumulated_text))
final = pp.finalize() print("Finalize events:", len(final)) for e in final: print(" type:", e.type, "tc:", getattr(e, 'tool_calls', None)) ENDOFSCRIPT python3 /tmp/test_issue.py </tool_call>
- Assistant
Let me use the create command to make a test file:
- Assistant
OK, let me write the file step by step using echo/append.
- Assistant
Let me use the create command to create a test file:'
Test 1: Single chunk with full XML
print("=== Test 1: Single chunk with full XML ===") events = pp.process_chunk(_make_output(xml_text)) final = pp.finalize() all_events = events + final tool_events = [e for e in all_events if e.type == "tool_call"] print(f"tool_events: {len(tool_events)}") print(f"tool_calls_detected: {pp.tool_calls_detected}") print(f"tool_accumulated_text: {pp.tool_accumulated_text!r}")
Test 2: Chunked XML
print("\n=== Test 2: Chunked XML ===") parser2 = HermesToolParser() cfg2 = _make_cfg(enable_auto_tool_choice=True, tool_parser_instance=parser2) pp2 = StreamingPostProcessor(cfg2) pp2.reset()
chunks = [ "<tool_call>", '{"name": "calculate", "arguments": {"x": 1, "y": 2}}', "</tool_call>", ] all_events2 = [] for chunk in chunks: events2 = pp2.process_chunk(_make_output(chunk)) all_events2.extend(events2) print(f" chunk {chunk!r}: {len(events2)} events") final2 = pp2.finalize() all_events2.extend(final2) tool_events2 = [e for e in all_events2 if e.type == "tool_call"] print(f"tool_events: {len(tool_events2)}") print(f"tool_calls_detected: {pp2.tool_calls_detected}") print(f"tool_accumulated_text: {pp2.tool_accumulated_text!r}")
- Assistant
Let me try writing the file using Python directly:
- Assistant
Good, the XML string is correct. Let me now run the full test:
- Assistant
OK, the Hermes parser works fine with a single chunk. Let me test with the XML split across chunks:
- Assistant
OK, chunked XML works too. Let me test with multiple tool calls:
- Assistant
Now let me test with Qwen XML parser to see if it has issues:
- Assistant
comes but the final</tool_call>never comes? That would meantool_calls_detectedis False, butfinalize()` should still try.Let me try a different approach - let me look at what tests exist and what the expected behavior should be. Let me run the full test suite:Let me now run all the tests to see if there are any failures that hint at the issue:
- Assistant
Let me run without --timeout.
- Assistant
Let me exclude integration tests.
- Assistant
Let me run just the relevant test files:
- Assistant
Let me now dig deeper into the issue. Let me check what happens when the Qwen streaming parser handles text with XML and reasoning mode is active:
- Assistant
Let me look more carefully at the test files. Let me search for any test files related to this specific issue:
- Assistant
Let me check the gemma4 tool parser tests and the output router:
- Assistant
Let me look at the test_chat_streaming_spec.py:
- Assistant
Now let me understand the issue better. Let me look at the
parse_tool_callsfunction: - Assistant
Let me look at the
parse_tool_callsfunction to understand what it does. - Assistant
Let me look at more of parse_tool_calls
- Assistant
Let me look at the
_process_with_reasoningmethod in the postprocessor: - Assistant
Let me look at the full
_process_with_reasoningmethod to understand how it handles tool calls. - Assistant
OK, so the
_process_with_reasoningmethod does call_detect_tool_callswithcontent(the extracted content from the reasoning parser). Let me look at the flow more carefully.Wait, I'm confused. Let me re-read the issue description one more time:
"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."OK so the issue is specifically about XML tool calls. Let me think about what XML formats are used:
- Hermes/Qwen: ``
- Nemotron: ``
- Gemma4:
<|tool_call>call:name{args}<tool_call|>
The issue says "Streaming drops XML tool-call output." This means the streaming path fails to emit tool_call events for XML tool calls that the non-streaming path correctly parses.
- Assistant
Let me try to write the test file differently. Let me create it with the
createcommand: - Assistant
Let me write a test file step by step:
- Assistant
Let me just write the whole file using Python's file writing capabilities.
- Assistant
Let me run the test file:
- Assistant
Let me now look deeper at what exactly the issue is. Let me look at the specific test mentioned in the chat_streaming_spec.py - the
_GapStreamParsertest that shows what happens when streaming misses a tool call and finalize catches it. Let me also check what happens with the reasoning parser path: - Assistant
Let me try to understand this better by writing a more targeted test. Let me look specifically at the Qwen parser streaming behavior with chunked XML:
- Assistant
Let me focus on writing a comprehensive test to find the bug:
- Assistant
Interesting - the "Here is my response" text before the tool call is suppressed. Let me check what non-streaming does:
- Assistant
So non-streaming preserves "Here is my response Done!" in the content, but streaming drops them. Now let me understand the real bug. Let me look at the
finalize()path more carefully, particularly whentool_calls_detectedis False but the text has tool calls the streaming parser missed: - Assistant
Let me carefully run one command at a time:
- Assistant
- Assistant
Let me write the test file using python:
- Assistant
Let me look at git log for recent changes related to streaming and tool calls:
- Assistant
Let me check what happens when tools are requested but no tool parser is configured:
- Assistant
Interesting! When no tool parser is configured, the XML tool call is passed through as content. Let me check what
strip_special_tokensdoes: - Assistant
Found it! `
- Assistant
I see - the `
- Assistant
The content is being sanitized incorrectly. Now let me check the QwenToolParser streaming with a critical scenario - when content has text before AND after the tool call:
- Assistant
Interesting! The streaming path is leaking partial `
- Assistant
- Assistant
Let me investigate the key issue more carefully - what happens with content AFTER a tool call in streaming:
- Assistant
Found a bug! Content after a tool call is being dropped in streaming. Let me look deeper at the Qwen parser's streaming behavior: in prev)
cur_close_count = 1 (</tool_call> in curr)
cur_close_count <= prev_close_count -> return {'content': delta_text}
Actually let me check
print('')) print('curr close count:', curr.count('</tool_call>')) " </tool_call>
- Assistant
Let me carefully trace through the code to find the exact issue. Let me look at the QwenToolParser streaming method more carefully:
- Assistant
Interesting! The QwenToolParser's streaming method returns
{"content": delta_text}for characters within ` - Assistant
OK so the QwenToolParser streaming parser has a problem. When the tool call tags are split character by character, the streaming parser returns
{"content": "<"},{"content": "t"}, etc. for each character of `` arrives, the tool call is emitted. But the content before it (the partial tag text) has already been emitted.But wait, looking at my earlier test, when the tool call is split across chunks but at the `
- Assistant
OK, I see an issue with the Qwen parser returning content during streaming when it shouldn't. Let me focus on the actual bug now. Let me look at the QwenToolParser streaming code very carefully:
- Assistant
Now I understand the issue. Let me look at what happens when the streaming parser fails and the
finalize()doesn't have a generic fallback toparse_tool_calls:'parser = QwenToolParser() result = parser.extract_tool_calls(text) print('Qwen parser: tools_called=%s, calls=%d' % (result.tools_called, len(result.tool_calls)))
Generic parser
content, tc = parse_tool_calls(text) print('Generic parser: calls=%s' % (tc is not None)) if tc: for t in tc: print(' call: %s' % t.function.name) " </tool_call>
- Assistant
Now I understand the issue clearly. Let me summarize my findings:
The Bug: The streaming
finalize()method only triesself.tool_parser.extract_tool_calls()as fallback. But the non-streaming path (_parse_tool_calls_with_parser) has an additional fallback to the genericparse_tool_calls()function fromapi/tool_calling.py. When:- No tool parser is configured (
self.tool_parseris None), OR - The configured parser's
extract_tool_callsfails to recognize the XML format
...streaming drops tool calls that non-streaming correctly parses via
parse_tool_calls.The fix: In
finalize(), add a fallback toparse_tool_callswhen the configured parser fails or is absent.Let me implement the fix:
- No tool parser is configured (
- Assistant
Let me look at the finalize method and the key area where the fix should go.
- Assistant
Let me look at the rest of the finalize method.
- Assistant
- Assistant
I keep getting my XML tool-call tags intercepted. Let me now focus on implementing the fix. Let me look at the issue from the right perspective. The issue says "Streaming must emit the same recovered XML tool calls as non-streaming." The key problem is that
finalize()only uses the configured parser and doesn't fall back to the genericparse_tool_callsfunction.Let me implement the fix:
- Assistant
Now let me implement the fix. I need to:
- Import
parse_tool_callsfromapi.tool_calling - In
_process_standard, accumulate text inself.accumulated_texteven when no tool parser is configured (sofinalizehas text to work with) - In
finalize(), add a fallback toparse_tool_callswhen the configured parser fails or is absent
Let me implement:
- Import
- Assistant
Good, the import is added. Now let me modify
_process_standardto accumulate text and modifyfinalize()to fall back toparse_tool_calls: - Assistant
Let me look at the _process_standard method to understand what needs to change.
- Assistant
Now I understand the issue. Let me implement the fix in two parts:
- In
_process_standard, always accumulate text inself.accumulated_textsofinalize()has text even when no tool_parser is configured - In
finalize(), add a fallback to the genericparse_tool_callswhen the configured parser fails
- In
- Assistant
Now let me modify the
finalize()method to add the fallback toparse_tool_calls: - Assistant
Now let me replace the finalize method to add the fallback:
- Assistant
The shell is having trouble with quotes. Let me use Python to write the changes:
- Assistant
Let me verify the changes look correct:
- Assistant
Good, the changes look correct. Now let me run the existing tests to make sure the changes don't break anything:
- Assistant
That test requires mlx library. Let me skip it:
- Assistant
All 274 tests pass. Now let me verify the fix works by running a test:
- Assistant
The generic fallback is working. Now let me test more scenarios:
- Assistant
Let me run the test correctly.
- Assistant
I need to provide a command to the bash_terminal tool. Let me continue with more tests.
- Assistant
Let me test more scenarios with a proper command.
- Assistant
The fix is working. The generic fallback now recovers Llama-style XML when the Qwen parser can't parse it. Now let me also handle the
_process_channel_routedmethod, which might have the same issue: - Assistant
Let me look at the _process_channel_routed method:
- Assistant
I need to add
self.accumulated_text += delta_textto_process_channel_routedas well: - Assistant
Let me run all the tests again to make sure everything passes:
- Assistant
All 274 tests pass. Now let me run a comprehensive test to verify all the scenarios from the issue:
- Assistant
One test failed because the output wasn't finished. Let me fix the test - the finish_reason="tool_calls" comes from a separate finish event after the tool call:
- Assistant
All scenarios are working. Let me run the full test suite one more time:
- Assistant
All 333 tests pass. Let me now verify the complete diff of the changes:
- Assistant
The diff looks good. Let me now run a comprehensive final test:
- Assistant
All 435 tests pass. Let me now verify the final state of the file to make sure everything is correct:
- Assistant
The chunked test fails because the streaming parser already detected the tool calls correctly during streaming (when
</tool_call>arrived). Let me fix the test: - Assistant
Good, the tool calls are correctly emitted during streaming. Let me write a comprehensive final test:
- Assistant
All 10 tests pass. Let me run the full test suite one final time:
- Assistant
test_paired_compat.py needs mlx library. Let me skip that.
- Assistant
The failure in test_structured_output.py is due to missing mlx library, not related to my changes. Let me verify:
- Assistant
The failure is unrelated to my changes - it's a missing mlx library. Let me run only the tests relevant to my changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.