Repository navigation
Description
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.javaconvertToMessage(:83-102) dispatchesMsgRole.TOOLtoconvertToolMessageat :94.convertToolMessage(:433-461) checkshasMediaContent(result.getOutput())at :443, and when media is present builds thetoolmessage content fromconvertContentBlocksat :444-445.convertContentBlocks(:167-296) turns anImageBlockinto animage_urlpart at :173-181, and aDataBlockwith an image MIME type into the same part at :259-270.hasMediaContent(List<ContentBlock>)(:463-475) returns true forImageBlock,AudioBlock,VideoBlockandDataBlock.
OpenAIChatFormatter.doFormat(:54-80) converts eachMsginto exactly oneOpenAIMessageviaconvertMessage(:92-94), so there is currently no place where a single tool result can expand into two messages (text-onlytool+userwith 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:
- OpenAI Chat Completions:
toolmessage content is a string or an array of text content parts;image_urlparts are defined forusermessages.
https://platform.openai.com/docs/api-reference/chat - Zhipu GLM (docs.bigmodel.cn, Chat Completions):
toolmessage content is a string; multimodal image input is defined on theusercontent array, and notool-role image input is documented.
https://docs.bigmodel.cn/ - DeepSeek vision guide: "images are only supported in
usermessages" (the create-chat-completion reference page separately lists an array type fortoolcontent, so the two pages are inconsistent; the vision guide is the more specific statement).
https://api-docs.deepseek.com/zh-cn/guides/vision - MiniMax OpenAI-compatible API: content is typed generically as
string | array, with no documented example of images in atoolmessage.
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.pyconvert_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 collectsTextBlock("- {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.pypending_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
toolmessage is emitted with the textual output only (:359-371), and the promotedusermessage is appended afterwards (:373-393).
src/agentscope/formatter/_deepseek_formatter.pyimplements the same promotion and pending-media buffering (:66-71, :179-216).src/agentscope/formatter/_anthropic_formatter.pyintentionally keeps media insidetool_result(:196-255), because the Anthropic API natively supports images there. This issue should not change Anthropic, DashScope or Gemini behavior.- The built-in
Readtool returns image/audio/video asDataBlocksince 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:
- Emit a text-only
toolmessage for a tool result that contains media, using the existingconvertToolResultToStringtext plus a placeholder that identifies the media. - Append a single
usermessage carrying the media parts (and the identifier text), instead of putting media in thetoolmessage. - Buffer the promoted media across the whole run of consecutive
MsgRole.TOOLmessages and flush only after the last tool message of the turn. This matters because in Java every tool result is its ownTOOLMsg(agentscope-core/.../tool/ToolResultMessageBuilder.java:40-51); flushing per message would insert ausermessage betweentoolmessages and break the assistanttool_calls→tool→toolsequence that strict providers expect. - Be enabled by default for these OpenAI-compatible formatters, or at minimum expose an explicit formatter option modeled on
OllamaChatFormatter's existingpromoteToolResultImagesswitch (agentscope-extensions/.../ollama/formatter/OllamaChatFormatter.java:59, :65, :201-258, currently defaultfalse). Since these providers document no media support intoolmessages, promoting by default seems safer, but a switch would allow keeping the current behavior for gateways that do accept it. - 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).
- Keep a textual fallback for media types the target model does not accept, so unsupported blocks are not silently dropped.
- Keep DeepSeek thinking-mode compatibility:
compat/deepseek/DeepSeekFormatter.java:67-105 backfillsreasoning_contentfor all assistant turns (applyDeepSeekFixes, :97-105) because DeepSeek returns HTTP 400 otherwise. Inserting the promotedusermessage must not disturb that pass or thetool_call_idpairing. - Update
OpenAIMessageConverterTest#testToolMessageWithMultimodalResult, which currently asserts the non-spec shape.
Describe the alternatives you've considered
- Keep media in the
toolmessage (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
usermessage. 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
- 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();-
Format the message with any OpenAI-compatible formatter, for example
new GLMFormatter()ornew DeepSeekFormatter(), serialize the resultingOpenAIRequest, and inspect the request body (or point the model at a local mock endpoint that logs requests). -
Observed: a
toolmessage whosecontentis an array containingimage_url. Expected after the fix: atoolmessage with text content plus a placeholder, followed by ausermessage 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-BETA1andmain) - Java: 17
- Affected module:
agentscope-extensions-model-openai(chat-completions formatters); theopenai-officialResponses API module is out of scope for this request
Related issues and PRs
- [Bug] 工具返回多模态时Formatter不符合预期 #1153 — tool returning multimodal content did not format as expected (closed; DashScope/OpenAI alignment, about preserving multimodal parts, not about promotion to a
usermessage) - [Feature]: Support DataBlock in all provider message converters #1932 / feat(core): support DataBlock in all provider message converters #1933 —
DataBlocksupport in all provider message converters - [Bug]: Base64 tool-result formatting creates nondeterministic temporary paths #3199 / fix(formatter): make Base64 tool-result temp paths deterministic #3200 — Base64 tool-result temp-path determinism (the text fallback path that would be used for promoted blocks)
- [Bug]: Deprecated formatter.* DeepSeek/GLM formatters bypass provider fixes on the two-arg doFormat(List, GenerateOptions) production path (missed by #3272) #3556 — deprecated
formatter.*DeepSeek/GLM formatters bypass provider fixes - [Feature]: Agent as Tool(子智能体工具)消息仅支持text 不支持image等多模态消息 #1386 — Agent as Tool messages are text-only (related limitation, different code path)
Activity
wahllllll commentedon Oct 31, 2026
Confirmed on current
mainand fixed in #3889.The line references in the report all hold:
convertToolMessagecheckshasMediaContent(result.getOutput())and then builds the content-part array directly on thetoolmessage, so the request carries a shape the Chat Completions schema does not define. BecauseOpenAIMessage.contentis typed asObject, 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
toolmessage text-only, using the representationconvertToolResultToStringalready produced but could not reach, and delivers the media in a followingusermessage that names the tool call.doFormatemits both messages through a newconvertMessageshook, so the provider formatters that extendOpenAIChatFormatterget the same behavior rather than each needing its own copy.Two notes:
OpenAIMessageConverterTest#testToolMessageWithMultimodalResultasserted 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.Msgobjects and tool-result conversion at the AgentScope level are untouched, so existing sessions keep working and the change is not a data migration.Regression:
OpenAIToolMediaPromotionTestasserts 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.