Skip to content

Commit c52d1fc

Browse files
authored
fix(anthropic): preserve parallel tool call batches (#4019)
## 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.
1 parent a63c625 commit c52d1fc

4 files changed

Lines changed: 186 additions & 224 deletions

File tree

‎agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/AnthropicChatModel.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
*
6060
* <ul>
6161
* <li>System messages are handled via the system parameter, not as messages
62-
* <li>Tool results must be in separate user messages
62+
* <li>All results for a tool batch must be in one following user message
6363
* <li>Supports Claude models (claude-3-*, claude-sonnet-*, etc.)
6464
* </ul>
6565
*/

‎agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/formatter/AnthropicChatFormatter.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
*
3131
* <ul>
3232
* <li>Only the first message can be a system message (handled via system parameter)
33-
* <li>Tool results must be in separate user messages
33+
* <li>All results for a tool batch must be in one following user message
3434
* <li>Supports thinking blocks natively (extended thinking feature)
3535
* </ul>
3636
*/

‎agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/formatter/AnthropicMessageConverter.java‎

Lines changed: 43 additions & 175 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
import io.agentscope.core.message.ToolUseBlock;
3838
import io.agentscope.core.tool.search.ToolSearchTool;
3939
import java.util.ArrayList;
40-
import java.util.LinkedHashMap;
4140
import java.util.List;
4241
import java.util.Map;
4342
import java.util.function.Function;
@@ -73,196 +72,73 @@ public AnthropicMessageConverter(Function<List<ContentBlock>, String> toolResult
7372
}
7473

7574
/**
76-
* Convert list of Msg to list of Anthropic MessageParam. Handles the special case where tool
77-
* results need to be in separate user messages.
75+
* Convert messages while preserving assistant tool batches and grouping consecutive client
76+
* tool results in one user message, before any accompanying text or media.
7877
*
7978
* @param messages The messages to convert
8079
* @return List of MessageParam for Anthropic API
8180
*/
8281
public List<MessageParam> convert(List<Msg> messages) {
8382
List<MessageParam> result = new ArrayList<>();
8483

85-
for (int i = 0; i < messages.size(); i++) {
84+
for (int i = 0; i < messages.size(); ) {
8685
Msg msg = messages.get(i);
87-
boolean isFirstMessage = (i == 0);
88-
89-
if (msg.getRole() == MsgRole.ASSISTANT && clientToolUses(msg).size() > 1) {
90-
SplitToolResultSequence splitResults = collectSplitToolResults(messages, i + 1);
91-
if (shouldSplitParallelToolCalls(msg, splitResults)) {
92-
result.addAll(convertParallelToolCalls(msg, splitResults));
93-
i += splitResults.consumedMessages();
94-
continue;
86+
if (!hasClientToolResults(msg)) {
87+
MessageParam param = convertMessageContent(msg, msg.getContent());
88+
if (param != null) {
89+
result.add(param);
9590
}
91+
i++;
92+
continue;
9693
}
9794

98-
// Special handling for tool results - they create separate user messages.
99-
// Server tool results (e.g. web_search_tool_result) stay inline in the
100-
// assistant message instead.
101-
if (msg.hasContentBlocks(ToolResultBlock.class)) {
102-
// Add non-tool-result content first (if any)
95+
List<ContentBlockParam> toolResults = new ArrayList<>();
96+
List<ContentBlockParam> trailingContent = new ArrayList<>();
97+
int end = i;
98+
do {
99+
msg = messages.get(end);
103100
List<ContentBlock> nonToolBlocks = new ArrayList<>();
104-
List<ToolResultBlock> toolResults = new ArrayList<>();
105-
106101
for (ContentBlock block : msg.getContent()) {
107102
if (block instanceof ToolResultBlock tr && !tr.isServerTool()) {
108-
toolResults.add(tr);
103+
toolResults.add(convertToolResult(tr));
109104
} else {
110105
nonToolBlocks.add(block);
111106
}
112107
}
113-
114-
// Add regular content if present
115-
if (!nonToolBlocks.isEmpty()) {
116-
MessageParam regularMsg = convertMessageContent(msg, nonToolBlocks, i == 0);
117-
if (regularMsg != null) {
118-
result.add(regularMsg);
108+
MessageParam regular = convertMessageContent(msg, nonToolBlocks);
109+
if (regular != null) {
110+
if (msg.getRole() == MsgRole.ASSISTANT) {
111+
result.add(regular);
112+
} else {
113+
trailingContent.addAll(regular.content().asBlockParams());
119114
}
120115
}
121-
122-
// Add tool results as separate user messages
123-
for (ToolResultBlock toolResult : toolResults) {
124-
result.add(convertToolResult(toolResult));
125-
}
126-
} else {
127-
MessageParam param = convertMessageContent(msg, msg.getContent(), isFirstMessage);
128-
if (param != null) {
129-
result.add(param);
130-
}
131-
}
116+
end++;
117+
} while (end < messages.size()
118+
&& messages.get(end).getRole() != MsgRole.ASSISTANT
119+
&& hasClientToolResults(messages.get(end)));
120+
i = end;
121+
122+
toolResults.addAll(trailingContent);
123+
result.add(
124+
MessageParam.builder()
125+
.role(Role.USER)
126+
.content(MessageParam.Content.ofBlockParams(toolResults))
127+
.build());
132128
}
133-
134129
return result;
135130
}
136131

137-
/**
138-
* Decide whether the current assistant message should be expanded into Anthropic's required
139-
* tool-use/tool-result alternation.
140-
*
141-
* <p>Splitting is enabled only when all of the following are true:
142-
*
143-
* <ul>
144-
* <li>The current message role is {@link MsgRole#ASSISTANT}.
145-
* <li>At least one following pure tool-result message was discovered.
146-
* <li>The current message contains two or more {@link ToolUseBlock}s.
147-
* <li>Every tool-use id is present and non-blank.
148-
* <li>The number of collected tool results equals the number of tool uses, and every
149-
* tool-use id has a corresponding result.
150-
* </ul>
151-
*/
152-
private boolean shouldSplitParallelToolCalls(Msg msg, SplitToolResultSequence splitResults) {
153-
if (msg.getRole() != MsgRole.ASSISTANT || splitResults.consumedMessages() == 0) {
154-
return false;
155-
}
156-
157-
List<ToolUseBlock> toolUses = clientToolUses(msg);
158-
if (toolUses.size() <= 1) {
159-
return false;
160-
}
161-
162-
List<String> toolUseIds = toolUses.stream().map(ToolUseBlock::getId).toList();
163-
if (toolUseIds.stream().anyMatch(id -> id == null || id.isBlank())) {
164-
return false;
165-
}
166-
167-
return splitResults.resultsById().size() == toolUseIds.size()
168-
&& toolUseIds.stream().allMatch(id -> splitResults.resultsById().containsKey(id));
169-
}
170-
171-
/**
172-
* Collect the consecutive pure tool-result messages that immediately follow an assistant
173-
* message.
174-
*
175-
* <p>Scanning starts at {@code startIndex}, which is normally the message right after the
176-
* assistant message being inspected. The scan continues only across messages whose content is
177-
* made entirely of {@link ToolResultBlock}s. It stops as soon as a message has no tool results
178-
* or contains any non-tool-result content, because such a message must be preserved in its
179-
* original position rather than consumed into the split sequence.
180-
*/
181-
private SplitToolResultSequence collectSplitToolResults(List<Msg> messages, int startIndex) {
182-
Map<String, ToolResultBlock> byId = new LinkedHashMap<>();
183-
int consumed = 0;
184-
185-
for (int i = startIndex; i < messages.size(); i++) {
186-
Msg msg = messages.get(i);
187-
List<ToolResultBlock> toolResults = msg.getContentBlocks(ToolResultBlock.class);
188-
if (toolResults.isEmpty() || hasNonToolResultContent(msg)) {
189-
break;
190-
}
191-
192-
consumed++;
193-
for (ToolResultBlock toolResult : toolResults) {
194-
if (toolResult.getId() != null) {
195-
byId.putIfAbsent(toolResult.getId(), toolResult);
196-
}
197-
}
198-
}
199-
200-
return new SplitToolResultSequence(byId, consumed);
201-
}
202-
203-
private boolean hasNonToolResultContent(Msg msg) {
204-
return msg.getContent().stream().anyMatch(block -> !(block instanceof ToolResultBlock));
205-
}
206-
207-
/**
208-
* Expand one assistant message with parallel tool uses into alternating Anthropic messages.
209-
*
210-
* <p>Each {@link ToolUseBlock} from the original assistant message is wrapped in its own
211-
* assistant message and immediately followed by the matching user tool-result message. Any
212-
* leading assistant content, such as explanatory text before the tool calls, is attached only
213-
* to the first split assistant message so it is not duplicated across the generated sequence.
214-
*/
215-
private List<MessageParam> convertParallelToolCalls(
216-
Msg assistantMsg, SplitToolResultSequence splitResults) {
217-
List<MessageParam> converted = new ArrayList<>();
218-
// Server tool blocks (use + result) stay with the leading content; only client tool
219-
// calls participate in the tool-use/tool-result alternation.
220-
List<ContentBlock> leadingBlocks =
221-
assistantMsg.getContent().stream()
222-
.filter(block -> !(block instanceof ToolUseBlock tub) || tub.isServerTool())
223-
.toList();
224-
List<ToolUseBlock> toolUses = clientToolUses(assistantMsg);
225-
226-
for (int i = 0; i < toolUses.size(); i++) {
227-
ToolUseBlock toolUse = toolUses.get(i);
228-
List<ContentBlock> assistantBlocks = new ArrayList<>();
229-
if (i == 0) {
230-
assistantBlocks.addAll(leadingBlocks);
231-
}
232-
assistantBlocks.add(toolUse);
233-
234-
MessageParam assistantParam =
235-
convertMessageContent(assistantMsg, assistantBlocks, false);
236-
if (assistantParam != null) {
237-
converted.add(assistantParam);
238-
}
239-
240-
ToolResultBlock toolResult = splitResults.resultsById().get(toolUse.getId());
241-
converted.add(convertToolResult(toolResult));
242-
}
243-
244-
return converted;
245-
}
246-
247-
private record SplitToolResultSequence(
248-
Map<String, ToolResultBlock> resultsById, int consumedMessages) {}
249-
250-
/**
251-
* Tool calls that are executed by the local toolkit (i.e. excluding provider server tools
252-
* such as Anthropic's web_search, which are executed on the server side).
253-
*/
254-
private List<ToolUseBlock> clientToolUses(Msg msg) {
255-
return msg.getContentBlocks(ToolUseBlock.class).stream()
256-
.filter(toolUse -> !toolUse.isServerTool())
257-
.toList();
132+
private boolean hasClientToolResults(Msg msg) {
133+
return msg.getContentBlocks(ToolResultBlock.class).stream()
134+
.anyMatch(toolResult -> !toolResult.isServerTool());
258135
}
259136

260137
/**
261138
* Convert message content to MessageParam.
262139
*/
263-
private MessageParam convertMessageContent(
264-
Msg msg, List<ContentBlock> blocks, boolean isFirstMessage) {
265-
Role role = convertRole(msg.getRole(), isFirstMessage);
140+
private MessageParam convertMessageContent(Msg msg, List<ContentBlock> blocks) {
141+
Role role = convertRole(msg.getRole());
266142
List<ContentBlockParam> contentBlocks = new ArrayList<>();
267143

268144
for (ContentBlock block : blocks) {
@@ -273,7 +149,6 @@ private MessageParam convertMessageContent(
273149
ContentBlockParam.ofText(
274150
TextBlockParam.builder().text(hb.getHint()).build()));
275151
} else if (block instanceof ThinkingBlock thinkingBlock) {
276-
// Anthropic supports thinking blocks natively
277152
contentBlocks.add(
278153
ContentBlockParam.ofText(
279154
TextBlockParam.builder()
@@ -356,9 +231,9 @@ private MessageParam convertMessageContent(
356231
}
357232

358233
/**
359-
* Convert tool result to separate user message.
234+
* Convert a client tool result to an Anthropic content block.
360235
*/
361-
private MessageParam convertToolResult(ToolResultBlock toolResult) {
236+
private ContentBlockParam convertToolResult(ToolResultBlock toolResult) {
362237
// Convert output to content blocks
363238
List<ToolResultBlockParam.Content.Block> blocks = new ArrayList<>();
364239

@@ -437,13 +312,7 @@ private MessageParam convertToolResult(ToolResultBlock toolResult) {
437312
}
438313
ToolResultBlockParam toolResultParam = resultBuilder.build();
439314

440-
// Wrap in user message
441-
return MessageParam.builder()
442-
.role(Role.USER)
443-
.content(
444-
MessageParam.Content.ofBlockParams(
445-
List.of(ContentBlockParam.ofToolResult(toolResultParam))))
446-
.build();
315+
return ContentBlockParam.ofToolResult(toolResultParam);
447316
}
448317

449318
private TextBlockParam convertTextBlock(TextBlock textBlock) {
@@ -454,10 +323,9 @@ private TextBlockParam convertTextBlock(TextBlock textBlock) {
454323
* Convert AgentScope MsgRole to Anthropic Role. Important: Anthropic only allows the first
455324
* message to be system. Non-first system messages are converted to user.
456325
*/
457-
private Role convertRole(MsgRole msgRole, boolean isFirstMessage) {
326+
private Role convertRole(MsgRole msgRole) {
458327
return switch (msgRole) {
459-
case SYSTEM -> isFirstMessage ? Role.USER : Role.USER; // Anthropic uses user for
460-
// system messages
328+
case SYSTEM -> Role.USER;
461329
case USER -> Role.USER;
462330
case ASSISTANT -> Role.ASSISTANT;
463331
case TOOL -> Role.USER; // Tool results are always user messages

0 commit comments

Comments
 (0)