Skip to content

[Bug]: AnthropicMessageConverter splits parallel tool_use/tool_result into alternating messages (since #2090) — rejected by Anthropic-compatible providers (DeepSeek), contradicts Anthropic docs #4018

Closed

Description

@anlostsheep

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:

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

  1. HarnessAgent (or ReActAgent) with AnthropicChatModel pointing 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();
  1. The model returns one assistant message with 2 tool_use blocks; both tools execute successfully.
  2. 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-flash through an Anthropic-compatible gateway that forwards the request body unchanged to DeepSeek's Anthropic-compatible API

Additional context

Activity

  1. added
    bug
    on Nov 6, 2026
  2. iluv7 commented on Nov 6, 2026

    @iluv7
    Contributor

    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:

    • The patched Java implementation succeeds in both streaming and non-streaming modes using a prepared two-tool history.
    • Separate user messages for the two results are rejected with HTTP 400.
    • The alternating assistant/user history succeeds on the direct endpoint, so I haven't reproduced the reported 502 through your gateway.

    Could you test #4019 with your original setup to confirm whether it resolves the failure?

  3. anlostsheep commented on Nov 6, 2026

    @anlostsheep
    Author

    Hi @iluv7 — thanks for the fix. We re-ran the scenario from #4018 against your branch (head 1484256; agentscope-core, agentscope-harness and agentscope-extensions-model-anthropic built as 2.1.0-SNAPSHOT, tests skipped at build time; AnthropicMessageConverterTest passes 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 two tool_use blocks 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:

    assistant [tool_use, tool_use]
    user      [tool_result, tool_result]   (in tool_use order, first in the content array)
    
    Mode HTTP Outcome
    streaming, thinking on 200 correct answer: 1,286,400 / 3
    streaming, thinking off 200 correct answer: 1,286,400 / 3
    non-streaming, thinking on 200 200 from the API, but the run fails before executing the tools — see below

    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), which ToolCallsAccumulator tries 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 until maxIters. 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:

    1. It maps the logical model name to the per-provider upstream model name; the rest of the body (messages, tools, system, thinking) is forwarded as-is.
    2. It normalizes upstream errors: 429/5xx keep their status; a recognized Anthropic error envelope keeps its status but gets a generic message; any other 4xx is returned as 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:

    Case History shape HTTP
    S1 native: one assistant [tool_use ×2] + one user [tool_result ×2] 200, correct answer
    S2 alternating assistant/user ×2 (with thinking) 502
    S3 alternating, without thinking 502
    S4 native tool_use, but two separate user messages with one tool_result each 502

    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.

  4. iluv7 commented on Nov 6, 2026

    @iluv7
    Contributor

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions