Repository navigation
fix(anthropic): preserve parallel tool call batches - #4019
Conversation
## Problem
Non-streaming Anthropic tool responses set `ToolUseBlock.content` using
`JsonValue.toString()`. Non-empty arguments can become Java-style map
text such as `{store_id=S001, month=2026-10}` instead of JSON. The agent
accumulator rejects those arguments as malformed, so tools do not
execute even though the API request succeeds.
This independent bug was reported during validation of #4019:
#4018 (comment).
This PR is based on current upstream main and does not include or depend
on #4019.
## Changes
- Serialize the already-parsed argument map with the existing JSON
codec, keeping `input` and `content` consistent.
- Add regression coverage using real SDK-deserialized non-streaming
responses through ReAct accumulation, tool execution, and the next model
turn. Cover non-empty arguments, nested objects/arrays/null values, and
empty objects.
ningmao-hlyz
left a comment
There was a problem hiding this comment.
Verified on the PR head: converter tests 38/38, module tests 256 with 0 failures; the new regression fails on a7322248 with expected: <6> but was: <10>, matching the description. I also checked the server-tool path: an assistant message mixing server_tool_use / web_search_tool_result with client tool uses still emits one assistant message, and a two-result probe produced one user message with both results. This is the right replacement for #2090 - the #2077 400 came from one user message per result, and grouping keeps every id's result in the immediately following message.
| * <ul> | ||
| * <li>Only the first message can be a system message (handled via system parameter) | ||
| * <li>Tool results must be in separate user messages | ||
| * <li>All results for a tool batch must be in one following user message |
There was a problem hiding this comment.
The same bullet still exists in AnthropicChatModel (AnthropicChatModel.java:62) and was not updated, so the class doc now contradicts the converter. Worth fixing in the same commit.
There was a problem hiding this comment.
Updated the matching bullet in AnthropicChatModel so it agrees with the formatter: all results for a tool batch belong in one following user message.
| result.add(regularMsg); | ||
| MessageParam regular = convertMessageContent(msg, nonToolBlocks, i == 0); | ||
| if (regular != null) { | ||
| if (regular.role().equals(Role.ASSISTANT)) { |
There was a problem hiding this comment.
regular.role() can be ASSISTANT only when an ASSISTANT message itself carries a client ToolResultBlock; TOOL/USER/SYSTEM all map to USER here. Msg permits it, and I verified the output is assistant(text, tool_use) followed by user(tool_result), but no test exercises it, so the branch reads as dead code. Either add a case or drop the branch; if it stays, == would match the enum comparison on line 116.
There was a problem hiding this comment.
Kept the branch and added a regression test covering an ASSISTANT message containing text, a client tool use, and its result. It verifies that assistant content is preserved and the result becomes a following user message. The condition now uses msg.getRole() == MsgRole.ASSISTANT, comparing the Java enum rather than the SDK role wrapper.
| } while (i < messages.size() | ||
| && messages.get(i).getRole() != MsgRole.ASSISTANT | ||
| && hasClientToolResults(messages.get(i))); | ||
| i--; |
There was a problem hiding this comment.
Optional: the i-- rewind is the only place in main code that moves a for-loop index backwards, which makes the consumed range implicit. An explicit int end = i; while (...) end++; ... i = end; reads closer to how the batch is defined. Also, otherContent is appended after the results by contract, so trailingContent would say more than "other".
ningmao-hlyz
left a comment
There was a problem hiding this comment.
FYI for reviewers: I checked the other protocol converters and this bug class is Anthropic-specific — Anthropic is the only major protocol that requires merging all parallel tool_results into one user message. The OpenAI-family converters (OpenAIMessageConverter, DashScope, Ollama) emit one role:"tool" message per result, which is exactly what those APIs require, and core's native shape (ToolResultMessageBuilder → one TOOL Msg per result) already matches. So no equivalent fix is needed elsewhere.
Two tiny nits that don't fit inline (they're outside the diff):
AnthropicMessageConverter.java:330—case SYSTEM -> isFirstMessage ? Role.USER : Role.USER;both arms are identical, so the ternary is dead code. It reads like an unfinished distinction (first-message system promotion?). If SYSTEM → USER is intentional here (system extraction happening elsewhere), I'd simplify tocase SYSTEM -> Role.USER;with a short comment, to avoid the next reader hunting for a difference that isn't there.AnthropicMessageConverterTest.java:383— the comment "Tool result creates separate user message" still describes the pre-fix behavior this PR reverses; worth updating while touching this test.
| && hasClientToolResults(messages.get(end))); | ||
| i = end; | ||
|
|
||
| toolResults.addAll(trailingContent); |
There was a problem hiding this comment.
Possible illegal user message if a TOOL-role Msg mixes client results with server blocks.
In this merge branch, nonToolBlocks is populated unconditionally (L104–106), so a ToolUseBlock or a server ToolResultBlock riding on the same TOOL message gets encoded by convertMessageContent into tool_use / server-tool result params and appended into the resulting Role.USER message (L122). The Anthropic API rejects tool_use / server tool blocks in a user message, so such a request would 400.
Reachability note: Msg.validateRoleContent already blocks this combination for USER and SYSTEM, so the only open path is MsgRole.TOOL carrying both a client result and a server block / tool_use. The existing regression test covers the ASSISTANT mixed case (which correctly keeps result.add(regular)), but not this one.
There was a problem hiding this comment.
It doesn't matter. In most cases, only one ToolResultBlock will be carried.
| assertEquals(MessageParam.Role.USER, result.get(2).role()); | ||
| List<ContentBlockParam> blocks = result.get(2).content().asBlockParams(); | ||
| assertEquals( | ||
| (results.get(0) == mixedResults || results.get(0) == mixedFirstResult) ? 3 : 2, |
There was a problem hiding this comment.
Nit: results.get(0) == mixedResults || results.get(0) == mixedFirstResult (L602, L626) uses reference equality as a control-flow condition. It works today, but if the converter ever copies/rebuilds block param lists, the branch silently stops being taken and the assertions below it are skipped — a structural assert (instanceof / size / first block type) would be more robust.
jujn
left a comment
There was a problem hiding this comment.
Assign to @ningmao-hlyz (Review)
Backport the verified fix to the 2.0.x implementation and retain its existing public contracts where the upstream kernel differs. (cherry picked from commit c52d1fc) Constraint: No AgentScope Service or SDK migration Confidence: high Not-tested: Whole-repository verification pending after lane integration
Problem
Parallel client tool calls are rewritten into alternating assistant/user exchanges, and individual tool results are emitted as separate user messages. This changes the original tool batch structure and does not follow Anthropic's documented parallel result format. DeepSeek's official endpoint rejects separate result messages with HTTP 400 in the direct test below; the gateway-specific 502 reported in #4018 has not been reproduced.
Changes
trailingContent.Fixes #4018.
Related: #3740 includes broader native thinking/history replay changes; this PR focuses on parallel tool batch formatting.
Validation
Live DeepSeek verification
Tested
deepseek-flashagainst the official Anthropic-compatible endpoint (https://api.deepseek.com/anthropic), with thinking disabled to isolate history formatting:AnthropicChatModel, streaming, prepared two-tool historyAnthropicChatModel, non-streaming, same historyThe direct endpoint tolerates the alternating history in this test, so this does not establish that alternating messages cause the reported gateway 502. The prepared-history tests validate formatting and request acceptance, not a complete Agent run with model-generated parallel calls. Verification through the issue author's original gateway is still needed. Native thinking replay is outside this PR's scope.
Full-repository
clean verifywas not run.