Skip to content

fix(core): route streaming tool call chunks by protocol index to prevent null tool names - #2205

Open
chickenlj wants to merge 3 commits into
1.xfrom
fix/streaming-tool-call-index-routing
Open

chickenlj wants to merge 3 commits into
1.xfrom
fix/streaming-tool-call-index-routing

Conversation

@chickenlj

Copy link
Copy Markdown
Collaborator

Fixes #1237

Summary

In streaming mode, OpenAIResponseParser discarded the protocol-level tool_calls[].index of each delta, so ToolCallsAccumulator had to merge argument fragments purely via lastToolCallKey order heuristics. When a model or gateway never sends function.name in any chunk (observed with Qwen3-14b behind an OpenAI-compatible gateway), or sends it after argument fragments, the accumulated tool call ended up with a null name. That block was persisted into memory, and every subsequent request logged ToolUseBlock has null id or name, skipping, leaving the ReAct agent stuck in a retry loop until token exhaustion. This mirrors the design of the Python implementation, which keys streaming tool call accumulation by tool_call.index and therefore does not exhibit this bug.

  • OpenAIResponseParser now propagates tool_calls[].index on both named chunks and fragments via block metadata (ToolUseBlock.METADATA_STREAM_INDEX). Fragments still carry no fabricated id (an earlier attempt, fix(ToolCallsAccumulator): fallback to 'unknown_tool' for null tool names and use stable synthetic IDs for streaming tool calls #1238, fabricated ids from the index, which split one tool call into two builders whenever the first chunk carried a real id).
  • ToolCallsAccumulator uses the stream index as the primary routing key, so all chunks of the same tool call converge on one builder regardless of id/name presence. This also fixes late-arriving names and interleaved parallel tool call deltas. Blocks without the index (other providers' parsers) keep the legacy routing path unchanged.
  • buildAllToolCalls() drops builders whose name never arrived, with a diagnostic warning, instead of emitting an unexecutable block with a null name into memory. The internal routing metadata is stripped from the final block.

Test plan

  • Standard stream (first chunk carries id+name, fragments carry neither): merged into a single correct call, no regression
  • Name never arrives (gateway strips function.name): call dropped with warning, no null-name block emitted
  • Name arrives after argument fragments: merged into a single call with full arguments
  • Interleaved parallel tool call deltas: arguments routed to the correct call by index
  • Blocks without stream index (legacy parsers): behavior unchanged
  • Full agentscope-core suite: 3821 tests, 0 failures

…ent null tool names

In streaming mode, argument fragments were merged into tool calls purely
via lastToolCallKey heuristics because the parser discarded the
tool_calls[].index of each delta. When a model or gateway never sends
function.name (or sends it after argument fragments), the accumulated
tool call ended up with a null name, was persisted in memory, and then
skipped with "ToolUseBlock has null id or name" on every subsequent
request, stalling the ReAct loop.

Propagate the protocol-level index through block metadata and let the
accumulator use it as the primary routing key, so all chunks of the same
tool call converge on one builder regardless of id/name presence. Tool
calls whose name never arrived are now dropped with a warning at build
time instead of polluting memory. Blocks without the index keep the
legacy routing behavior.
@codecov

codecov Bot commented Jul 15, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.87879% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/core/agent/accumulator/ToolCallsAccumulator.java 86.20% 2 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a streaming-mode tool-call accumulation bug where OpenAI-compatible providers may omit function.name (and sometimes send it late), previously causing ToolUseBlock instances with null names to be persisted and subsequently skipped, stalling ReAct execution. It also standardizes LF line endings across platforms to avoid Spotless CRLF/LF mismatches.

Changes:

  • Propagates protocol tool_calls[].index through OpenAIResponseParser into ToolUseBlock metadata and uses it in ToolCallsAccumulator as the primary routing key for streaming tool-call deltas.
  • Prevents persisting unexecutable tool calls by dropping accumulated builders whose tool name never arrived, and strips the routing metadata from final accumulated blocks.
  • Adds tests covering standard streaming, late-arriving names, missing names, interleaved parallel calls, and legacy behavior without stream index; enforces LF line endings via Spotless + .gitattributes.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pom.xml Configure Spotless to use UNIX line endings for consistent formatting across platforms.
agentscope-distribution/agentscope-bom/pom.xml Same Spotless line-ending normalization for the BOM module.
agentscope-dependencies-bom/pom.xml Same Spotless line-ending normalization for the dependencies BOM module.
agentscope-core/src/main/java/io/agentscope/core/message/ToolUseBlock.java Introduce METADATA_STREAM_INDEX for internal streaming routing.
agentscope-core/src/main/java/io/agentscope/core/formatter/openai/OpenAIResponseParser.java Attach stream index metadata to tool-call blocks and fragments during chunk parsing.
agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java Route streaming tool-call chunks by stream index; drop nameless calls; strip routing metadata.
agentscope-core/src/test/java/io/agentscope/core/formatter/openai/OpenAIResponseParserTest.java Add coverage asserting stream-index metadata propagation on named chunks and fragments.
agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulatorTest.java Add coverage for stream-index routing, late names, nameless call dropping, and legacy behavior.
.gitattributes Enforce LF for text files and mark binaries to avoid line-ending normalization.

Comment on lines +189 to +205
// 0. Prefer the protocol-level stream index when the parser provided one
Integer streamIndex = getStreamIndex(block);
if (streamIndex != null) {
String key = streamIndexToKey.get(streamIndex);
if (key == null) {
// First chunk for this index: prefer the real tool ID as key,
// otherwise derive a stable key from the index itself
if (block.getId() != null && !block.getId().isEmpty()) {
key = block.getId();
} else {
key = "stream_index:" + streamIndex;
}
streamIndexToKey.put(streamIndex, key);
}
lastToolCallKey = key;
return key;
}
Comment on lines +289 to +295
log.warn(
"Dropping accumulated tool call without a name (id={},"
+ " arguments={}). The model or gateway did not send"
+ " function.name in any streaming chunk.",
builder.toolId,
builder.rawContent);
return false;

@AgentScopeJavaBot AgentScopeJavaBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI Review

This PR fixes a real streaming bug (issue #1237): when OpenAI-compatible streaming responses omit function.name from every chunk, ToolCallsAccumulator previously produced a ToolUseBlock with a null name, stalling the agent. The fix has three coordinated parts: (1) OpenAIResponseParser now propagates tool_calls[].index into ToolUseBlock metadata, (2) ToolCallsAccumulator uses the protocol stream index as the primary routing key for chunk merging, and (3) buildAllToolCalls() defensively drops builders whose name never arrived. The core fix is well-architected, correctly solves the described problem, and includes thorough unit tests (9 new tests covering index routing, parallel calls, fragment merging, and nameless-call dropping). Note: the PR also bundles unrelated changes (.gitattributes, BOM pom entries, Claw controller WorkspaceManager fixes) that should ideally be in separate commits/PRs.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@AgentScopeJavaBot AgentScopeJavaBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI Review

This PR fixes a real streaming bug (issue #1237): when OpenAI-compatible streaming responses omit function.name from every chunk, ToolCallsAccumulator previously produced a ToolUseBlock with a null name, stalling the agent. The fix has three coordinated parts: (1) OpenAIResponseParser now propagates tool_calls[].index into ToolUseBlock metadata, (2) ToolCallsAccumulator uses the protocol stream index as the primary routing key for chunk merging, and (3) buildAllToolCalls() defensively drops builders whose name never arrived. The core fix is well-architected, correctly solves the described problem, and includes thorough unit tests (9 new tests covering index routing, parallel calls, fragment merging, and nameless-call dropping). Note: the PR also bundles unrelated changes (.gitattributes, BOM pom entries, Claw controller WorkspaceManager fixes) that should ideally be in separate commits/PRs.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Solid, well-scoped fix with good tests — routing streaming tool-call deltas by the protocol-level tool_calls[].index is the right answer, and stripping the internal key before the accumulated block is persisted is a nice touch. My concerns are edge cases and packaging, not the core logic: mixed deltas with/without an index can still split one tool call, the new silent drop can turn a stalled agent into a confident wrong answer, the drop warning logs raw tool arguments, and the repo-wide EOL migration plus the three-controller copy-paste should not ride along in a core bugfix PR.

Commenting only (not approving) so the edge cases can be answered first; CI is green and the CLA is signed.

} else {
key = "stream_index:" + streamIndex;
}
streamIndexToKey.put(streamIndex, key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Mixed chunks with/without index can split one tool call into two builders.

determineKey gives the stream index top priority, so the first indexed chunk of a call binds index N to a key. If that first chunk carries no id, the key becomes "stream_index:N". A later chunk of the same call that omits index (some OpenAI-compatible gateways only attach it to the opening delta) but does carry the real call_x id then falls through to branch 1 and creates a second builder keyed "call_x" — the arguments end up split across two blocks, and after the new name filter one of them is dropped.

Would be safer to keep a reverse id -> key binding when an index is registered, e.g.:

if (block.getId() != null && !block.getId().isEmpty()) {
    key = block.getId();
    // remember that this id is already owned by an index-derived key
    knownIdToKey.put(block.getId(), key);
}

and consult it in branch 1 before creating a new builder. If you can guarantee index is present on every delta for a given provider, a comment saying so (plus a test for the mixed case) would be enough to close this out.

return true;
}
log.warn(
"Dropping accumulated tool call without a name (id={},"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Don't log the accumulated arguments.

builder.rawContent is the raw tool-argument JSON of the dropped call. Tool arguments routinely carry credentials, user PII, or file contents, and this repo's review guidance is explicit that API keys must not leak into logs. It is also unbounded in length. Suggest logging only the size (and never the payload):

log.warn(
        "Dropping accumulated tool call without a name (id={}, argumentBytes={})."
                + " The model or gateway did not send function.name in any streaming chunk.",
        builder.toolId,
        builder.rawContent.length());

return builders.values().stream()
.filter(
builder -> {
if (builder.hasName()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Dropping silently converts a stalled agent into a wrong answer.

Before this change a nameless block reached ReasoningContext.buildFinalMessage() and was skipped later (the loop you describe in the PR body). Now the call disappears from the returned list, so if it was the only content of the turn the assistant message degrades to plain text and the ReAct loop treats it as a final answer — the user gets a confident non-answer instead of an error. That is a better failure than an infinite retry, but not a great one.

Could this surface something actionable? Options, cheapest first:

  1. keep the warn but also set a flag on the accumulator (e.g. isDiscardedCount() > 0) so ReActAgent can emit a GenerateReason/error message such as "the model requested a tool call but the provider stream did not deliver its name";
  2. or route the malformed arguments into a synthetic tool result with an error the model can correct on the next iteration.

Either way the user-visible difference (silent text answer vs. explicit failure) deserves a test — the current testDropToolCallWithoutName only asserts the empty list.

* same tool call. This key is internal routing information and is stripped from the final
* accumulated block.
*/
public static final String METADATA_STREAM_INDEX = "streamToolCallIndex";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] New public metadata key is visible on per-chunk blocks, not only internally.

ToolCallsAccumulator.build() strips streamToolCallIndex from the accumulated block, which is right. But the raw chunk blocks still carry it, and those are handed straight to users on paths like LegacyHookDispatcher.fireReasoningChunk (where accumulatedContent falls back to the raw tub when the accumulator returns null) and to any streaming event consumer that persists chunk metadata. So the new key becomes part of what third-party code sees, even though the javadoc calls it "internal routing information".

Two small follow-ups worth considering: state in the javadoc that consumers must not rely on or persist this key (it is not part of the wire format and could be renamed), and if you prefer a hard guarantee, strip it where the chunk is emitted instead of only at aggregation time.

}
if (toolIndex != null) {
metadata.put(
ToolUseBlock.METADATA_STREAM_INDEX, toolIndex);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Only the OpenAI-compatible parser propagates the index.

The accumulator now depends on METADATA_STREAM_INDEX, but every other parser (dashscope, anthropic, gemini, ollama, …) still relies on the old id/name/lastToolCallKey heuristics — which is exactly the path this PR shows to be unreliable. Fine as a scoped fix (the new testLegacyRoutingWithoutStreamIndex locks the fallback in), but please note in the PR description that non-OpenAI providers are still exposed to the null-name bug, so the follow-up can be tracked rather than rediscovered.

Comment thread .gitattributes
@@ -0,0 +1,21 @@
# Ensure consistent LF line endings across platforms (Windows, Linux, macOS)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Warning] Repo-wide line-ending policy inside a core bugfix PR.

* text=auto eol=lf changes checkout output for every contributor and every existing file, which is a much larger blast radius than the streaming fix this PR is about (and a spotless lineEndings=UNIX change in three pom.xml files on top of it). If someone has a dirty Windows checkout, the renormalisation can look like a mass edit in their next git diff.

Happy with the change on its own merits, but it should be its own PR with a note telling contributors to re-clone or run git add --renormalize . once — reviewers of the tool-call fix should not have to sign off on an EOL migration.

private static WorkspaceManager newWorkspaceManager(Path workspace) {
return new WorkspaceManager(workspace, new LocalFilesystem(workspace, true, 10, null));
return new WorkspaceManager(
workspace, new LocalFilesystem(workspace, true, 10, null), null);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Same three-line fix copy-pasted into three controllers.

new WorkspaceManager(workspace, new LocalFilesystem(...), null) with an identical 6-line comment now appears in AgentSkillsController, AgentToolsController and AgentWorkspaceController. The intent (avoid opening a WorkspaceIndex that nobody closes) is clear, but nothing stops a fourth call site from using the leaking 2-arg constructor again. Consider one shared factory (ClawWorkspaceManagers.forRequest(workspace)), or better: give WorkspaceManager a close()-friendly try-with-resources use in these per-request paths so the fix cannot be forgotten. Unrelated to the streaming change — another argument for splitting this PR.

assertEquals("call_1", toolCall.getId());
assertEquals("get_weather", toolCall.getName());
assertEquals("{\"city\":\"Beijing\"}", toolCall.getContent());
assertEquals("Beijing", toolCall.getInput().get("city"));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Info] Test coverage is good; two cases still missing.

Index routing, late-arriving name, interleaved parallel calls, metadata stripping and the legacy fallback are all covered — thank you for that. The gaps map to the findings above:

  1. mixed stream where the first delta has index but no id and a later delta has the id but no index (should stay one tool call);
  2. buildAggregated() / final-message behaviour when all calls are dropped, i.e. what the agent actually returns to the user.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/model Model providers and formatters bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants