Skip to content

[Feature]: Promote images in tool results to a user message in OpenAI-compatible formatters (parity with Python) #3882

Open

Description

@mars171

Is your feature request related to a problem? Please describe.

When a tool returns an image, the OpenAI-compatible formatters put the media directly inside the tool message as a multimodal content-part array (text + image_url). This shape is not accepted by the OpenAI Chat Completions schema and is not supported consistently by OpenAI-compatible providers, so tool-returned images either cause a request error or are silently ignored by the model.

Current code path (verified on v2.0.4; OpenAIMessageConverter is byte-identical on main and v2.1.0-BETA1):

  • agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/formatter/OpenAIMessageConverter.java
    • convertToMessage (:83-102) dispatches MsgRole.TOOL to convertToolMessage at :94.
    • convertToolMessage (:433-461) checks hasMediaContent(result.getOutput()) at :443, and when media is present builds the tool message content from convertContentBlocks at :444-445.
    • convertContentBlocks (:167-296) turns an ImageBlock into an image_url part at :173-181, and a DataBlock with an image MIME type into the same part at :259-270.
    • hasMediaContent(List<ContentBlock>) (:463-475) returns true for ImageBlock, AudioBlock, VideoBlock and DataBlock.
  • OpenAIChatFormatter.doFormat (:54-80) converts each Msg into exactly one OpenAIMessage via convertMessage (:92-94), so there is currently no place where a single tool result can expand into two messages (text-only tool + user with media).
  • AbstractBaseFormatter.convertToolResultToString (:230-262) already produces a text-only representation (URL, or a temp file path for Base64 media), but it is unreachable for media results because the branch at :443 takes precedence.

Because OpenAIMessage.content is typed as Object (dto/OpenAIMessage.java:63-64), the invalid shape serializes without any warning. The current behavior is even asserted by OpenAIMessageConverterTest#testToolMessageWithMultimodalResult (.../formatter/OpenAIMessageConverterTest.java:885-912, assertTrue(result.isMultimodal())).

The resulting request body looks like this:

{
  "role": "tool",
  "tool_call_id": "call_123",
  "content": [
    {"type": "text", "text": "Screenshot taken"},
    {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}
  ]
}

Public API documentation does not define image_url parts for tool messages:

The same code path is inherited by OpenAIChatFormatter and by the provider formatters that extend it: DeepSeekFormatter, GLMFormatter, KimiFormatter, MiniMaxFormatter, and the *MultiAgentFormatter variants (e.g. compat/glm/GLMFormatter.java:72, compat/minimax/MiniMaxFormatter.java:31, compat/kimi/KimiFormatter.java:85, OpenAIMultiAgentFormatter.java:42).

Describe the solution you'd like

Mirror the Python implementation, which already handles this by "promoting" tool-result media into a separate user message:

  • src/agentscope/formatter/_formatter_base.py
    • convert_tool_result_to_string (:105-187) returns the tool text plus a list of blocks to promote. For a supported media type it appends a placeholder to the tool text,
      <system-reminder>A(n) {main_type} file is returned and will be presented to you with the identifier [{id}].</system-reminder> (:153-157),
      and collects TextBlock("- {id} ({main_type} file): ") plus the media block (:158-165), wrapped in <system-reminder>The multimodal data and their identifiers are listed as follows: ... </system-reminder> (:174-185). The identifier is the block's own stable id, so repeated formatting of the same history is stable (:147-151).
  • src/agentscope/formatter/_openai_formatter.py
    • pending_media (:276-282) delays the promoted message until the tool-result blocks of the current message have been emitted, and flushes it at :406.
    • The tool message is emitted with the textual output only (:359-371), and the promoted user message is appended afterwards (:373-393).
  • src/agentscope/formatter/_deepseek_formatter.py implements the same promotion and pending-media buffering (:66-71, :179-216).
  • src/agentscope/formatter/_anthropic_formatter.py intentionally keeps media inside tool_result (:196-255), because the Anthropic API natively supports images there. This issue should not change Anthropic, DashScope or Gemini behavior.
  • The built-in Read tool returns image/audio/video as DataBlock since PR build(deps): bump io.milvus:milvus-sdk-java from 2.6.17 to 3.0.3 #2114, which is what makes this path user-visible without a custom tool.

