Skip to content

fix(anthropic): preserve parallel tool call batches - #4019

Merged
jujn merged 3 commits into
agentscope-ai:mainfrom
iluv7:fix/anthropic-parallel-tool-history
Nov 8, 2026
Merged

jujn merged 3 commits into
agentscope-ai:mainfrom
iluv7:fix/anthropic-parallel-tool-history

Conversation

@iluv7

@iluv7 iluv7 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Preserve all tool uses in their original assistant message.
  • Group consecutive client tool results into one user message, placing results before accompanying text or media.
  • Keep server tool blocks inline and stop result grouping at conversation boundaries.
  • Update formatter/model comments and regression tests for separate/combined results, mixed text, multiple turns, and assistant messages carrying client tool results.
  • Use an explicit batch end index without rewinding the loop cursor; name accompanying content trailingContent.

Fixes #4018.

Related: #3740 includes broader native thinking/history replay changes; this PR focuses on parallel tool batch formatting.

Validation

  • Regression test fails against the original implementation (expected 6 messages, actual 10).
  • After review changes, Anthropic module and dependency tests passed: core 2,993 tests (9 skipped), Anthropic 257 tests (no skips), no failures/errors.
  • Earlier targeted formatter tests passed: 71 tests, no failures/errors/skips; the review follow-up was validated with the full module/dependency test command.
  • Spotless check and git diff --check passed.

Live DeepSeek verification

Tested deepseek-flash against the official Anthropic-compatible endpoint (https://api.deepseek.com/anthropic), with thinking disabled to isolate history formatting:

Test Result
Patched Java AnthropicChatModel, streaming, prepared two-tool history Success; returns both supplied results
Patched Java AnthropicChatModel, non-streaming, same history Success; returns both supplied results
Raw HTTP streaming: one assistant with two tool uses, one user with both results HTTP 200
Raw HTTP streaming: one assistant with two tool uses, two separate user result messages HTTP 400; missing immediately following tool result
Raw HTTP streaming: alternating assistant/tool-use and user/tool-result messages HTTP 200

The 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 verify was not run.

@jujn jujn added the P1 紧急不重要 label Nov 7, 2026
jujn pushed a commit that referenced this pull request Nov 7, 2026
## 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 ningmao-hlyz 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.

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

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)) {

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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--;

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.

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".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

@ningmao-hlyz ningmao-hlyz 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.

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 to case 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);

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.

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.

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.

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,

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.

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 jujn 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.

Assign to @ningmao-hlyz (Review)

@jujn
jujn merged commit c52d1fc into agentscope-ai:main Nov 8, 2026
5 checks passed
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 紧急不重要

Projects

None yet

3 participants