Repository navigation
Description
Describe the bug
Since #2090 (fix for #2077, merged 2026-07-10), AnthropicMessageConverter rewrites a parallel tool-call batch into alternating messages:
assistant(tool_use_1) -> user(tool_result_1) -> assistant(tool_use_2) -> user(tool_result_2)
and, independently, emits one user message per ToolResultBlock (AnthropicMessageConverter.java:94-119 → result.add(convertToolResult(...)) inside the loop; :209-237 → convertParallelToolCalls).
This is the opposite of what the Anthropic Messages API documents for parallel tool use:
- "return one
tool_resultfor eachtool_useblock, all together in the next user message" — https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use - "Wrong: a separate user message for each tool result. Correct: all tool results together in a single user message" — same page, "Incorrect tool result formatting"
- "Tool result blocks must immediately follow their corresponding tool use blocks… the
tool_resultblocks must come FIRST in the content array" — https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls
Anthropic-compatible providers that validate the history strictly reject the split shape. With DeepSeek's Anthropic-compatible API (model deepseek-flash), every turn in which the model emits ≥2 parallel tool_use blocks fails with HTTP 502 Invalid upstream response, the request is retried and the run ends with a ModelException (retries exhausted). Single tool calls are unaffected (1 tool_use + 1 tool_result is naturally alternating).
Note: #2077 attributed its 400 to "orphaned tool_use IDs". The native shape itself is valid per the docs and is accepted by DeepSeek in our test (see matrix below), so the 400 in #2077 may have come from a missing/orphaned tool_result (e.g. replay after compaction) rather than from the native shape.
To Reproduce
HarnessAgent(orReActAgent) withAnthropicChatModelpointing to an Anthropic-compatible endpoint that serves DeepSeek, streaming on, two simple tools:
AnthropicChatModel model = AnthropicChatModel.builder()
.baseUrl(ANTHROPIC_COMPATIBLE_BASE_URL) // SDK appends /v1/messages
.apiKey(API_KEY)
.modelName("deepseek-flash")
.stream(true)
.build();
Toolkit tk = new Toolkit();
tk.registerTool(new StoreTools()); // get_store_sales(store_id, month), get_store_returns(store_id, month)
HarnessAgent agent = HarnessAgent.builder()
.name("parallel-tool-repro")
.sysPrompt("Always call tools to get data; never make numbers up.")
.model(model)
.toolkit(tk)
.maxIters(8)
.generateOptions(GenerateOptions.builder().maxTokens(4000).build())
.build();
// A question that makes the model call both tools in the same step:
agent.streamEvents(new UserMessage("What are the sales and the number of returns of store S001 in 2026-10? I need both."), ctx)
.blockLast();- The model returns one assistant message with 2
tool_useblocks; both tools execute successfully. - The next model request (built by
AnthropicMessageConverter) is rejected with 502; after retries the run fails.
Raw-HTTP matrix against the same endpoint (same tools, same two tool results, only the history shape differs):
| # | History shape sent back | Result |
|---|---|---|
| S1 | native: 1 assistant [tool_use ×2] + 1 user [tool_result ×2] | 200, correct final answer |
| S2 | AgentScope split: assistant/user alternating ×2 (with thinking) | 502 |
| S3 | same as S2 without thinking blocks | 502 |
| S4 | native assistant [tool_use ×2] + 2 separate user [tool_result] | 502 |
S4 shows that "one user message per tool_result" (lines 94-119) is rejected on its own, even without the alternating rewrite.
Expected behavior
Keep the native shape for a completed parallel batch: one assistant message containing all tool_use blocks, followed by one user message whose content starts with all matching tool_result blocks, as documented by Anthropic.
Error messages
WARN io.agentscope.core.model.ModelUtils - Retrying model request (attempt 1/2) due to: Failed to stream Anthropic API: 502: {"type":"error","error":{"message":"Invalid upstream response","type":"api_error"}}
io.agentscope.core.model.ModelException: Failed to stream Anthropic API: 502: {"type":"error","error":{"message":"Invalid upstream response","type":"api_error"}} [model=deepseek-flash, provider=anthropic]
Caused by: com.anthropic.errors.InternalServerException: 502: {"type":"error","error":{"type":"api_error","message":"Invalid upstream response"}}
Environment (please complete the following information):
- AgentScope-Java Version: 2.0.4 (
agentscope-core,agentscope-harness,agentscope-extensions-model-anthropic) - Java Version: 17 (JBR 17.0.5)
- OS: macOS (arm64)
- Model / provider:
deepseek-flashthrough an Anthropic-compatible gateway that forwards the request body unchanged to DeepSeek's Anthropic-compatible API
Additional context
- Related: [Bug]:Batch parallel tool calls produce invalid tool_use/tool_result message format for Anthropic API, causing 400 error #2077, fix(anthropic): split parallel tool calls into alternating messages #2090. The open PR fix(anthropic): preserve native thinking and parallel tool history #3740 ("preserve native thinking and parallel tool history") appears to restore exactly the native shape — happy to verify it against DeepSeek once it lands or on a snapshot build.
GenerateOptions.parallelToolCalls(false)(→disable_parallel_tool_use: true) is not a workaround here: DeepSeek still returned paralleltool_useblocks in our runs.- Current workaround (no vendor patch): a custom formatter extending
AnthropicChatFormatterthat overridesdoFormat(List<Msg>)to (1) merge consecutive same-role messages, (2) keep alltool_useblocks in one assistant message, (3) put alltool_resultblocks first in the following single user message; injected viaAnthropicChatModel.builder().formatter(...). With it the same parallel question completes in 2 model calls with no 502. - Not tested: the official Anthropic API (Claude models) directly; the expected behavior above relies on the Anthropic documentation.
Activity
iluv7 commentedon Nov 6, 2026
Thanks for the detailed report. I've opened #4019 to preserve parallel tool calls in one assistant message and group their results into one following user message, before any accompanying text or media.
I tested against DeepSeek's official Anthropic-compatible endpoint with
deepseek-flash, with thinking disabled to isolate history formatting:Could you test #4019 with your original setup to confirm whether it resolves the failure?
anlostsheep commentedon Nov 6, 2026
Hi @iluv7 — thanks for the fix. We re-ran the scenario from #4018 against your branch (head
1484256;agentscope-core,agentscope-harnessandagentscope-extensions-model-anthropicbuilt as2.1.0-SNAPSHOT, tests skipped at build time;AnthropicMessageConverterTestpasses separately, 38/38).Setup: an internal Anthropic-compatible gateway that forwards requests to DeepSeek's Anthropic-compatible endpoint (model
deepseek-flash), two tools, one question that makes the model emit twotool_useblocks in the same turn.The converter fix works. The request for the second turn now looks like this, and the turn completes in 2 model calls:
Non-streaming note (not caused by your change). The non-stream path builds the tool call with
ToolUseBlock.content = toolUse._input().toString()(AnthropicResponseParser.java:93-96). For a non-empty input that produces{store_id=S001, month=2026-10}(30 chars), whichToolCallsAccumulatortries to parse as JSON and rejects:malformed arguments after the stream ended (raw length: 30) ... Cause: JsonException. Every tool call is then rejected before execution, and the agent loops untilmaxIters. The same code is in 2.0.4, and your PR doesn't touch that file. We only ran non-streaming with thinking enabled; the failure is in argument parsing, so thinking is orthogonal.On the 502 vs 400 difference. Our gateway does not rewrite the message history. Two things are worth knowing:
502 {"type":"api_error","message":"Invalid upstream response"}.So a 400 that you see directly will appear as a 502 through the gateway. We re-ran the raw matrix through it, same seed data, only the history shape changed:
The three failures come back in ~200–400 ms (a normal turn takes ~1.3 s), which looks like an early upstream rejection rather than a gateway-side parse failure of a 200 response.
One point we could not close: you saw the alternating shape (S2) pass directly, but through the gateway it is a 502. Since the body is forwarded unchanged apart from the model name, this cannot come from message rewriting; it is either the upstream rejecting the shape or the gateway failing while processing the upstream response. The most likely explanation is that the upstream model/account behind the gateway is not the same one you tested against (the logical name is mapped in the provider configuration), but we only hold a gateway credential and cannot run the same matrix against DeepSeek directly to confirm.
Happy to re-run anything if you want a different shape or model variant.
iluv7 commentedon Nov 6, 2026
Thanks for verifying #4019 and for identifying the separate non-streaming argument parsing issue.
I've opened #4031 to fix it: non-streaming tool arguments are now serialized as JSON instead of using
JsonValue.toString(). Regression tests cover SDK response parsing through ReAct accumulation and actual tool execution, including non-empty and nested arguments.I also verified a complete non-streaming ReActAgent run against DeepSeek's official Anthropic-compatible endpoint (
deepseek-flash, thinking disabled): the model-generated arguments reached the tool correctly, the tool executed once, and the agent returned the expected answer.Could you test #4031 in your original gateway setup, particularly the non-streaming + thinking-on case that failed previously? This PR is independent of #4019.
fix(anthropic): serialize non-streaming tool arguments as JSON (#4031)
fix(anthropic): preserve parallel tool call batches (#4019)