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 using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to 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 understanding the repository structure and the issue at hand. The issue is about streaming dropping XML tool-call output that non-streaming parses correctly. I need to explore the repository to understand the codebase first.
Assistant
Let me explore the repository structure more and look for files related to streaming and XML tool-call parsing.
Assistant
Let me look at the vllm_mlx directory and tests directory to find code related to streaming and XML tool-call parsing.
Assistant
I see there's a tool_parsers directory which is likely relevant. Let me also look for streaming-related code. Let me explore these areas.
Assistant
I see there's an xlam_tool_parser.py file which might be related to XML tool calls. Let me look at the test files and the tool parsers to understand the issue better.
Assistant
Let me look at the streaming and tool parser tests to understand the issue better. The issue is about streaming dropping XML tool-call output that non-streaming parses correctly. Let me look at relevant test files and source code.
Assistant
Let me look at the abstract tool parser and the streaming pipeline to understand the full picture.
Assistant
Now let me look at how streaming works with tool calls. I need to find the streaming pipeline code. Let me also search for XML-related tool parsers since the issue mentions "XML tool-call output".
Assistant
Let me search for XML-style tool call patterns in the codebase:
Assistant
Let me look at the seed_oss_tool_parser.py since it likely has XML tool call handling, and the auto_tool_parser.py which may orchestrate streaming vs non-streaming.
The file might be too large. Let me try viewing it differently.
Assistant
The seed_oss_tool_parser.py is quite large. Let me look at more of it to understand the streaming logic.
Let me also look at the auto_tool_parser which is mentioned in the issue about streaming vs non-streaming behavior.
Assistant
Let me look at more of the seed_oss_tool_parser.py to understand its streaming implementation.
Assistant
Let me continue viewing the seed_oss_tool_parser.py to see the rest of the streaming logic:
Assistant
Now I have a good understanding of the seed_oss_tool_parser.py. This is an XML-based tool parser for Seed-OSS/GPT-OSS models. The issue is about streaming dropping XML tool-call output that non-streaming parses correctly.
Let me look at the auto_tool_parser to see how it orchestrates between streaming and non-streaming parsing.
Assistant
Let me look at the streaming pipeline to understand how tool calls are emitted during streaming:
Assistant
Let me look at the streaming pipeline and also search for where streaming handles tool calls. I need to understand how streaming and non-streaming parse tool calls differently.
Let me search for where the streaming output router and tool call handling happens.
Assistant
Let me explore the service/postprocessor.py and service/helpers.py to understand how streaming output is processed.
Assistant
Let me look at the postprocessor.py file in detail, especially around the _detect_tool_calls method and the streaming logic.
Assistant
Assistant
Let me search for test files related to tool calls and streaming:
Assistant
Let me look at the test files to understand what behavior is expected.
Assistant
Let me look at specific test cases to understand expected behavior:
Assistant
Let me look at the test_streaming.py file and also search for tests related to the specific issue:
Assistant
Let me look at the test file for the streaming postprocessor:
Assistant
Let me look at the test_postprocessor.py file to understand expected behavior.
Assistant
Let me look at the test_postprocessor.py file in more detail to understand the expected behavior for the finalize() method.
Assistant
Assistant
I need to run the existing tests to understand the current behavior and validate my fix. Let me try running the tests again.
Assistant
All tests pass. Let me look at the specific test that tests content after tool calls:
Assistant
Good, all 74 tests pass. Now let me write a reproduction script to confirm the issue, then implement the fix.
Assistant
Let me use bash to create the file properly:
Assistant
Let me run the reproduction script to confirm the issue exists:
Assistant
Let me look at how test_postprocessor.py handles imports:
Assistant
Let me update my test script to avoid the import issue:
Assistant
Let me run the reproduction script now.
Assistant
I need to fix the test to use proper tool call markers. Let me update it:
Assistant
Let me run the test to see what happens.
Assistant
Now I've confirmed the issue. The test shows:
tool_calls_detected is True after the first chunk
The second chunk returns empty events (because tool_calls_detected is True)
BUT the text IS being accumulated in tool_accumulated_text
The problem is in finalize(): it has the condition not self.tool_calls_detected which prevents the fallback from running
Let me look at the current finalize() code to understand what needs to change:
Assistant
I've confirmed the issue. The test shows that tool_accumulated_text IS being accumulated ('`
Assistant
Now I understand the issue. Let me analyze the code carefully.
The issue is in the finalize() method which has this condition:
python
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected # <-- This prevents fallback when streaming detected tool calls
and _has_plausible_markup
):
When tool_calls_detected is True (streaming detected SOME tool calls), the fallback doesn't run. But if the streaming parser missed some tool calls (e.g., because they were split across chunks), those missed tool calls won't be recovered.
Let me implement the fix:
Assistant
Now I understand the issue clearly. The problem is:
When tool_calls_detected is True, _detect_tool_calls() is never called again, so subsequent text isn't accumulated in tool_accumulated_text
The finalize() fallback also has not self.tool_calls_detected which prevents it from running
Let me implement the fix:
Assistant
Now I understand the issue clearly. Let me implement the fix:
The problem:
When tool_calls_detected is True, subsequent chunks are dropped without being accumulated in tool_accumulated_text
The finalize() fallback has not self.tool_calls_detected which prevents it from running when streaming already detected tool calls
This means tool calls that arrive after the first detected one are dropped and never recovered
The fix:
Accumulate ALL content in tool_accumulated_text in the _process_* methods before returning []
In finalize(), run the fallback regardless of tool_calls_detected state
Avoid emitting duplicate tool calls by tracking what was already emitted
Let me implement this:
Assistant
Now I understand the issue. Let me implement the fix:
Problem Analysis:
When tool_calls_detected is True, subsequent chunks in _process_* methods return [] without calling _detect_tool_calls(), so content isn't accumulated
finalize() has not self.tool_calls_detected condition which prevents fallback parsing when streaming already detected tool calls
This causes tool calls that arrive after the first one to be dropped
Fix Plan:
Always accumulate content in tool_accumulated_text even when tool_calls_detected is True
Track emitted tool calls in _emitted_tool_calls_set to avoid duplicates
In finalize(), run fallback regardless of tool_calls_detected, but only emit NEW tool calls
Assistant
Now I understand the issue clearly. Let me implement the fix:
Problem:
When tool_calls_detected is True, subsequent chunks in _process_* methods return [] without calling _detect_tool_calls(), so content isn't accumulated in tool_accumulated_text
finalize() has not self.tool_calls_detected which prevents fallback when streaming already detected tool calls
Tool calls arriving after the first one are dropped and never recovered
Fix:
Track emitted tool calls in _emitted_tool_calls_set to avoid duplicates
Accumulate content in _process_* methods even when tool_calls_detected is True
In finalize(), run fallback regardless of tool_calls_detected, but only emit NEW tool calls
Assistant
The user wants me to continue implementing the fix for the streaming tool call parsing issue. Let me use the bash_terminal tool to make the changes using sed commands.
Assistant
I need to continue implementing the fix for the streaming tool call parsing issue. Let me make the necessary changes to the postprocessor.py file step by step.
Assistant
The sed command inserted the code in the wrong place. Let me fix this by reverting and using the proper edit command.
Assistant
I need to continue implementing the fix. The issue is that streaming drops XML tool-call output that non-streaming parses correctly. Let me re-examine the code and make the proper changes.
The key changes needed are:
Track emitted tool calls to avoid duplicates in finalize() fallback
Accumulate content in process* methods even when tool_calls_detected is True
In finalize(), run fallback regardless of tool_calls_detected, but only emit NEW tool calls
Let me use the edit command properly.
Assistant
I need to continue implementing the fix. Let me make the necessary changes step by step.
First, let me add the _emitted_tool_calls_set tracking variable in __init__:
Assistant
Let me make the necessary changes step by step. First, I'll add the _emitted_tool_calls_set tracking variable:
Assistant
Let me try using sed to make the changes:
Assistant
Let me use sed to make the changes step by step:
Assistant
The user wants me to continue implementing the fix for the streaming tool call parsing issue. I've started making changes to the postprocessor.py file but the sed command didn't work correctly. Let me take a different approach and make all the changes at once using a Python script to modify the file.
Assistant
Let me continue implementing the fix. I'll use a Python script to make the changes more reliably:
Assistant
Let me verify the changes were applied correctly:
Assistant
The reproduction script passes. Let me now run the existing tests to make sure the fix doesn't break anything:
Assistant
Let me look at the failing test to understand the structure:
Assistant
I need to understand the structure of tool calls returned by the streaming parser. Let me check:
Assistant
I see the issue. The streaming parser returns tool calls with structure tc["function"]["name"] while the non-streaming parser returns tc["name"]. I need to handle both structures. Let me fix the code:
Assistant
I see the issue. The streaming parser returns tool calls in a different structure than the non-streaming parser. I need to handle both structures when tracking emitted tool calls:
Assistant
Now let me run the tests again to verify the fix:
Assistant
Let me check the current state of the file and fix it properly:
Assistant
Let me look at the current state and fix it properly:
Assistant
Let me debug this further to understand the actual structure:
Assistant
Let me take a different approach and debug the actual structure of the streaming parser output:
Assistant
Let me examine the streaming parser output structure and fix the issue properly:
Assistant
Let me make the code more defensive to handle all possible structures of tool calls returned by streaming parsers:
Assistant
Let me run the tests again to verify the defensive fix:
Assistant
All 74 tests pass. Let me verify the reproduction script still works and run additional tests:
Assistant
All tests pass. Let me also run the tool parser tests to make sure nothing is broken:
Assistant
All tests pass. Let me clean up the temporary test file and verify the final state of the changes:
Assistant
Let me verify the final state of my changes:
Assistant
Let me run the full test suite to verify all tests pass:
Assistant
All 208 tests pass. Let me review the changes I made to ensure they properly address the issue:
Summary of Changes
The issue was: "Streaming drops XML tool-call output that non-streaming parses correctly"
Root Cause:
When tool_calls_detected became True (streaming detected a tool call), subsequent chunks were dropped without being accumulated in tool_accumulated_text
The finalize() fallback method had not self.tool_calls_detected condition, preventing it from running when streaming had already detected tool calls
This meant tool calls arriving after the first detected one were never recovered
Fix Applied to vllm_mlx/service/postprocessor.py:
Assistant
The user wants me to submit my changes. Let me use the correct syntax for the submit command.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Now I have a much better understanding of the codebase. Let me understand the issue:
The issue is about streaming dropping XML tool-call output that non-streaming parses correctly.
Looking at the code:
Postprocessor.py - StreamingPostProcessor processes streaming engine output. It has:
_detect_tool_calls() method that calls self.tool_parser.extract_tool_calls_streaming() for incremental parsing
finalize() method that has a fallback to call self.tool_parser.extract_tool_calls() (non-streaming) if the streaming parser missed something
seed_oss_tool_parser.py - This is the XML-based tool parser for Seed-OSS/GPT-OSS models. It has:
extract_tool_calls() - full non-streaming parser that can parse complete XML
extract_tool_calls_streaming() - streaming parser that tries to emit tool calls incrementally
The key issue seems to be in the finalize() method in postprocessor.py. Let me look more carefully at what happens.
Looking at the finalize() method:
python
_fallback_text = self.tool_accumulated_text or self.accumulated_text
The problem might be that tool_accumulated_text is not being properly accumulated in all cases. Let me trace through the code:
In _detect_tool_calls():
python
if not self.tool_markup_possible and "<" not in content and "[" not in content:
self.tool_accumulated_text += content
return {"content": content}
So tool_accumulated_text is only accumulated when we're NOT in tool markup mode. Once self.tool_markup_possible is True, content goes directly to extract_tool_calls_streaming() but isn't added to tool_accumulated_text properly.
Wait, looking more carefully:
python
if not self.tool_markup_possible:
self.tool_markup_possible = True
tool_previous = self.tool_accumulated_text
self.tool_accumulated_text += content # This is called after tool_markup_possible is set
Actually, tool_accumulated_text IS being updated. Let me look at what happens when tool_calls_detected is True.
In _process_channel_routed():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # <-- THIS IS THE PROBLEM! When tool_calls_detected is True, it returns empty events!
And in _process_standard():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # <-- SAME ISSUE!
So when tool_calls_detected is True but the stream hasn't finished, the code returns [] (empty events). This means the streaming delta_text is never processed for more content.
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 look at the test files for clues about what the expected behavior is:
Now I understand the issue better. Let me look at the finalize() method in postprocessor.py more carefully.
Looking at the code again:
python
def finalize(self) -> list[StreamEvent]:
"""Finalize stream — flush remaining tool calls, emit corrections."""
events = []
_fallback_text = self.tool_accumulated_text or self.accumulated_text
_has_plausible_markup = bool(_fallback_text) and (
"<" in _fallback_text
or "{" in _fallback_text
or "[Calling" in _fallback_text
)
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
result = self.tool_parser.extract_tool_calls(
_fallback_text, request=self.request
)
...
The issue is that _fallback_text uses self.tool_accumulated_text first. But when tool_calls_detected is True, the streaming path returns [] for subsequent chunks (see _process_channel_routed and _process_standard). This means the remaining delta_text is never added to tool_accumulated_text.
Wait, let me re-read the flow:
When tool call is detected, tool_calls_detected is set to True
For subsequent chunks, _process_standard and _process_channel_routed return [] when tool_calls_detected is True
The delta_text in those chunks is never accumulated
So when finalize() runs, tool_accumulated_text might not contain all the text that was generated. The non-streaming parser can parse the full text but streaming misses parts of it.
Actually wait, let me look at this more carefully. The issue description says:
Streaming drops XML tool-call output that non-streaming parses correctly
This could mean:
Streaming fails to emit tool calls that non-streaming correctly extracts
Streaming stops processing too early and drops remaining content
Let me look at the seed_oss_tool_parser streaming logic more carefully. The issue might be in the extract_tool_calls_streaming method where it doesn't properly handle all cases.
Actually, I think I need to look at the issue from a different angle. Let me look at the seed_oss parser's streaming logic again to see where it might be dropping output.
Looking at seed_oss_tool_parser.py's extract_tool_calls_streaming:
When is_tool_call_started is True and we're looking for the function header
If we find the function name but not the closing >, we return None
When we find the function end token, we either emit a full tool call or an empty arguments one
The key issue might be when:
Tool calls are split across chunks
Multiple tool calls exist
The parser state gets desynced
Let me look at a specific scenario in the streaming code. In the seed_oss parser:
python
if self.json_closed and not self.in_function:
tool_ends = current_text.count(self.tool_call_end_token)
if tool_ends > self.current_tool_index:
self.current_tool_index += 1
...
return None
This advances to the next tool call. But what if the next tool call's content arrives in a later chunk and the parser needs to parse it?
The issue might be in how the streaming parser handles incomplete tool calls that need to be assembled from multiple chunks.
Actually, I think the key issue might be in the postprocessor's finalize() method. Let me look at what happens when the streaming parser emits a tool_call event - does it properly emit the remaining content?
Wait, looking at _detect_tool_calls():
python
if "tool_calls" in tool_result:
self.tool_calls_detected = True
return tool_result
When tool_calls are detected, subsequent chunks in _process_standard and _process_channel_routed return []:
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return []
This means ALL content after the first tool call detection is dropped. That's wrong!
For example, if the model outputs:
code
Let me help you.<tool_call>{"name":"read","arguments":{}}</tool_call> more text
The streaming would:
Detect "Let me help you." as content
Detect "<tool_call>{"name":"read","arguments":{}}" as a tool call
Drop "more text" because tool_calls_detected is True
But the non-streaming parser would correctly extract both the tool call AND the content.
Wait, but looking at the issue more carefully:
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.
The key requirements are:
Streaming must emit the same tool calls as non-streaming
Must handle calls split across chunks
Must handle multiple calls
Must finish with tool_calls
Reasoning mode must not alter recovery
Plain text or malformed markup must not create calls or abort the stream
So the issue is specifically about:
Streaming dropping tool calls that non-streaming recovers
The finalize() method needs to properly handle the case where streaming missed something
Let me re-read the finalize() code:
python
_fallback_text = self.tool_accumulated_text or self.accumulated_text
This uses tool_accumulated_text first. But tool_accumulated_text is only populated in _detect_tool_calls() when tool_markup_possible is False:
python
if not self.tool_markup_possible and "<" not in content and "[" not in content:
self.tool_accumulated_text += content
return {"content": content}
Once tool_markup_possible becomes True, content is NOT added to tool_accumulated_text. Instead it goes to extract_tool_calls_streaming().
But there's another issue. After tool calls are detected (tool_calls_detected = True), subsequent chunks just return [] and their content is never accumulated anywhere.
The fix should be:
When tool_calls_detected is True and the chunk is not finished, still accumulate the delta_text somewhere
In finalize(), use ALL accumulated text to do the fallback parsing
Let me look at the accumulated_text field which is set in process_chunk:
python
self.accumulated_text = ""
Wait, accumulated_text is initialized but never set in any of the process methods. Let me check...
The accumulated_text is not updated in process_chunk(). It's used in finalize():
python
_fallback_text = self.tool_accumulated_text or self.accumulated_text
But self.accumulated_text is never populated! It's always empty.
So the only way finalize() gets text to parse is through tool_accumulated_text, which is only populated in _detect_tool_calls() when we're NOT in tool markup mode.
The problem is:
When tool markup is detected, tool_markup_possible becomes True
Subsequent content goes to extract_tool_calls_streaming() but not to tool_accumulated_text
If the streaming parser fails to extract tool calls, finalize() has nothing to parse
The fix should be to accumulate ALL text in tool_accumulated_text so that finalize() can do fallback parsing.
Actually, let me look at this differently. The tool_accumulated_text IS being updated in _detect_tool_calls():
python
tool_previous = self.tool_accumulated_text
self.tool_accumulated_text += content # Always updates when tool_markup_possible is True
So once tool_markup_possible becomes True, content IS added to tool_accumulated_text. That's good.
But wait, what about when tool_calls_detected becomes True? In that case, _process_standard() returns [] without ever calling _detect_tool_calls() again. So subsequent chunks are NOT accumulated.
So the fix is:
When tool_calls_detected is True, we should still accumulate delta_text in tool_accumulated_text
Then finalize() can do fallback parsing
Let me also check if there are other places where text should be accumulated.
Looking at _process_channel_routed():
python
if self.tool_parser and content:
result = self._detect_tool_calls(content)
And _process_standard():
python
if self.tool_parser and delta_text:
result = self._detect_tool_calls(delta_text)
Both call _detect_tool_calls(). But after tool_calls_detected is True, both paths return [] before calling _detect_tool_calls():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # Returns without calling _detect_tool_calls!
So when tool_calls_detected is True and the chunk is not finished, the delta_text is completely lost. This is the bug.
The fix should be to:
Still accumulate the text even when tool_calls_detected is True
Let finalize() do the fallback parsing on all accumulated text
Let me verify by looking at the existing test:
python
def test_fallback_tool_detection_on_finalize(self):
"""Finalize detects tool calls when streaming detection missed them."""
...
# Accumulate some text without triggering streaming detection
pp.tool_accumulated_text = "<tool_call>{}"
This test shows that the intended behavior is for finalize() to detect tool calls when streaming missed them. But for this to work, ALL text needs to be in tool_accumulated_text.
Let me create a fix.
Actually, I need to re-examine more carefully. The issue is that:
When streaming parser successfully detects a tool call, tool_calls_detected becomes True
When tool_calls_detected is True, subsequent content is dropped without accumulation
When finalize() runs, it has partial text and can't recover what was dropped
The fix should be to accumulate ALL text (even after tool_calls_detected) so finalize() can do proper fallback parsing.
But wait, there's a nuance. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly". This means the streaming parser is NOT detecting some tool calls that the non-streaming parser CAN detect.
Looking at the seed_oss_tool_parser's streaming method, I see it has complex state management. If the state gets out of sync (e.g., due to split tokens), the streaming parser might not emit a tool_call when it should.
The finalize() fallback is supposed to handle this - it calls extract_tool_calls() (non-streaming) on the accumulated text. But if the accumulated text is incomplete (because subsequent chunks were dropped), the fallback also fails.
So the fix is:
Accumulate ALL delta_text in tool_accumulated_text, even after tool_calls_detected is True
Then finalize() can parse the complete text
Actually, looking at this more carefully, I think there's a second issue too. Even if we accumulate all text, the finalize() fallback has this check:
python
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
It only runs the fallback when not self.tool_calls_detected. But if streaming successfully detected a tool call but missed others, this fallback won't run.
So the fix should also change the condition to run fallback even when tool_calls_detected is True, or at least accumulate text for the fallback.
Let me think about this more carefully...
Actually, the cleanest fix might be:
Always accumulate delta_text in tool_accumulated_text in process_chunk()
In finalize(), always run the fallback parsing on the complete text
Use the non-streaming parser to extract ALL tool calls from the complete text
Let me implement this.
Wait, but I need to be more careful. The issue says "Streaming drops XML tool-call output that non-streaming parses correctly". The key problem is that streaming might miss tool calls that split across chunks.
Looking at the seed_oss_tool_parser streaming code, I see that it has complex state management. If the parser is in the middle of parsing a parameter and a new chunk arrives, it should continue parsing. But if the state is complex enough, it might miss the end of a tool call.
Actually, let me re-read the seed_oss parser's streaming method more carefully to see if there are specific bugs...
Looking at the method, I notice that when json_closed is True and we need to advance to the next tool:
python
if self.json_closed and not self.in_function:
tool_ends = current_text.count(self.tool_call_end_token)
if tool_ends > self.current_tool_index:
self.current_tool_index += 1
self.header_sent = False
self.param_count = 0
self.json_started = False
self.json_closed = False
if self.current_tool_index >= current_text.count(
self.tool_call_start_token
):
self.is_tool_call_started = False
return None
This returns None when advancing to the next tool. But it doesn't accumulate content for the new tool. The next call to extract_tool_calls_streaming should continue parsing from current_text, so this should be fine.
Let me look for other issues...
In the "content before tool calls" section:
python
if not self.is_tool_call_started:
if (
self.tool_call_start_token_id is not None
and self.tool_call_start_token_id in delta_token_ids
) or self.tool_call_start_token in delta_text:
self.is_tool_call_started = True
if self.tool_call_start_token in delta_text:
content_before = delta_text[
: delta_text.index(self.tool_call_start_token)
]
if content_before:
return {"content": content_before}
# Fall through to header parsing below instead of returning
# None — the function header may already be in current_text.
If the token ID check passes but the string check fails, is_tool_call_started becomes True but we fall through to header parsing. If there's no function header yet, we return None (which suppresses the chunk). But the content before the tool call hasn't been emitted!
Wait, actually, let me re-read:
python
if (
self.tool_call_start_token_id is not None
and self.tool_call_start_token_id in delta_token_ids
) or self.tool_call_start_token in delta_text:
self.is_tool_call_started = True
This only sets is_tool_call_started = True if either:
The start token ID is in the delta token IDs
The start token string is in the delta text
If neither condition is true, we fall through to:
python
else:
if (
current_text.rstrip().endswith(self.tool_call_end_token)
and delta_text.strip() == ""
):
return None
return {"content": delta_text}
So if we're not yet in tool call mode and the start token hasn't arrived, we emit the content. That's correct.
Let me look at another section. When the function header is found:
python
# Find current tool call portion
tool_starts_count = current_text.count(self.tool_call_start_token)
if self.current_tool_index >= tool_starts_count:
return None
This returns None if there's nothing more to parse for the current tool. But if the text has accumulated more tool call starts, this should advance.
Actually wait, I think there might be a bug here. The current_tool_index is not incremented when parsing content for the current tool. Let me check...
if self.json_closed and not self.in_function:
tool_ends = current_text.count(self.tool_call_end_token)
if tool_ends > self.current_tool_index:
self.current_tool_index += 1
So current_tool_index only advances when we find a new tool end. But tool_starts_count counts tool start tokens. If there are 2 tools, tool_starts_count would be 2. When current_tool_index reaches 2, we return None.
But wait, if the first tool's end hasn't arrived yet, current_tool_index stays at 0, and tool_starts_count might be 2. So we'd return None because 0 < 2 is True... no wait, the condition is if self.current_tool_index >= tool_starts_count, so if current_tool_index is 0 and tool_starts_count is 2, we'd continue parsing.
OK, I think the streaming parser logic is complex but mostly correct. The main issue is in the postprocessor:
When tool_calls_detected is True, subsequent chunks are dropped without accumulation
finalize() can't recover what was dropped
Let me focus on the postprocessor fix.
Actually, I want to trace through a specific scenario to confirm the issue.
Scenario: Model outputs "Hello<tool_call>{"name":"func","arguments":{}}"</tool_call>"
This test sets tool_accumulated_text directly (not through the streaming process). It also mocks has_pending_tool_call to return True. This is a unit test that only tests the finalize() method in isolation.
The actual bug would manifest in an integration test or real usage where:
Streaming fails to detect some tool calls
finalize() is called
finalize() should detect them via fallback, but doesn't because text wasn't accumulated
Let me look at the specific scenarios mentioned in the issue:
"calls split across chunks" - streaming might miss incomplete tool calls
"multiple calls" - streaming might only emit the first one
"finish with tool_calls" - streaming should end with tool_calls finish reason
The fix should be:
In process_chunk(), always accumulate delta_text in tool_accumulated_text
In finalize(), always run the fallback parsing (remove the not self.tool_calls_detected condition, or handle it differently)
Actually, thinking about this more, the cleanest approach would be:
Always accumulate ALL delta_text in tool_accumulated_text during streaming
In finalize(), run fallback parsing on the complete text
If fallback finds MORE tool calls than streaming detected, emit them
If streaming didn't detect any but fallback does, emit them with finish_reason="tool_calls"
Let me implement this fix.
Actually, I realize I need to understand the intended flow better. Let me look at how the finalization is supposed to work:
Flush remaining tool calls (tool calls that weren't emitted during streaming)
Emit corrections (fix streaming errors)
So the fix should:
Make sure ALL text is accumulated in tool_accumulated_text
Run fallback parsing on the complete text
Emit any tool calls that the streaming parser missed
Now let me think about the implementation:
In _process_standard():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # BUG: This drops the delta_text!
Fix:
python
if self.tool_calls_detected:
# Always accumulate text for finalize fallback
self.tool_accumulated_text += delta_text
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return []
Similarly for _process_channel_routed():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # BUG: This drops the content!
Fix:
python
if self.tool_calls_detected:
# Always accumulate text for finalize fallback
self.tool_accumulated_text += (content or "")
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return []
And in _process_with_reasoning():
python
if self.tool_calls_detected:
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return [] # BUG: This drops the content!
Fix:
python
if self.tool_calls_detected:
# Always accumulate text for finalize fallback
self.tool_accumulated_text += (content or "")
if output.finished:
return [
StreamEvent(
type="finish",
finish_reason="tool_calls",
tool_calls_detected=True,
)
]
return []
Now for the finalize() method, I need to ensure it runs the fallback even when tool_calls_detected is True. The current condition is:
python
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
I should change this to run the fallback regardless of tool_calls_detected, or at least handle the case where tool calls were detected during streaming but the non-streaming parser might find more.
Actually, thinking about it more carefully:
If tool_calls_detected is True, the streaming parser successfully found tool calls. The fallback might find the SAME tool calls (from the accumulated text). If the fallback finds MORE tool calls, we should emit those too.
But the current code only emits events when result.tools_called is True and not self.tool_calls_detected. We should change this to also handle the case where we want to emit additional tool calls.
Actually, looking at the issue description again:
Streaming must emit the same recovered XML tool calls as non-streaming
This means streaming should produce the same output as non-streaming. The finalize() fallback is supposed to make up for streaming's limitations.
So the fix should be:
Accumulate ALL text in tool_accumulated_text
In finalize(), run the fallback parsing
If the fallback finds tool calls, emit them (even if tool_calls_detected is True, to supplement missing ones)
But actually, I think the simplest fix is:
Accumulate ALL text
In finalize(), run the fallback and emit tool calls even if tool_calls_detected is True
Let me implement this.
Wait, but there's another subtlety. If tool_calls_detected is True and the fallback also finds tool calls, we'd be emitting the SAME tool calls twice. We need to avoid duplicates.
The cleanest approach:
Always accumulate text
In finalize(), run fallback
If not self.tool_calls_detected AND fallback finds tool calls, emit them with finish_reason="tool_calls"
If self.tool_calls_detected AND fallback finds MORE tool calls than streaming detected, emit the additional ones
Actually, let me look at this differently. The issue is:
Streaming drops tool calls that non-streaming recovers
The finalize() fallback is supposed to recover these
But finalize() doesn't run because tool_calls_detected is True
The simplest fix is to make finalize() always run the fallback, and have it emit tool calls regardless of whether streaming detected any. If streaming detected tool calls, the fallback should still run and potentially emit more.
But we need to handle the case where the fallback emits the SAME tool calls. We should avoid duplicate emissions.
One approach: Track which tool call names were already emitted, and only emit new ones in finalize().
Another approach: Run the fallback parsing BEFORE streaming starts. But that defeats the purpose of streaming.
Actually, I think the simplest approach is:
Accumulate ALL text in tool_accumulated_text
In finalize(), run fallback parsing
If fallback finds tool calls, emit them
If streaming already emitted tool calls, don't emit them again (but this is OK because the non-streaming parser might find MORE)
Actually, the current code has:
python
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
The not self.tool_calls_detected condition is there to avoid emitting duplicate tool calls. But this also prevents finalize() from running when streaming detected some tool calls but missed others.
I think the fix should be:
Remove the not self.tool_calls_detected condition
Instead, track which tool calls were already emitted
Only emit NEW tool calls in finalize()
Or simpler:
Keep the not self.tool_calls_detected condition
But ALWAYS accumulate text so finalize() can parse it
If streaming detects tool calls, finalize() won't run the fallback (which is fine, because streaming handled it)
If streaming doesn't detect tool calls but finalize()'s fallback does, emit them
But wait, the issue is specifically about streaming MISSING tool calls. So case 4 is the important one.
Actually, 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.
So the issue is:
Streaming drops tool calls
Non-streaming correctly parses them
Streaming should emit the same tool calls
This means the problem is in the streaming parser, not just in the postprocessor. But the postprocessor's finalize() fallback is supposed to compensate for streaming's limitations.
The fix should ensure that:
All text is accumulated
finalize() runs the fallback
The fallback recovers what streaming missed
Let me focus on the two changes:
Accumulate ALL text in process_chunk()
Run fallback in finalize() even when tool_calls_detected is True (but only emit NEW tool calls)
For #2, I'll change the condition to:
python
if (
self.tool_parser
and _fallback_text
and _has_plausible_markup
):
And then check if the tool calls are already emitted:
python
if result.tools_called:
# Check if these tool calls were already emitted
existing_names = set()
# We'd need to track which tool calls were emitted
# ...
# Emit any new tool calls
for new_call in new_tool_calls:
if new_call not in existing_names:
events.append(...)
Actually, tracking emitted tool calls is complex. Let me think of a simpler approach.
Simpler approach:
Accumulate ALL text in tool_accumulated_text
In finalize(), run the fallback on the complete text
If not self.tool_calls_detected, emit all tool calls with finish_reason="tool_calls"
If self.tool_calls_detected, emit any ADDITIONAL tool calls that weren't already emitted
For #4, we can compare the tool calls found by the fallback with what streaming already emitted. But we'd need to track what was emitted.
Alternatively, we can always run the fallback in finalize() and emit tool calls. The risk is duplicate emissions, but that's better than missing tool calls.
Actually, looking at the test test_fallback_tool_detection_on_finalize, it expects:
This test only has ONE event in the finalize output. If we always run the fallback, we might emit tool calls even when streaming already did, which would cause duplicates.
Let me think about this differently. The test shows that finalize() is expected to emit tool calls when streaming didn't detect them. The not self.tool_calls_detected condition ensures we don't emit duplicates.
But the bug is: when streaming DOES detect some tool calls but misses others, the fallback doesn't run and we lose the missed ones.
So the fix should be more nuanced:
Accumulate ALL text
Run the fallback
Compare tool calls from fallback with what streaming emitted
Only emit NEW tool calls
But we don't track what streaming emitted. We only have tool_calls_detected which is a boolean.
Actually, looking at the StreamEvent structure:
python
StreamEvent(
type="tool_call",
tool_calls=result["tool_calls"],
finish_reason="tool_calls" if output.finished else None,
tool_calls_detected=True,
)
Each StreamEvent has a tool_calls list. We could compare these lists.
But this is getting complicated. Let me think of the simplest fix that addresses the issue.
Simplest fix:
Accumulate ALL text in tool_accumulated_text in process_chunk() (even when tool_calls_detected is True)
In finalize(), run the fallback regardless of tool_calls_detected
Compare the tool calls found by fallback with what was already emitted
Only emit NEW tool calls
For step 3, we'd need to track what was emitted. One way is to keep a list of emitted tool call IDs.
Actually, let me re-examine the issue. The problem is:
Streaming fails to emit some tool calls
finalize() should recover them
But finalize() doesn't run because tool_calls_detected is True
The simplest fix: Always accumulate text, and always run the fallback in finalize(). If the fallback finds tool calls that weren't already emitted, emit them.
To track what was already emitted, we can store the tool call names/IDs that were detected by streaming:
python
# After emitting tool_calls in _detect_tool_calls():
self._emitted_tool_call_ids = set()
for tc in tool_result["tool_calls"]:
self._emitted_tool_call_ids.add(tc["id"])
Then in finalize():
python
if result.tools_called:
for tc in result.tool_calls:
if tc["id"] not in self._emitted_tool_call_ids:
# Emit this new tool call
...
This is cleaner. Let me implement this.
But wait, there's another issue. When tool_calls_detected is True and we're in the middle of streaming, _process_standard() returns [] without accumulating anything. So the tool_accumulated_text doesn't contain all the text.
Let me trace through a concrete scenario:
Model output: "Hello<tool_call>{"name":"func","arguments":{}}"</tool_call> More content"
Streaming chunks: ["He", "llo", "<tool_call>", '{"name":"func","arguments":{}}', " More content", ""]
In this case, the second tool call is completely missed. The finalize() fallback would parse "<tool_call>{"name":"func1","arguments":{}}" but not the second tool call.
This is the bug! When tool_calls_detected is True, subsequent chunks are dropped, so the second tool call is never accumulated.
The fix should be:
In _process_standard(), _process_channel_routed(), and _process_with_reasoning(), always accumulate delta_text or content in tool_accumulated_text before returning []
In finalize(), run the fallback even when tool_calls_detected is True
Only emit NEW tool calls (those not already emitted)
Let me implement this.
Wait, actually, I just realized that there might be a simpler approach. Looking at the code:
The tool_accumulated_text is used for the fallback. If we always accumulate text in tool_accumulated_text, the fallback can parse the complete text.
And for the tool_calls_detected condition:
python
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
We need to remove or modify this condition. If streaming detected tool calls, but the fallback finds MORE tool calls, we should emit them.
But we also need to avoid emitting the SAME tool calls twice. To do this:
Track which tool call names were already emitted
Only emit NEW tool calls in finalize()
Let me implement this.
Actually, I realize I'm overcomplicating this. Let me re-read the issue:
Streaming drops XML tool-call output that non-streaming parses correctly
The key word is "drops". The issue is that streaming DROPS output. The fix should ensure that streaming doesn't drop output.
The simplest fix:
Always accumulate text in process_chunk()
Run the fallback in finalize() on the complete text
If not tool_calls_detected and fallback finds tool calls, emit them
If tool_calls_detected and fallback finds ADDITIONAL tool calls, emit the additional ones
For step 4, we need to track what was emitted. Let me implement this.
Actually, thinking about this more, I realize that the cleanest fix is to always accumulate text, and to have finalize() run the fallback regardless of tool_calls_detected. The fallback can then emit tool calls, and we need to avoid duplicates.
One way to avoid duplicates: track the set of emitted tool call names, and only emit NEW ones.
But actually, tool calls might have the same name (e.g., multiple calls to the same function with different arguments). So we can't just compare names.
A better approach: track the set of emitted tool call IDs, and only emit NEW ones.
But this requires emitting tool call IDs during streaming. Looking at the code, the streaming parser generates IDs via _generate_tool_id(). We'd need to track these.
Actually, let me look at how the streaming parser emits tool calls:
The streaming parser assigns a tool call ID. We could track these IDs in the postprocessor.
OK let me think about this differently. The core issue is:
Streaming misses some tool calls
finalize() should recover them
But finalize() has conditions that prevent it from running
The simplest fix is:
Always accumulate text (so finalize() has complete text to parse)
Run the fallback regardless of tool_calls_detected
Compare the tool calls from fallback with what streaming already emitted
Only emit NEW tool calls
For step 3-4, we need to track what streaming emitted. We can store the list of emitted tool calls:
python
self._emitted_tool_calls: list[dict] = []
Then in _detect_tool_calls():
python
if "tool_calls" in tool_result:
self.tool_calls_detected = True
self._emitted_tool_calls.extend(tool_result["tool_calls"])
return tool_result
And in finalize():
python
if result.tools_called:
# Compare with emitted tool calls
emitted_names = set(tc["function"]["name"] for tc in self._emitted_tool_calls)
emitted_args = set(tc["function"]["arguments"] for tc in self._emitted_tool_calls)
for i, tc in enumerate(result.tool_calls):
key = (tc["function"]["name"], tc["function"]["arguments"])
if key not in zip(emitted_names, emitted_args):
# This is a NEW tool call
events.append(StreamEvent(...))
Actually, this comparison is getting complex. Let me use a simpler approach: track the count of tool calls emitted, and only emit NEW ones in finalize().
Wait, but this doesn't work if streaming emitted 2 tool calls but the fallback finds 3.
OK, let me use a different approach. Track the set of (name, arguments) tuples that were emitted. In finalize(), only emit tool calls that weren't already emitted.
python
self._emitted_tool_calls_set: set = set()
Then in _detect_tool_calls():
python
if "tool_calls" in tool_result:
self.tool_calls_detected = True
for tc in tool_result["tool_calls"]:
# Use name and arguments as the key
key = (tc["function"]["name"], tc["function"]["arguments"])
self._emitted_tool_calls_set.add(key)
return tool_result
And in finalize():
python
if result.tools_called:
for i, tc in enumerate(result.tool_calls):
key = (tc["function"]["name"], tc["function"]["arguments"])
if key not in self._emitted_tool_calls_set:
events.append(StreamEvent(...))
self._emitted_tool_calls_set.add(key)
This is cleaner. Let me implement this.
But actually, I realize that this approach might be too aggressive. If streaming correctly emits tool calls, and finalize() parses the same text and finds the same tool calls, we'd be comparing and finding they're the same, so we wouldn't emit duplicates. But the comparison might fail due to whitespace or other formatting differences.
A safer approach: Only run the fallback in finalize() when not tool_calls_detected. But also, always accumulate text so that the fallback has complete text to parse.
Wait, I think I've been overthinking this. Let me re-read the issue:
Streaming drops XML tool-call output that non-streaming parses correctly
The key issue is "drops". The streaming parser is DROPPING output. This happens in two ways:
When tool_calls_detected is True, subsequent chunks are dropped
When the streaming parser returns None (suppressed), the content might be lost
For #1, the fix is to always accumulate text.
For #2, the streaming parser should return {"content": delta_text} when it doesn't find a tool call, not None.
Looking at _detect_tool_calls():
python
if tool_result is None:
return None # inside tool markup
When the streaming parser returns None, _detect_tool_calls() also returns None, and the postprocessor suppresses the event. This means the content is lost.
So None means the content is inside tool markup and should be suppressed. This is intentional for content that's part of a tool call (e.g., the function name "read" is part of a tool call, not separate content).
But for content AFTER the tool call is complete (like "more text" after the tool call), the streaming parser should return {"content": "more text"}, not None.
OK, I think the issue is specifically about the case where tool_calls_detected is True and subsequent chunks are dropped. Let me focus on that.
The fix:
Always accumulate delta_text/content in tool_accumulated_text even when tool_calls_detected is True
In finalize(), run the fallback and emit any NEW tool calls
Let me implement this.
Actually, I just realized there's an even simpler fix. Looking at the finalize() method:
python
def finalize(self) -> list[StreamEvent]:
events = []
_fallback_text = self.tool_accumulated_text or self.accumulated_text
...
if (
self.tool_parser
and _fallback_text
and not self.tool_calls_detected
and _has_plausible_markup
):
The tool_accumulated_text is built up by _detect_tool_calls(). But when tool_calls_detected is True and subsequent chunks return [], they're never accumulated.
The fix is to accumulate ALL delta_text in tool_accumulated_text in process_chunk(), and also to run the fallback in finalize() even when tool_calls_detected is True.
For the latter, I need to track what was already emitted to avoid duplicates. Let me use the approach of tracking emitted (name, arguments) pairs.
Let me now implement the fix:
In StreamingPostProcessor.__init__(), add:
python
self._emitted_tool_calls_set: set = set()
In _detect_tool_calls(), track emitted tool calls:
python
if "tool_calls" in tool_result:
self.tool_calls_detected = True
for tc in tool_result["tool_calls"]:
key = (tc["function"]["name"], tc["function"]["arguments"])
self._emitted_tool_calls_set.add(key)
return tool_result
In _process_standard(), _process_channel_routed(), and _process_with_reasoning(), always accumulate text:
python
if self.tool_calls_detected:
self.tool_accumulated_text += (delta_text or content or "")
...
In finalize(), run the fallback and emit NEW tool calls:
python
if result.tools_called:
for i, tc in enumerate(result.tool_calls):
key = (tc["function"]["name"], tc["function"]["arguments"])
if key not in self._emitted_tool_calls_set:
events.append(StreamEvent(...))
self._emitted_tool_calls_set.add(key)
This is the approach I'll take. Let me implement it.
Hmm, wait. Let me re-read the code more carefully to understand the exact flow.
In process_chunk():
python
def process_chunk(self, output: GenerationOutput) -> list[StreamEvent]:
delta_text = output.new_text
if not delta_text:
# Handle finish-only chunks
if output.finished:
return [self._make_finish_event(output)]
return []
# Step 1: Separate content from reasoning
if output.channel is not None:
return self._process_channel_routed(delta_text, output)
if self.reasoning_parser and self.enable_thinking is not False:
return self._process_with_reasoning(delta_text, output)
return self._process_standard(delta_text, output)
So the flow is:
process_chunk() calls one of the three _process_*() methods
Each of those methods might call _detect_tool_calls()
And the three _process_*() methods all have this pattern:
python
if self.tool_calls_detected:
if output.finished:
return [StreamEvent(type="finish", ...)]
return []
This pattern drops the delta_text/content when tool_calls_detected is True.
The fix should:
Accumulate the delta_text/content before returning []
Let finalize() run the fallback and emit any NEW tool calls
Let me now implement the fix.
Actually, I want to be more careful about the fix. The issue says:
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.
So the fix should ensure that:
All tool calls are emitted (not dropped)
Tool calls split across chunks are handled
Multiple tool calls are handled
The stream finishes with tool_calls
The finalize() method is supposed to handle #4 by emitting finish_reason="tool_calls". But for #1-3, we need to fix the streaming parser and the postprocessor.
Let me focus on the postprocessor fix, since the streaming parser (seed_oss_tool_parser.py) has complex state management that's harder to fix.
OK let me just implement the fix now. The key changes are:
Always accumulate text in tool_accumulated_text
Track emitted tool calls to avoid duplicates
Run fallback in finalize() even when tool_calls_detected is True
Let me start writing the code.
Wait, before I implement the fix, let me run the existing tests to make sure I understand the current behavior.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /Rapid-MLX && python -m pytest tests/test_postprocessor.py -v --tb=short 2>&1 | head -100
</tool_call>
Added _emitted_tool_calls_set tracking - A set to track which tool calls (by name+arguments) were already emitted during streaming, to avoid duplicates in the finalize fallback
Accumulate ALL text in tool_accumulated_text - In all three _process_* methods (_process_channel_routed, _process_with_reasoning, _process_standard), when tool_calls_detected is True, we now accumulate the delta_text/content before returning []
Run finalize fallback regardless of tool_calls_detected - Removed the not self.tool_calls_detected condition from the finalize fallback
Only emit NEW tool calls in finalize - The finalize fallback now compares tool calls from the non-streaming parser against already-emitted ones and only emits new ones
Defensive tool call extraction - Made the code more robust to handle different tool call structures from different streaming parsers (some use tc["function"]["name"], others use tc["name"])