Skip to content

Build and run agents you can see, understand and trust.

fix(formatter): preserve DeepSeek images and Moonshot videos (#2825)

qbc604f8e75b636
diff --git a/src/agentscope/formatter/_deepseek_formatter.py b/src/agentscope/formatter/_deepseek_formatter.py
index 7f09c1eb9..845b97292 100644
--- a/src/agentscope/formatter/_deepseek_formatter.py
+++ b/src/agentscope/formatter/_deepseek_formatter.py
@@ -4,7 +4,7 @@ from typing import Any
from pydantic import Field
-from ._formatter_base import FormatterBase
+from ._openai_formatter import _OpenAIFormatterBase
from .._logging import logger
from ..message import (
Msg,
@@ -17,7 +17,7 @@ from ..message import (
)
-class DeepSeekChatFormatter(FormatterBase):
+class DeepSeekChatFormatter(_OpenAIFormatterBase):
"""The DeepSeek formatter class for chatbot scenario, where only a user
and an agent are involved. We use the `role` field to identify different
entities in the conversation.
@@ -26,11 +26,22 @@ class DeepSeekChatFormatter(FormatterBase):
input_types: list[str] = Field(
default_factory=lambda: ["text/plain"],
description=(
- 'The supported input types. Defaults to ``["text/plain"]`` '
- "(DeepSeek does not support multimodal input)."
+ 'The supported input types. Defaults to ``["text/plain"]``; '
+ "image input is only supported by ``deepseek-flash``."
),
)
+ @staticmethod
+ def _content_from_blocks(
+ blocks: list[dict[str, Any]],
+ ) -> str | list[dict[str, Any]]:
+ """Keep text-only content as a string for text-only DeepSeek models,
+ and multimodal content as a list of content blocks."""
+ if any(block["type"] != "text" for block in blocks):
+ return blocks
+ return "\n".join(block["text"] for block in blocks)
+
+ # pylint: disable=too-many-branches
async def format(
self,
msgs: list[Msg],
@@ -52,11 +63,22 @@ class DeepSeekChatFormatter(FormatterBase):
content_blocks: list = []
reasoning_content_blocks: list = []
tool_calls = []
+ pending_media: list[dict[str, Any]] = []
for block in msg.get_content_blocks():
+ if pending_media and not isinstance(block, ToolResultBlock):
+ messages.extend(pending_media)
+ pending_media = []
+
if isinstance(block, TextBlock):
content_blocks.append({"type": "text", "text": block.text})
+ # DeepSeek only accepts images in user messages
+ elif isinstance(block, DataBlock) and msg.role == "user":
+ formatted = self._format_openai_data_block(block)
+ if formatted is not None:
+ content_blocks.append(formatted)
+
elif isinstance(block, ThinkingBlock):
reasoning_content_blocks.append(block.thinking)
@@ -66,13 +88,10 @@ class DeepSeekChatFormatter(FormatterBase):
or tool_calls
or reasoning_content_blocks
):
- content_text = "\n".join(
- b.get("text", "") for b in content_blocks
- )
+ content = self._content_from_blocks(content_blocks)
msg_flush_hint: dict[str, Any] = {
"role": msg.role,
- "content": content_text
- or (None if tool_calls else ""),
+ "content": content or (None if tool_calls else ""),
}
if msg.role == "assistant":
msg_flush_hint["reasoning_content"] = (
@@ -92,20 +111,29 @@ class DeepSeekChatFormatter(FormatterBase):
{"role": "user", "content": block.hint},
)
else:
- hint_text_parts: list[str] = []
+ hint_parts: list[dict[str, Any]] = []
for sub in block.hint:
if isinstance(sub, TextBlock):
- hint_text_parts.append(sub.text)
+ hint_parts.append(
+ {"type": "text", "text": sub.text},
+ )
elif isinstance(sub, DataBlock):
- hint_text_parts.append(
- f"[{sub.source.media_type} attached, "
- "not supported by this provider]",
+ hint_parts.append(
+ self._format_openai_data_block(sub)
+ or {
+ "type": "text",
+ "text": f"[{sub.source.media_type} "
+ "attached, not supported by this "
+ "provider]",
+ },
)
- if hint_text_parts:
+ if hint_parts:
messages.append(
{
"role": "user",
- "content": "\n".join(hint_text_parts),
+ "content": self._content_from_blocks(
+ hint_parts,
+ ),
},
)
@@ -127,13 +155,10 @@ class DeepSeekChatFormatter(FormatterBase):
or tool_calls
or reasoning_content_blocks
):
- content_text = "\n".join(
- b.get("text", "") for b in content_blocks
- )
+ content = self._content_from_blocks(content_blocks)
msg_flush: dict[str, Any] = {
"role": msg.role,
- "content": content_text
- or (None if tool_calls else ""),
+ "content": content or (None if tool_calls else ""),
}
if msg.role == "assistant":
msg_flush["reasoning_content"] = (
@@ -148,9 +173,10 @@ class DeepSeekChatFormatter(FormatterBase):
reasoning_content_blocks = []
tool_calls = []
- textual_output, _ = self.convert_tool_result_to_string(
- block.output,
- )
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(block.output)
messages.append(
{
"role": "tool",
@@ -160,13 +186,36 @@ class DeepSeekChatFormatter(FormatterBase):
},
)
+ if multimodal_data:
+ promo_content: list[dict[str, Any]] = []
+ for item in multimodal_data:
+ if isinstance(item, TextBlock):
+ promo_content.append(
+ {"type": "text", "text": item.text},
+ )
+ elif isinstance(item, DataBlock):
+ formatted = self._format_openai_data_block(
+ item,
+ )
+ if formatted is not None:
+ promo_content.append(formatted)
+ if promo_content:
+ pending_media.append(
+ {
+ "role": "user",
+ "content": promo_content,
+ },
+ )
+
else:
logger.warning(
"Unsupported block type %s in the message, skipped.",
type(block),
)
- content_msg = "\n".join(b.get("text", "") for b in content_blocks)
+ messages.extend(pending_media)
+
+ content_msg = self._content_from_blocks(content_blocks)
msg_deepseek: dict[str, Any] = {
"role": msg.role,
@@ -198,7 +247,7 @@ class DeepSeekChatFormatter(FormatterBase):
return messages
-class DeepSeekMultiAgentFormatter(FormatterBase):
+class DeepSeekMultiAgentFormatter(_OpenAIFormatterBase):
"""
DeepSeek formatter for multi-agent conversations, where more than
a user and an agent are involved.
@@ -216,8 +265,8 @@ class DeepSeekMultiAgentFormatter(FormatterBase):
input_types: list[str] = Field(
default_factory=lambda: ["text/plain"],
description=(
- 'The supported input types. Defaults to ``["text/plain"]`` '
- "(DeepSeek does not support multimodal input)."
+ 'The supported input types. Defaults to ``["text/plain"]``; '
+ "image input is only supported by ``deepseek-flash``."
),
)
@@ -276,27 +325,43 @@ class DeepSeekMultiAgentFormatter(FormatterBase):
conversation_history_prompt = ""
formatted_msgs: list[dict] = []
- accumulated_text = []
+ content_blocks: list[dict[str, Any]] = [
+ {
+ "type": "text",
+ "text": f"{conversation_history_prompt}<history>\n",
+ },
+ ]
+ has_history = False
+ has_image = False
for msg in msgs:
for block in msg.get_content_blocks():
if isinstance(block, TextBlock):
- accumulated_text.append(f"{msg.name}: {block.text}")
-
- conversation_blocks_text = ""
- if accumulated_text:
- conversation_blocks_text = (
- conversation_history_prompt
- + "<history>\n"
- + "\n".join(accumulated_text)
- + "\n</history>"
- )
+ content_blocks[-1]["text"] += f"{msg.name}: {block.text}\n"
+ has_history = True
+ elif isinstance(block, DataBlock):
+ formatted = self._format_openai_data_block(block)
+ if formatted is not None:
+ content_blocks[-1]["text"] += f"{msg.name}: "
+ content_blocks.extend(
+ [
+ formatted,
+ {"type": "text", "text": "\n"},
+ ],
+ )
+ has_history = True
+ has_image = True
- if conversation_blocks_text:
+ if has_history:
+ content_blocks[-1]["text"] += "</history>"
formatted_msgs.append(
{
"role": "user",
- "content": conversation_blocks_text,
+ "content": (
+ content_blocks
+ if has_image
+ else content_blocks[0]["text"]
+ ),
},
)
diff --git a/src/agentscope/formatter/_moonshot_formatter.py b/src/agentscope/formatter/_moonshot_formatter.py
index 6814ef8ff..7d20d8c6b 100644
--- a/src/agentscope/formatter/_moonshot_formatter.py
+++ b/src/agentscope/formatter/_moonshot_formatter.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""The Moonshot AI formatter for agentscope."""
import base64
+from fnmatch import fnmatch
from typing import Any
import requests
@@ -21,10 +22,11 @@ from ..message import (
)
-def _moonshot_format_image_source(
+def _moonshot_format_media_source(
source: URLSource | Base64Source,
) -> dict[str, Any]:
- """Convert an image source to Moonshot ``image_url`` format.
+ """Convert an image or video source to Moonshot ``image_url`` or
+ ``video_url`` format.
Moonshot's vision API only accepts base64 data URIs or file IDs — raw
remote URLs are rejected. This helper downloads remote ``http(s)://``
@@ -48,12 +50,12 @@ def _moonshot_format_image_source(
url = f"data:{source.media_type};base64,{encoded}"
else:
- raise ValueError(f"Unsupported image source type: {type(source)}")
+ raise ValueError(f"Unsupported media source type: {type(source)}")
- return {
- "type": "image_url",
- "image_url": {"url": url},
- }
+ key = (
+ "video_url" if source.media_type.startswith("video/") else "image_url"
+ )
+ return {"type": key, key: {"url": url}}
class MoonshotChatFormatter(_OpenAIFormatterBase):
@@ -67,10 +69,15 @@ class MoonshotChatFormatter(_OpenAIFormatterBase):
"""
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*", "audio/*"],
+ default_factory=lambda: [
+ "text/plain",
+ "image/*",
+ "audio/*",
+ "video/*",
+ ],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*"]``.'
+ "The supported input types. Defaults to "
+ '``["text/plain", "image/*", "audio/*", "video/*"]``.'
),
)
@@ -78,7 +85,19 @@ class MoonshotChatFormatter(_OpenAIFormatterBase):
self,
source: URLSource | Base64Source,
) -> dict[str, Any]:
- return _moonshot_format_image_source(source)
+ return _moonshot_format_media_source(source)
+
+ def _format_openai_data_block(
+ self,
+ block: DataBlock,
+ ) -> dict[str, Any] | None:
+ media_type = block.source.media_type
+ if media_type.startswith("video/") and any(
+ fnmatch(media_type, pattern)
+ for pattern in self.supported_input_media_types
+ ):
+ return _moonshot_format_media_source(block.source)
+ return super()._format_openai_data_block(block)
# pylint: disable=too-many-branches
async def format(
@@ -307,10 +326,15 @@ class MoonshotMultiAgentFormatter(_OpenAIFormatterBase):
)
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*", "audio/*"],
+ default_factory=lambda: [
+ "text/plain",
+ "image/*",
+ "audio/*",
+ "video/*",
+ ],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*"]``.'
+ "The supported input types. Defaults to "
+ '``["text/plain", "image/*", "audio/*", "video/*"]``.'
),
)
@@ -318,7 +342,19 @@ class MoonshotMultiAgentFormatter(_OpenAIFormatterBase):
self,
source: URLSource | Base64Source,
) -> dict[str, Any]:
- return _moonshot_format_image_source(source)
+ return _moonshot_format_media_source(source)
+
+ def _format_openai_data_block(
+ self,
+ block: DataBlock,
+ ) -> dict[str, Any] | None:
+ media_type = block.source.media_type
+ if media_type.startswith("video/") and any(
+ fnmatch(media_type, pattern)
+ for pattern in self.supported_input_media_types
+ ):
+ return _moonshot_format_media_source(block.source)
+ return super()._format_openai_data_block(block)
async def format(self, msgs: list[Msg]) -> list[dict[str, Any]]:
"""Format input messages into the Moonshot AI API format for
diff --git a/tests/formatter_deepseek_test.py b/tests/formatter_deepseek_test.py
index c9b7e6c7a..2131a7393 100644
--- a/tests/formatter_deepseek_test.py
+++ b/tests/formatter_deepseek_test.py
@@ -23,6 +23,9 @@ from agentscope.message import (
)
+_FIXED_ID = "TESTID1234567"
+
+
class TestDeepSeekFormatter(IsolatedAsyncioTestCase):
"""Comprehensive tests for DeepSeek Chat and MultiAgent formatters."""
@@ -213,6 +216,42 @@ class TestDeepSeekFormatter(IsolatedAsyncioTestCase):
# Empty
self.assertListEqual([], await fmt.format([]))
+ async def test_chat_formatter_preserves_user_images(self) -> None:
+ """User images are preserved, while images in other roles are
+ dropped since DeepSeek only accepts them in user messages."""
+ fmt = DeepSeekChatFormatter(input_types=["text/plain", "image/*"])
+ image = DataBlock(
+ source=Base64Source(
+ data="ZmFrZQ==",
+ media_type="image/png",
+ ),
+ )
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="Inspect this image."), image],
+ ),
+ AssistantMsg(name="assistant", content=[image]),
+ ]
+
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Inspect this image."},
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;base64,ZmFrZQ==",
+ },
+ },
+ ],
+ },
+ ],
+ await fmt.format(msgs),
+ )
+
async def test_chat_formatter_reasoning_content_always_present(
self,
) -> None:
@@ -311,6 +350,57 @@ class TestDeepSeekFormatter(IsolatedAsyncioTestCase):
# Empty
self.assertListEqual([], await fmt.format([]))
+ async def test_multiagent_formatter_preserves_all_agent_images(
+ self,
+ ) -> None:
+ """Collapsed history preserves images regardless of source role."""
+ fmt = DeepSeekMultiAgentFormatter(
+ input_types=["text/plain", "image/png"],
+ )
+ msgs = [
+ UserMsg(name="user", content="Inspect the result."),
+ AssistantMsg(
+ name="analyst",
+ content=[
+ TextBlock(text="Here is the screenshot."),
+ DataBlock(
+ source=Base64Source(
+ data="ZmFrZQ==",
+ media_type="image/png",
+ ),
+ ),
+ ],
+ ),
+ ]
+ prompt = fmt.conversation_history_prompt
+
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ f"{prompt}<history>\n"
+ "user: Inspect the result.\n"
+ "analyst: Here is the screenshot.\n"
+ "analyst: "
+ ),
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;base64,ZmFrZQ==",
+ },
+ },
+ {"type": "text", "text": "\n</history>"},
+ ],
+ },
+ ],
+ await fmt.format(msgs),
+ )
+
async def test_chat_formatter_complex_multi_step(self) -> None:
"""Complex multi-step sequence with interleaved thinking, text,
tool calls, and tool results."""
@@ -495,6 +585,104 @@ class TestDeepSeekFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_promotes_tool_result_image(self) -> None:
+ """Tool-result images are promoted after the tool message."""
+ fmt = DeepSeekChatFormatter(
+ input_types=["text/plain", "image/png"],
+ )
+ msgs = [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ToolCallBlock(
+ id="call_image",
+ name="capture",
+ input="{}",
+ ),
+ ToolResultBlock(
+ id="call_image",
+ name="capture",
+ output=[
+ TextBlock(text="Screenshot captured."),
+ DataBlock(
+ id=_FIXED_ID,
+ source=Base64Source(
+ data="ZmFrZQ==",
+ media_type="image/png",
+ ),
+ ),
+ ],
+ state=ToolResultState.SUCCESS,
+ ),
+ TextBlock(text="I can inspect it now."),
+ ],
+ ),
+ ]
+ tool_content = (
+ "Screenshot captured.\n"
+ "<system-reminder>A(n) image file is returned and will be "
+ "presented to you with the identifier "
+ f"[{_FIXED_ID}].</system-reminder>"
+ )
+
+ self.assertListEqual(
+ [
+ {
+ "role": "assistant",
+ "content": None,
+ "reasoning_content": "",
+ "tool_calls": [
+ {
+ "id": "call_image",
+ "type": "function",
+ "function": {
+ "name": "capture",
+ "arguments": "{}",
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_image",
+ "content": tool_content,
+ "name": "capture",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": (
+ "<system-reminder>The multimodal data and "
+ "their identifiers are listed as follows:"
+ ),
+ },
+ {
+ "type": "text",
+ "text": f"- {_FIXED_ID} (image file): ",
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;base64,ZmFrZQ==",
+ },
+ },
+ {
+ "type": "text",
+ "text": "</system-reminder>",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "I can inspect it now.",
+ "reasoning_content": "",
+ },
+ ],
+ await fmt.format(msgs),
+ )
+
async def test_chat_formatter_hint_block_multimodal(self) -> None:
"""DeepSeek is text-only — DataBlock degrades to a placeholder
string."""
diff --git a/tests/formatter_moonshot_test.py b/tests/formatter_moonshot_test.py
index 825cd61a8..1ee827524 100644
--- a/tests/formatter_moonshot_test.py
+++ b/tests/formatter_moonshot_test.py
@@ -419,6 +419,50 @@ class TestMoonshotFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_base64_video(self) -> None:
+ """Base64-encoded video is emitted as a video URL block."""
+ fmt = MoonshotChatFormatter(
+ input_types=["text/plain", "video/mp4"],
+ )
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="What happens in this video?"),
+ DataBlock(
+ source=Base64Source(
+ data="ZmFrZSB2aWRlbw==",
+ media_type="video/mp4",
+ ),
+ ),
+ ],
+ ),
+ ]
+
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What happens in this video?",
+ },
+ {
+ "type": "video_url",
+ "video_url": {
+ "url": (
+ "data:video/mp4;base64," "ZmFrZSB2aWRlbw=="
+ ),
+ },
+ },
+ ],
+ },
+ ],
+ await fmt.format(msgs),
+ )
+
async def test_chat_formatter_url_image_in_tool_result(
self,
) -> None: