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 structure to understand what we're dealing with. Let's first look at the root directory.
- Assistant
Let me explore the repository structure more carefully.
- Assistant
Let me explore the main package structure to understand the codebase better.
- Assistant
The issue is about streaming dropping XML tool-call output that non-streaming parses correctly. Let me look at the relevant files. The key areas to investigate would be:
- Tool parsers (tool_parsers directory)
- Streaming-related code
- API endpoints that handle streamingLet me start by examining the tool_parsers directory and understanding the structure.
- Assistant
Let me look at the tests directory for any existing tests related to streaming and tool calls.
- Assistant
Let me look at the streaming-related code and tool parser infrastructure to understand the issue.
- Assistant
Let me look at the streaming code and understand how tool calls are handled during streaming.
- Assistant
Let me understand the streaming pipeline and where tool calls are parsed. Let me look at the key streaming-related files:
- Assistant
Let me understand the issue better. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly." This means that when streaming responses from the model, XML tool calls are not being properly parsed/emitted, but the same content is correctly parsed when not streaming.
Let me look at the test file for streaming tool filter and the streaming pipeline integration:
- Assistant
Now let me look at the
StreamingToolCallFilterand understand how streaming handles tool calls. Let me look at the utils module: - Assistant
Let me search for the
StreamingToolCallFilterclass and the streaming pipeline: - Assistant
Let me look at the
StreamingToolCallFilterclass and how it's used in the server: - Assistant
Now I need to understand how streaming tool calls are being processed. The issue states "Streaming drops XML tool-call output that non-streaming parses correctly." This suggests that during streaming, XML tool calls are not being properly extracted and emitted as structured tool calls, whereas non-streaming mode correctly parses them.
I should examine the server code to see how streaming responses are handled. Let me first look at the server.py file.
- Assistant
Let me look at the streaming handler in server.py more carefully.
- Assistant
Let me look for the streaming chat completion endpoint:
- Assistant
Let me search for the chat completions endpoint handler to understand how streaming is handled.
- Assistant
Let me look at the routes directory:
- Assistant
The chat.py file in routes/ is likely where the streaming logic lives. Let me examine it.
- Assistant
Let me look at the streaming chat completion function more closely to understand how tool calls are handled in streaming mode.
- Assistant
Now I need to look at the
StreamingPostProcessorclass to understand how it processes tool calls. This seems to be the key class that handles the conversion from raw model output to structured tool calls. Let me look at the postprocessor.py file. - Assistant
Let me understand the issue better. The problem is about "Streaming drops XML tool-call output that non-streaming parses correctly". This seems to be about XML tool call parsing during streaming mode vs non-streaming mode.
Let me look at the tool parsers, especially those that handle XML format:
- Assistant
Now let me look at the XML-based tool parsers - the ones that deal with XML tool calls. Let me check the qwen tool parser first since it seems to deal with XML:
- Assistant
Now I need to understand how XML tool calls work in streaming mode. Let me check the hermes tool parser since it also handles XML:
- Assistant
Now let me look at the minimax tool parser which uses XML-style tool calls:
- Assistant
Let me now look at the existing tests to understand the exact scenario:
- Assistant
Now let me look at the test for streaming tool filter and streaming pipeline integration:
- Assistant
Let me look at the test files related to tool parsers and streaming to understand what tests exist and what might be failing:
- Assistant
Let me now look at the
stream_chat_completionfunction more carefully, specifically focusing on how tool calls are handled in streaming vs non-streaming mode: - Assistant
Let me now look at the
_parse_tool_calls_with_parserfunction and understand how it works: - Assistant
Let me look at the tool_calling.py file to understand how tool calls are parsed.
- Assistant
Let me now look at the test files that might be related to this issue to understand what's being tested:
- Assistant
Let me now look at the existing tests for the streaming postprocessor:
- Assistant
Let me look at the postprocessor tests to understand what's being tested:
- Assistant
Let me now look at the test files that specifically test streaming tool calls to understand what tests exist:
- Assistant
Let me now run the existing tests to understand what's currently passing:
- Assistant
All tests pass. Let me now run the streaming-related tests:
- Assistant
Let me now understand the full issue. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly." Let me look at the Qwen3coder tool parser since it specifically handles XML:
- Assistant
Let me take a step back and look at the test files more carefully. The issue title mentions "Streaming drops XML tool-call output that non-streaming parses correctly." Let me understand what specific scenarios this covers by examining the test files more closely:
- Assistant
Let me look at the existing tests to understand what specific scenarios might be failing:
- Assistant
Let me look at the postprocessor more carefully to understand the streaming issue:
- Assistant
Let me look at where
accumulated_textis actually set: - Assistant
Let me look at the
_process_with_reasoningmethod: - Assistant
Now let me understand the full postprocessor file more carefully, especially the
_process_standardand_detect_tool_callsmethods: - Assistant
Now I need to understand the full picture. Let me look at the domain events module and the anthropic streaming route:
- Assistant
Let me look at the Anthropic streaming route to understand the full picture:
- Assistant
Now I understand the issue. Let me trace through the actual problem scenario carefully. The key insight is in the
finalize()method: - Assistant
Let me look at the full postprocessor file to understand all the methods involved:
- Assistant
Let me look at the key files one at a time to understand the issue.
- Assistant
Let me look at the finalize method and the _detect_tool_calls method:
- Assistant
Now I have a clear understanding of the issue. Let me trace through the problem:
In
_detect_tool_callsand_process_standard, when the streaming parser (extract_tool_calls_streaming) finds tool calls, it setsself.tool_calls_detected = True. But infinalize(), the conditionnot self.tool_calls_detectedprevents the fallbackextract_tool_callsfrom running. This means if the streaming parser detects SOME tool calls but misses others (which the non-streaming parser would find), the missed ones are never recovered.The fix is to:
- Track how many tool calls were emitted during streaming
- In
finalize(), always runextract_tool_callswhen there's plausible markup - Only emit tool calls that weren't already emitted during streaming
Let me implement this:
- Assistant
I apologize for the confusion. Let me use only the terminal tool going forward.
- Assistant
Let me carefully trace the issue. The key insight is in
finalize()- the conditionnot self.tool_calls_detectedmeans if streaming parser found ANY tool calls, the fallbackextract_tool_callswon't run, missing calls that the non-stream parser would catch.Let me implement the fix:') prev_close = previous_text.count('</tool_call>') if close_count > prev_close: return {'tool_calls': [{'index': 0, 'id': 'c1', 'type': 'function', 'function': {'name': 'fn1', 'arguments': '{}'}}]} return {'content': delta_text}
parser.extract_tool_calls_streaming = fake_streaming
def fake_extract(text, request=None): # Non-stream parser finds BOTH tool calls if '
- Assistant
Let me write a reproduce script first.") prev_closes = prev.count("</tool_call>") if closes > prev_closes and closes == 1: # First call found return {"tool_calls": [{"index": 0, "id": "c1", "type": "function", "function": {"name": "fn1", "arguments": "{}"}}]} elif closes > prev_closes and closes > 1: # Second call just completed - BUG: returns content instead of tool_calls return {"content": delta} if "", text, re.DOTALL) tc_list = [] for i, c in enumerate(calls): tc_list.append({"id": f"call_{i}", "name": "fn", "arguments": "{}"}) result.tools_called = len(tc_list) > 0 result.tool_calls = tc_list return result
parser = GapStreamingParser() cfg = _make_cfg(enable_auto_tool_choice=True, tool_parser_instance=parser) pp = StreamingPostProcessor(cfg, tools_requested=True) pp.reset()
- Assistant
Let me try again with a single bash terminal call. I need to be very careful to not include any XML-like patterns in my response.
- Assistant
Good, I confirmed the bug pattern. Let me now create a more realistic test case with actual XML markers:', text, re.DOTALL): tc_list.append({'id': f'call_{len(tc_list)}', 'name': 'fn1', 'arguments': m.group(1)}) for m in re.finditer(r'<function_call>(.*?)</function_call>', text, re.DOTALL): tc_list.append({'id': f'call_{len(tc_list)}', 'name': 'fn2', 'arguments': m.group(1)}) result.tools_called = len(tc_list) > 0 result.tool_calls = tc_list result.content = None return result def extract_tool_calls_streaming(self, prev, cur, delta, **kw): # Streaming only handles ') prev_closes = prev.count('</tool_call>') if closes > prev_closes: return {'tool_calls': [{'index': 0, 'id': 'c1', 'type': 'function', 'function': {'name': 'fn1', 'arguments': '{}'}}]} if 'hello<function_call>{"x":1}</function_call>'
Non-streaming
nr = parser.extract_tool_calls(full) print(f'Non-streaming found: {len(nr.tool_calls)} calls')
Streaming
events_during = pp.process_chunk(_make_output(full, finished=True)) tc = [e.tool_calls for e in events_during if e.type == 'tool_call' and e.tool_calls] tc_count = sum(len(x) for x in tc)
- Assistant
Let me write the test script to a file first, then run it.', text, re.DOTALL): tc_list.append({'id': 'c' + str(len(tc_list)), 'name': 'fn1', 'arguments': m.group(1)}) for m in re.finditer(r'alt_open(.*?)alt_close', text, re.DOTALL): tc_list.append({'id': 'c' + str(len(tc_list)), 'name': 'fn2', 'arguments': m.group(1)}) return ExtractedToolCallInformation( tools_called=len(tc_list) > 0, tool_calls=tc_list, content=None ) def extract_tool_calls_streaming(self, prev, cur, delta, **kw): # Streaming only recognizes ') return {'tool_calls': [{'index': 0, 'id': 'c1', 'type': 'function', 'function': {'name': 'fn1', 'arguments': '{}'}}]} if 'bye'
Non-streaming finds both
nr = parser.extract_tool_calls(full) print(f'Non-streaming: {len(nr.tool_calls)} calls')
Streaming
events_during = pp.process_chunk(_make_output(full, finished=True)) tc = sum(len(e.tool_calls) for e in events_during if e.type == 'tool_call' and e.tool_calls)
fe = pp.finalize() ftc = sum(len(e.tool_calls) for e in fe if e.type == 'tool_call' and e.tool_calls)
total = tc + ftc print(f'Streaming: {total} calls (during={tc}, finalize={ftc})') print(f'tool_calls_detected={pp.tool_calls_detected}')
if total < len(nr.tool_calls): print('BUG CONFIRMED') else: print('OK') ENDOFSCRIPT python /tmp/test_bug.py </tool_call>
- Assistant
Let me try a completely different approach - write the script using
echoto avoid XML-like patterns in my response. - Assistant
Good, so the finalize fallback works when
tool_calls_detectedis False. Now let me test the case where streaming detects the first call but misses the second (sotool_calls_detected=Trueprevents finalize from running): - Assistant
The fast path skipped the streaming parser because my markers don't contain
<or[. Let me use markers with angle brackets: - Assistant
Now I've confirmed the bug. When streaming detects some tool calls (setting
tool_calls_detected=True), thefinalize()method skips the fallbackextract_tool_calls, so any additional tool calls the streaming parser missed are lost.The fix:
- Track how many tool calls were emitted during streaming
- Remove the
not self.tool_calls_detectedgate fromfinalize() - Only emit tool calls that weren't already emitted
Let me implement this:
- Assistant
Now let me see the full picture of the code I need to modify:
- Assistant
Now let me implement the fix. I need to:
- Add
_streaming_tool_call_countto__init__andreset - Increment it in
_detect_tool_callswhen tool calls are emitted - In
finalize(), remove thenot self.tool_calls_detectedgate and only emit tool calls beyond the already-emitted count
Let me make the changes:
- Add
- Assistant
Let me add
_streaming_tool_call_countto the__init__andresetmethods. - Assistant
Let me use
sedto make the changes: - Assistant
Now let me add it to the
resetmethod too: - Assistant
Line 193 is in the
resetmethod. Let me add the counter reset there. - Assistant
Now I need to increment the counter in
_detect_tool_callswhen tool calls are found: - Assistant
Let me look at the context around line 575:
- Assistant
I need to increment the counter when tool calls are found in
_detect_tool_calls: - Assistant
Now I need to modify the
finalize()method. Let me see it: - Assistant
Let me see the full finalize method.
- Assistant
Now I need to modify the
finalizemethod. I need to:- Remove
not self.tool_calls_detectedfrom the condition - Only emit tool calls that weren't already emitted during streaming
- Remove
- Assistant
Now let me make the changes. I'll use Python to do the replacement precisely:
- Assistant
Let me verify the changes look correct.
- Assistant
Good, the changes look correct. Now let me verify the counter increment is in place:
- Assistant
Let me see the lines around the increment.
- Assistant
Good, the counter increment is in place. Now let me run the test again to verify the fix:
- Assistant
The fix works. Now let me also handle the same issue in the
_process_channel_routedand_process_with_reasoningpaths which also haveself.tool_calls_detectedpatterns. Let me also check the reasoning path: - Assistant
Now let me run all the existing tests to make sure I haven't broken anything:
- Assistant
All postprocessor tests pass. Let me also run the other relevant test suites:
- Assistant
All tests pass. Let me now create a more comprehensive test to cover all the edge cases mentioned in the issue:
- Assistant
All comprehensive tests pass. Let me also check that the channel-routed and reasoning paths have the proper counter tracking. Let me look at how those paths handle tool calls:
- Assistant
Let me look at lines 546-555 to see the context around the other instance of
tool_calls_detected = True. - Assistant
Now I need to also check the channel-routed and reasoning paths, since those also call
_detect_tool_calls. Let me look at how those methods are structured: - Assistant
Good - all three processing paths call
_detect_tool_callswhich has the counter increment. Now let me run all the tests that can run without the mlx dependency: - Assistant
That test file can't run due to mlx dependency. Let me run just the tests that can run:
- Assistant
All 274 tests pass. Let me verify the final state of my changes:
- Assistant
The diff looks clean and minimal. Let me now run a final comprehensive check to make sure everything is working:
- Assistant
All 274 tests pass. Let me clean up the temporary test files:
- Assistant
Let me verify my changes are clean:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.