For Java, I would like the OpenAI-compatible formatters to:

  1. Emit a text-only tool message for a tool result that contains media, using the existing convertToolResultToString text plus a placeholder that identifies the media.
  2. Append a single user message carrying the media parts (and the identifier text), instead of putting media in the tool message.
  3. Buffer the promoted media across the whole run of consecutive MsgRole.TOOL messages and flush only after the last tool message of the turn. This matters because in Java every tool result is its own TOOL Msg (agentscope-core/.../tool/ToolResultMessageBuilder.java:40-51); flushing per message would insert a user message between tool messages and break the assistant tool_calls → tool → tool sequence that strict providers expect.
  4. Be enabled by default for these OpenAI-compatible formatters, or at minimum expose an explicit formatter option modeled on OllamaChatFormatter's existing promoteToolResultImages switch (agentscope-extensions/.../ollama/formatter/OllamaChatFormatter.java:59, :65, :201-258, currently default false). Since these providers document no media support in tool messages, promoting by default seems safer, but a switch would allow keeping the current behavior for gateways that do accept it.
  5. Reuse the media block id for the placeholder identifier (as Python does) and keep the promoted request byte-stable when the same history is formatted twice (related to [Bug]: Base64 tool-result formatting creates nondeterministic temporary paths #3199).
  6. Keep a textual fallback for media types the target model does not accept, so unsupported blocks are not silently dropped.
  7. Keep DeepSeek thinking-mode compatibility: compat/deepseek/DeepSeekFormatter.java:67-105 backfills reasoning_content for all assistant turns (applyDeepSeekFixes, :97-105) because DeepSeek returns HTTP 400 otherwise. Inserting the promoted user message must not disturb that pass or the tool_call_id pairing.
  8. Update OpenAIMessageConverterTest#testToolMessageWithMultimodalResult, which currently asserts the non-spec shape.

Describe the alternatives you've considered

  • Keep media in the tool message (status quo). It works only where a provider tolerates it; GLM's schema rejects it, and the OpenAI schema does not define it.
  • Only use the existing textual representation (AbstractBaseFormatter.convertToolResultToString). For Base64 media this yields a temporary file path that a remote model cannot read, so the image content is effectively lost (see [Bug]: Base64 tool-result formatting creates nondeterministic temporary paths #3199 for that path).
  • Ask users to attach the image in a separate user message. It breaks the tool-result attribution and the agent loop, and it cannot be done automatically inside a tool call.
  • Hardcode per-provider behavior in each compat formatter. The conversion logic is shared through OpenAIMessageConverter, so a formatter-level mechanism with provider-specific defaults avoids duplicating the promotion logic.

To reproduce

  1. Define a custom tool whose result contains a text block and an image block:
ToolResultBlock result =
        new ToolResultBlock(
                "call_123",
                "screenshot_tool",
                List.of(
                        TextBlock.builder().text("Screenshot taken").build(),
                        ImageBlock.builder()
                                .source(
                                        Base64Source.builder()
                                                .data("iVBORw0KGgoAAAANSUhEUg==") // truncated
                                                .mediaType("image/png")
                                                .build())
                                .build()),
                null);

Msg toolMsg = Msg.builder().role(MsgRole.TOOL).content(List.of(result)).build();
  1. Format the message with any OpenAI-compatible formatter, for example new GLMFormatter() or new DeepSeekFormatter(), serialize the resulting OpenAIRequest, and inspect the request body (or point the model at a local mock endpoint that logs requests).

  2. Observed: a tool message whose content is an array containing image_url. Expected after the fix: a tool message with text content plus a placeholder, followed by a user message whose content array contains the image:

{"role": "tool", "tool_call_id": "call_123", "content": "Screenshot taken\n<system-reminder>An image file is returned and will be presented to you with the identifier [img-1].</system-reminder>"}
{"role": "user", "content": [{"type": "text", "text": "<system-reminder>The multimodal data and their identifiers are listed as follows:\n- img-1 (image file): "}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}, {"type": "text", "text": "</system-reminder>"}]}

Environment

  • AgentScope-Java: 2.0.4 (the same converter is present on v2.1.0-BETA1 and main)
  • Java: 17
  • Affected module: agentscope-extensions-model-openai (chat-completions formatters); the openai-official Responses API module is out of scope for this request

Related issues and PRs

Activity

  1. wahllllll commented on Oct 31, 2026

    @wahllllll
    Contributor

    Confirmed on current main and fixed in #3889.

    The line references in the report all hold: convertToolMessage checks hasMediaContent(result.getOutput()) and then builds the content-part array directly on the tool message, so the request carries a shape the Chat Completions schema does not define. Because OpenAIMessage.content is typed as Object, nothing rejects it locally, and a provider either errors out or ignores the media — the tool's output is paid for and then discarded.

    The fix keeps the tool message text-only, using the representation convertToolResultToString already produced but could not reach, and delivers the media in a following user message that names the tool call. doFormat emits both messages through a new convertMessages hook, so the provider formatters that extend OpenAIChatFormatter get the same behavior rather than each needing its own copy.

    Two notes:

    • The existing OpenAIMessageConverterTest#testToolMessageWithMultimodalResult asserted the invalid shape (assertTrue(result.isMultimodal())). That assertion is now inverted, with the media checked on the user message instead. If it was intentional as a record of current behavior, it is worth confirming that the shape was never meant to reach a request.
    • This changes the request body only. Journals, stored Msg objects and tool-result conversion at the AgentScope level are untouched, so existing sessions keep working and the change is not a data migration.

    Regression: OpenAIToolMediaPromotionTest asserts the tool message stays text-only and that the media follows in a user message (expected: <2> but was: <1> before the change), plus a case pinning that text-only results are not split. The whole module passes: 581 tests.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions