Skip to content

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

fix(formatter): implement image extraction from tool results (#938)

qbcf5fdc3740a27
diff --git a/src/agentscope/_version.py b/src/agentscope/_version.py
index 6d54c24c7..b2b674ebc 100644
--- a/src/agentscope/_version.py
+++ b/src/agentscope/_version.py
@@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
"""The version of agentscope."""
-__version__ = "1.0.8dev"
+__version__ = "1.0.8"
diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.py
index 593b8b28d..3a1818325 100644
--- a/src/agentscope/formatter/_anthropic_formatter.py
+++ b/src/agentscope/formatter/_anthropic_formatter.py
@@ -11,7 +11,10 @@ from ..token import TokenCounterBase
class AnthropicChatFormatter(TruncatedFormatterBase):
- """Formatter for Anthropic messages."""
+ """The Anthropic 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.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
diff --git a/src/agentscope/formatter/_dashscope_formatter.py b/src/agentscope/formatter/_dashscope_formatter.py
index d5fd7817c..904cb74ed 100644
--- a/src/agentscope/formatter/_dashscope_formatter.py
+++ b/src/agentscope/formatter/_dashscope_formatter.py
@@ -16,10 +16,53 @@ from ..message import (
AudioBlock,
ToolUseBlock,
ToolResultBlock,
+ URLSource,
)
from ..token import TokenCounterBase
+def _format_dashscope_media_block(
+ block: ImageBlock | AudioBlock,
+) -> dict[str, str]:
+ """Format an image or audio block for DashScope API.
+
+ Args:
+ block (`ImageBlock` | `AudioBlock`):
+ The image or audio block to format.
+
+ Returns:
+ `dict[str, str]`:
+ A dictionary with "image" or "audio" key and the formatted URL or
+ data URI as value.
+
+ Raises:
+ `NotImplementedError`:
+ If the source type is not supported.
+ """
+ typ = block["type"]
+ source = block["source"]
+ if source["type"] == "url":
+ url = source["url"]
+ if _is_accessible_local_file(url):
+ return {typ: "file://" + os.path.abspath(url)}
+ else:
+ # treat as web url
+ return {typ: url}
+
+ elif source["type"] == "base64":
+ media_type = source["media_type"]
+ base64_data = source["data"]
+ return {
+ typ: f"data:{media_type};base64,{base64_data}",
+ }
+
+ else:
+ raise NotImplementedError(
+ f"Unsupported source type '{source.get('type')}' "
+ f"for {typ} block.",
+ )
+
+
def _reformat_messages(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
@@ -101,7 +144,10 @@ def _reformat_messages(
class DashScopeChatFormatter(TruncatedFormatterBase):
- """Formatter for DashScope messages."""
+ """The DashScope 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.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
@@ -120,6 +166,33 @@ class DashScopeChatFormatter(TruncatedFormatterBase):
ToolResultBlock,
]
+ def __init__(
+ self,
+ promote_tool_result_images: bool = False,
+ token_counter: TokenCounterBase | None = None,
+ max_tokens: int | None = None,
+ ) -> None:
+ """Initialize the DashScope chat formatter.
+
+ Args:
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
+ token_counter (`TokenCounterBase | None`, optional):
+ A token counter instance used to count tokens in the messages.
+ If not provided, the formatter will format the messages
+ without considering token limits.
+ max_tokens (`int | None`, optional):
+ The maximum number of tokens allowed in the formatted
+ messages. If not provided, the formatter will not truncate
+ the messages.
+ """
+ super().__init__(token_counter, max_tokens)
+ self.promote_tool_result_images = promote_tool_result_images
+
async def _format(
self,
msgs: list[Msg],
@@ -137,9 +210,13 @@ class DashScopeChatFormatter(TruncatedFormatterBase):
self.assert_list_of_msgs(msgs)
formatted_msgs: list[dict] = []
- for msg in msgs:
- content_blocks = []
+
+ i = 0
+ while i < len(msgs):
+ msg = msgs[i]
+ content_blocks: list[dict[str, Any]] = []
tool_calls = []
+
for block in msg.get_content_blocks():
typ = block.get("type")
@@ -151,29 +228,11 @@ class DashScopeChatFormatter(TruncatedFormatterBase):
)
elif typ in ["image", "audio"]:
- source = block["source"]
- if source["type"] == "url":
- url = source["url"]
- if _is_accessible_local_file(url):
- content_blocks.append(
- {typ: "file://" + os.path.abspath(url)},
- )
- else:
- # treat as web url
- content_blocks.append({typ: url})
-
- elif source["type"] == "base64":
- media_type = source["media_type"]
- base64_data = source["data"]
- content_blocks.append(
- {typ: f"data:{media_type};base64,{base64_data}"},
- )
-
- else:
- raise NotImplementedError(
- f"Unsupported source type '{source.get('type')}' "
- f"for {typ} block.",
- )
+ content_blocks.append(
+ _format_dashscope_media_block(
+ block, # type: ignore[arg-type]
+ ),
+ )
elif typ == "tool_use":
tool_calls.append(
@@ -191,17 +250,69 @@ class DashScopeChatFormatter(TruncatedFormatterBase):
)
elif typ == "tool_result":
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(block["output"])
+
+ # First add the tool result message in DashScope API format
formatted_msgs.append(
{
"role": "tool",
"tool_call_id": block.get("id"),
- "content": self.convert_tool_result_to_string(
- block.get("output"), # type: ignore[arg-type]
- ),
+ "content": textual_output,
"name": block.get("name"),
},
)
+ # Then, handle the multimodal data if any
+ promoted_blocks: list = []
+ for url, multimodal_block in multimodal_data:
+ if (
+ multimodal_block["type"] == "image"
+ and self.promote_tool_result_images
+ ):
+ promoted_blocks.extend(
+ [
+ TextBlock(
+ type="text",
+ text=f"\n- The image from '{url}': ",
+ ),
+ ImageBlock(
+ type="image",
+ source=URLSource(
+ type="url",
+ url=url,
+ ),
+ ),
+ ],
+ )
+
+ if promoted_blocks:
+ # Insert promoted blocks as new user message(s)
+ promoted_blocks = [
+ TextBlock(
+ type="text",
+ text="<system-info>The following are "
+ "the image contents from the tool "
+ f"result of '{block['name']}':",
+ ),
+ *promoted_blocks,
+ TextBlock(
+ type="text",
+ text="</system-info>",
+ ),
+ ]
+
+ msgs.insert(
+ i + 1,
+ Msg(
+ name="user",
+ content=promoted_blocks,
+ role="user",
+ ),
+ )
+
else:
logger.warning(
"Unsupported block type %s in the message, skipped.",
@@ -223,6 +334,9 @@ class DashScopeChatFormatter(TruncatedFormatterBase):
):
formatted_msgs.append(msg_dashscope)
+ # Move to next message
+ i += 1
+
return _reformat_messages(formatted_msgs)
@@ -272,6 +386,7 @@ class DashScopeMultiAgentFormatter(TruncatedFormatterBase):
"The content between <history></history> tags contains "
"your conversation history\n"
),
+ promote_tool_result_images: bool = False,
token_counter: TokenCounterBase | None = None,
max_tokens: int | None = None,
) -> None:
@@ -280,6 +395,12 @@ class DashScopeMultiAgentFormatter(TruncatedFormatterBase):
Args:
conversation_history_prompt (`str`):
The prompt to use for the conversation history section.
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
token_counter (`TokenCounterBase | None`, optional):
The token counter used for truncation.
max_tokens (`int | None`, optional):
@@ -288,6 +409,7 @@ class DashScopeMultiAgentFormatter(TruncatedFormatterBase):
"""
super().__init__(token_counter=token_counter, max_tokens=max_tokens)
self.conversation_history_prompt = conversation_history_prompt
+ self.promote_tool_result_images = promote_tool_result_images
async def _format_tool_sequence(
self,
@@ -304,7 +426,9 @@ class DashScopeMultiAgentFormatter(TruncatedFormatterBase):
`list[dict[str, Any]]`:
A list of dictionaries formatted for the DashScope API.
"""
- return await DashScopeChatFormatter().format(msgs)
+ return await DashScopeChatFormatter(
+ promote_tool_result_images=self.promote_tool_result_images,
+ ).format(msgs)
async def _format_agent_message(
self,
diff --git a/src/agentscope/formatter/_deepseek_formatter.py b/src/agentscope/formatter/_deepseek_formatter.py
index 602c61abc..cd256cdec 100644
--- a/src/agentscope/formatter/_deepseek_formatter.py
+++ b/src/agentscope/formatter/_deepseek_formatter.py
@@ -11,7 +11,10 @@ from ..token import TokenCounterBase
class DeepSeekChatFormatter(TruncatedFormatterBase):
- """Formatter for DeepSeek messages."""
+ """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.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
@@ -72,13 +75,14 @@ class DeepSeekChatFormatter(TruncatedFormatterBase):
)
elif typ == "tool_result":
+ textual_output, _ = self.convert_tool_result_to_string(
+ block.get("output"), # type: ignore[arg-type]
+ )
messages.append(
{
"role": "tool",
"tool_call_id": block.get("id"),
- "content": self.convert_tool_result_to_string(
- block.get("output"), # type: ignore[arg-type]
- ),
+ "content": textual_output,
"name": block.get("name"),
},
)
diff --git a/src/agentscope/formatter/_formatter_base.py b/src/agentscope/formatter/_formatter_base.py
index b6b9813f3..ba28c3032 100644
--- a/src/agentscope/formatter/_formatter_base.py
+++ b/src/agentscope/formatter/_formatter_base.py
@@ -2,7 +2,7 @@
"""The formatter module."""
from abc import abstractmethod
-from typing import Any, List
+from typing import Any, List, Tuple, Sequence
from .._utils._common import _save_base64_data
from ..message import Msg, AudioBlock, ImageBlock, TextBlock
@@ -36,9 +36,14 @@ class FormatterBase:
@staticmethod
def convert_tool_result_to_string(
output: str | List[TextBlock | ImageBlock | AudioBlock],
- ) -> str:
+ ) -> tuple[str, Sequence[Tuple[str, ImageBlock | AudioBlock | TextBlock]]]:
"""Turn the tool result list into a textual output to be compatible
- with the LLM API that doesn't support multimodal data.
+ with the LLM API that doesn't support multimodal data in the tool
+ result.
+
+ For URL-based images, the URL is included in the list. For
+ base64-encoded images, the local file path where the image is saved
+ is included in the returned list.
Args:
output (`str | List[TextBlock | ImageBlock | AudioBlock]`):
@@ -46,16 +51,19 @@ class FormatterBase:
data like images and audio.
Returns:
- `str`:
- A string representation of the tool result, with text blocks
- concatenated and multimodal data represented by file paths
- or URLs.
+ `tuple[str, list[Tuple[str, ImageBlock | AudioBlock | \
+ TextBlock]]]`:
+ A tuple containing the textual representation of the tool
+ result and a list of tuples. The first element of each tuple
+ is the local file path or URL of the multimodal data, and the
+ second element is the corresponding block.
"""
if isinstance(output, str):
- return output
+ return output, []
textual_output = []
+ multimodal_data = []
for block in output:
assert isinstance(block, dict) and "type" in block, (
f"Invalid block: {block}, a TextBlock, ImageBlock, or "
@@ -77,14 +85,16 @@ class FormatterBase:
f"at: {source['url']}",
)
+ path_multimodal_file = source["url"]
+
elif source["type"] == "base64":
- path_temp_file = _save_base64_data(
+ path_multimodal_file = _save_base64_data(
source["media_type"],
source["data"],
)
textual_output.append(
f"The returned {block['type']} can be found "
- f"at: {path_temp_file}",
+ f"at: {path_multimodal_file}",
)
else:
@@ -93,6 +103,10 @@ class FormatterBase:
"expected 'url' or 'base64'.",
)
+ multimodal_data.append(
+ (path_multimodal_file, block),
+ )
+
else:
raise ValueError(
f"Unsupported block type: {block['type']}, "
@@ -100,7 +114,7 @@ class FormatterBase:
)
if len(textual_output) == 1:
- return textual_output[0]
+ return textual_output[0], multimodal_data
else:
- return "\n".join("- " + _ for _ in textual_output)
+ return "\n".join("- " + _ for _ in textual_output), multimodal_data
diff --git a/src/agentscope/formatter/_gemini_formatter.py b/src/agentscope/formatter/_gemini_formatter.py
index c9cbd5674..814838b04 100644
--- a/src/agentscope/formatter/_gemini_formatter.py
+++ b/src/agentscope/formatter/_gemini_formatter.py
@@ -16,11 +16,47 @@ from ..message import (
ToolUseBlock,
ToolResultBlock,
VideoBlock,
+ URLSource,
)
from .._logging import logger
from ..token import TokenCounterBase
+def _format_gemini_media_block(
+ media_block: ImageBlock | AudioBlock | VideoBlock,
+) -> dict[str, Any]:
+ """Format an image/audio/video block for Gemini API.
+
+ Args:
+ media_block (`ImageBlock | AudioBlock | VideoBlock`):
+ The media block to format.
+
+ Returns:
+ `dict[str, Any]`:
+ A dictionary with "inline_data" key in Gemini format.
+
+ Raises:
+ `ValueError`:
+ If the source type is not supported.
+ """
+ source = media_block["source"]
+ if source["type"] == "base64":
+ return {
+ "inline_data": {
+ "data": source["data"],
+ "mime_type": source["media_type"],
+ },
+ }
+ elif source["type"] == "url":
+ return {
+ "inline_data": _to_gemini_inline_data(source["url"]),
+ }
+ else:
+ raise ValueError(
+ f"Unsupported source type: {source['type']}",
+ )
+
+
def _to_gemini_inline_data(url: str) -> dict:
"""Convert url into the Gemini API required format."""
parsed_url = urlparse(url)
@@ -69,7 +105,10 @@ def _to_gemini_inline_data(url: str) -> dict:
class GeminiChatFormatter(TruncatedFormatterBase):
- """The formatter for Google Gemini API."""
+ """The Gemini 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.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
@@ -108,6 +147,33 @@ class GeminiChatFormatter(TruncatedFormatterBase):
"audio": ["mp3", "wav", "aiff", "aac", "ogg", "flac"],
}
+ def __init__(
+ self,
+ promote_tool_result_images: bool = False,
+ token_counter: TokenCounterBase | None = None,
+ max_tokens: int | None = None,
+ ) -> None:
+ """Initialize the Gemini chat formatter.
+
+ Args:
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
+ token_counter (`TokenCounterBase | None`, optional):
+ A token counter instance used to count tokens in the messages.
+ If not provided, the formatter will format the messages
+ without considering token limits.
+ max_tokens (`int | None`, optional):
+ The maximum number of tokens allowed in the formatted
+ messages. If not provided, the formatter will not truncate
+ the messages.
+ """
+ super().__init__(token_counter, max_tokens)
+ self.promote_tool_result_images = promote_tool_result_images
+
async def _format(
self,
msgs: list[Msg],
@@ -116,7 +182,9 @@ class GeminiChatFormatter(TruncatedFormatterBase):
self.assert_list_of_msgs(msgs)
messages: list = []
- for msg in msgs:
+ i = 0
+ while i < len(msgs):
+ msg = msgs[i]
parts = []
for block in msg.get_content_blocks():
@@ -140,9 +208,12 @@ class GeminiChatFormatter(TruncatedFormatterBase):
)
elif typ == "tool_result":
- text_output = self.convert_tool_result_to_string(
- block["output"], # type: ignore[arg-type]
- )
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(block["output"])
+
+ # First add the tool result message in DashScope API format
messages.append(
{
"role": "user",
@@ -152,7 +223,7 @@ class GeminiChatFormatter(TruncatedFormatterBase):
"id": block["id"],
"name": block["name"],
"response": {
- "output": text_output,
+ "output": textual_output,
},
},
},
@@ -160,28 +231,59 @@ class GeminiChatFormatter(TruncatedFormatterBase):
},
)
- elif typ in ["image", "audio", "video"]:
- if block["source"]["type"] == "base64":
- media_type = block["source"]["media_type"]
- base64_data = block["source"]["data"]
-
- parts.append(
- {
- "inline_data": {
- "data": base64_data,
- "mime_type": media_type,
- },
- },
+ promoted_blocks: list = []
+ for url, multimodal_block in multimodal_data:
+ if (
+ multimodal_block["type"] == "image"
+ and self.promote_tool_result_images
+ ):
+ promoted_blocks.extend(
+ [
+ TextBlock(
+ type="text",
+ text=f"\n- The image from '{url}': ",
+ ),
+ ImageBlock(
+ type="image",
+ source=URLSource(
+ type="url",
+ url=url,
+ ),
+ ),
+ ],
+ )
+
+ if promoted_blocks:
+ # Insert promoted blocks as new user message(s)
+ promoted_blocks = [
+ TextBlock(
+ type="text",
+ text="<system-info>The following are "
+ "the image contents from the tool "
+ f"result of '{block['name']}':",
+ ),
+ *promoted_blocks,
+ TextBlock(
+ type="text",
+ text="</system-info>",
+ ),
+ ]
+
+ msgs.insert(
+ i + 1,
+ Msg(
+ name="user",
+ content=promoted_blocks,
+ role="user",
+ ),
)
- elif block["source"]["type"] == "url":
- parts.append(
- {
- "inline_data": _to_gemini_inline_data(
- block["source"]["url"],
- ),
- },
- )
+ elif typ in ["image", "audio", "video"]:
+ parts.append(
+ _format_gemini_media_block(
+ block, # type: ignore[arg-type]
+ ),
+ )
else:
logger.warning(
@@ -199,6 +301,10 @@ class GeminiChatFormatter(TruncatedFormatterBase):
},
)
+ # Move to next message (including inserted messages, which will
+ # be processed in subsequent iterations)
+ i += 1
+
return messages
@@ -249,6 +355,7 @@ class GeminiMultiAgentFormatter(TruncatedFormatterBase):
"The content between <history></history> tags contains "
"your conversation history\n"
),
+ promote_tool_result_images: bool = False,
token_counter: TokenCounterBase | None = None,
max_tokens: int | None = None,
) -> None:
@@ -257,6 +364,12 @@ class GeminiMultiAgentFormatter(TruncatedFormatterBase):
Args:
conversation_history_prompt (`str`):
The prompt to be used for the conversation history section.
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
token_counter (`TokenCounterBase | None`, optional):
The token counter used for truncation.
max_tokens (`int | None`, optional):
@@ -265,6 +378,7 @@ class GeminiMultiAgentFormatter(TruncatedFormatterBase):
"""
super().__init__(token_counter=token_counter, max_tokens=max_tokens)
self.conversation_history_prompt = conversation_history_prompt
+ self.promote_tool_result_images = promote_tool_result_images
async def _format_system_message(
self,
@@ -295,7 +409,9 @@ class GeminiMultiAgentFormatter(TruncatedFormatterBase):
`list[dict[str, Any]]`:
A list of dictionaries formatted for the Gemini API.
"""
- return await GeminiChatFormatter().format(msgs)
+ return await GeminiChatFormatter(
+ promote_tool_result_images=self.promote_tool_result_images,
+ ).format(msgs)
async def _format_agent_message(
self,
@@ -344,26 +460,11 @@ class GeminiMultiAgentFormatter(TruncatedFormatterBase):
accumulated_text.clear()
# handle the multimodal data
- if block["source"]["type"] == "url":
- conversation_parts.append(
- {
- "inline_data": _to_gemini_inline_data(
- block["source"]["url"],
- ),
- },
- )
-
- elif block["source"]["type"] == "base64":
- media_type = block["source"]["media_type"]
- base64_data = block["source"]["data"]
- conversation_parts.append(
- {
- "inline_data": {
- "data": base64_data,
- "mime_type": media_type,
- },
- },
- )
+ conversation_parts.append(
+ _format_gemini_media_block(
+ block, # type: ignore[arg-type]
+ ),
+ )
if accumulated_text:
conversation_parts.append(
diff --git a/src/agentscope/formatter/_ollama_formatter.py b/src/agentscope/formatter/_ollama_formatter.py
index d12d8786a..b671f8449 100644
--- a/src/agentscope/formatter/_ollama_formatter.py
+++ b/src/agentscope/formatter/_ollama_formatter.py
@@ -9,10 +9,45 @@ from urllib.parse import urlparse
from ._truncated_formatter_base import TruncatedFormatterBase
from .._logging import logger
from .._utils._common import _get_bytes_from_web_url
-from ..message import Msg, TextBlock, ImageBlock, ToolUseBlock, ToolResultBlock
+from ..message import (
+ Msg,
+ TextBlock,
+ ImageBlock,
+ ToolUseBlock,
+ ToolResultBlock,
+ URLSource,
+)
from ..token import TokenCounterBase
+def _format_ollama_image_block(
+ image_block: ImageBlock,
+) -> str:
+ """Format an image block for Ollama API.
+
+ Args:
+ image_block (`ImageBlock`):
+ The image block to format.
+
+ Returns:
+ `str`:
+ Base64 encoded image data as a string.
+
+ Raises:
+ `ValueError`:
+ If the source type is not supported.
+ """
+ source = image_block["source"]
+ if source["type"] == "url":
+ return _convert_ollama_image_url_to_base64_data(source["url"])
+ elif source["type"] == "base64":
+ return source["data"]
+ else:
+ raise ValueError(
+ f"Unsupported image source type: {source['type']}",
+ )
+
+
def _convert_ollama_image_url_to_base64_data(url: str) -> str:
"""Convert image url to base64."""
parsed_url = urlparse(url)
@@ -34,7 +69,10 @@ def _convert_ollama_image_url_to_base64_data(url: str) -> str:
class OllamaChatFormatter(TruncatedFormatterBase):
- """Formatter for Ollama messages."""
+ """The Ollama formatter class for chatbot scenario, where only a user
+ and an agent are involved. We use the `role` field to identify different
+ participants in the conversation.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
@@ -55,6 +93,33 @@ class OllamaChatFormatter(TruncatedFormatterBase):
]
"""The list of supported message blocks"""
+ def __init__(
+ self,
+ promote_tool_result_images: bool = False,
+ token_counter: TokenCounterBase | None = None,
+ max_tokens: int | None = None,
+ ) -> None:
+ """Initialize the Ollama chat formatter.
+
+ Args:
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
+ token_counter (`TokenCounterBase | None`, optional):
+ A token counter instance used to count tokens in the messages.
+ If not provided, the formatter will format the messages
+ without considering token limits.
+ max_tokens (`int | None`, optional):
+ The maximum number of tokens allowed in the formatted
+ messages. If not provided, the formatter will not truncate
+ the messages.
+ """
+ super().__init__(token_counter, max_tokens)
+ self.promote_tool_result_images = promote_tool_result_images
+
async def _format(
self,
msgs: list[Msg],
@@ -71,8 +136,10 @@ class OllamaChatFormatter(TruncatedFormatterBase):
"""
self.assert_list_of_msgs(msgs)
- messages: list[dict] = []
- for msg in msgs:
+ messages: list = []
+ i = 0
+ while i < len(msgs):
+ msg = msgs[i]
content_blocks: list = []
tool_calls = []
images = []
@@ -95,27 +162,74 @@ class OllamaChatFormatter(TruncatedFormatterBase):
)
elif typ == "tool_result":
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(block["output"])
+
messages.append(
{
"role": "tool",
"tool_call_id": block.get("id"),
- "content": self.convert_tool_result_to_string(
- block.get("output"), # type: ignore[arg-type]
- ),
+ "content": textual_output,
"name": block.get("name"),
},
)
- elif typ == "image":
- source_type = block["source"]["type"]
- if source_type == "url":
- images.append(
- _convert_ollama_image_url_to_base64_data(
- block["source"]["url"],
+ # Then, handle the multimodal data if any
+ promoted_blocks: list = []
+ for url, multimodal_block in multimodal_data:
+ if (
+ multimodal_block["type"] == "image"
+ and self.promote_tool_result_images
+ ):
+ promoted_blocks.extend(
+ [
+ TextBlock(
+ type="text",
+ text=f"\n- The image from '{url}': ",
+ ),
+ ImageBlock(
+ type="image",
+ source=URLSource(
+ type="url",
+ url=url,
+ ),
+ ),
+ ],
+ )
+
+ if promoted_blocks:
+ # Insert promoted blocks as new user message(s)
+ promoted_blocks = [
+ TextBlock(
+ type="text",
+ text="<system-info>The following are "
+ "the image contents from the tool "
+ f"result of '{block['name']}':",
+ ),
+ *promoted_blocks,
+ TextBlock(
+ type="text",
+ text="</system-info>",
+ ),
+ ]
+
+ msgs.insert(
+ i + 1,
+ Msg(
+ name="user",
+ content=promoted_blocks,
+ role="user",
),
)
- elif source_type == "base64":
- images.append(block["source"]["data"])
+
+ elif typ == "image":
+ images.append(
+ _format_ollama_image_block(
+ block, # type: ignore[arg-type]
+ ),
+ )
else:
logger.warning(
@@ -136,9 +250,16 @@ class OllamaChatFormatter(TruncatedFormatterBase):
if images:
msg_ollama["images"] = images
- if msg_ollama["content"] or msg_ollama.get("tool_calls"):
+ if (
+ msg_ollama["content"]
+ or msg_ollama.get("images")
+ or msg_ollama.get("tool_calls")
+ ):
messages.append(msg_ollama)
+ # Move to next message
+ i += 1
+
return messages
@@ -174,6 +295,7 @@ class OllamaMultiAgentFormatter(TruncatedFormatterBase):
"The content between <history></history> tags contains "
"your conversation history\n"
),
+ promote_tool_result_images: bool = False,
token_counter: TokenCounterBase | None = None,
max_tokens: int | None = None,
) -> None:
@@ -182,6 +304,12 @@ class OllamaMultiAgentFormatter(TruncatedFormatterBase):
Args:
conversation_history_prompt (`str`):
The prompt to use for the conversation history section.
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
token_counter (`TokenCounterBase | None`, optional):
The token counter used for truncation.
max_tokens (`int | None`, optional):
@@ -190,6 +318,7 @@ class OllamaMultiAgentFormatter(TruncatedFormatterBase):
"""
super().__init__(token_counter=token_counter, max_tokens=max_tokens)
self.conversation_history_prompt = conversation_history_prompt
+ self.promote_tool_result_images = promote_tool_result_images
async def _format_system_message(
self,
@@ -216,7 +345,9 @@ class OllamaMultiAgentFormatter(TruncatedFormatterBase):
`list[dict[str, Any]]`:
A list of dictionaries formatted for the Ollama API.
"""
- return await OllamaChatFormatter().format(msgs)
+ return await OllamaChatFormatter(
+ promote_tool_result_images=self.promote_tool_result_images,
+ ).format(msgs)
async def _format_agent_message(
self,
@@ -257,23 +388,13 @@ class OllamaMultiAgentFormatter(TruncatedFormatterBase):
elif block["type"] == "image":
# Handle the accumulated text as a single block
- source = block["source"]
if accumulated_text:
conversation_blocks.append(
{"text": "\n".join(accumulated_text)},
)
accumulated_text.clear()
- if source["type"] == "url":
- images.append(
- _convert_ollama_image_url_to_base64_data(
- source["url"],
- ),
- )
-
- elif source["type"] == "base64":
- images.append(source["data"])
-
+ images.append(_format_ollama_image_block(block))
conversation_blocks.append({**block})
if accumulated_text:
diff --git a/src/agentscope/formatter/_openai_formatter.py b/src/agentscope/formatter/_openai_formatter.py
index 69c4ec782..e61425b3a 100644
--- a/src/agentscope/formatter/_openai_formatter.py
+++ b/src/agentscope/formatter/_openai_formatter.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# pylint: disable=too-many-branches
+# pylint: disable=too-many-branches, too-many-nested-blocks
"""The OpenAI formatter for agentscope."""
import base64
import json
@@ -24,6 +24,43 @@ from ..message import (
from ..token import TokenCounterBase
+def _format_openai_image_block(
+ image_block: ImageBlock,
+) -> dict[str, Any]:
+ """Format an image block for OpenAI API.
+
+ Args:
+ image_block (`ImageBlock`):
+ The image block to format.
+
+ Returns:
+ `dict[str, Any]`:
+ A dictionary with "type" and "image_url" keys in OpenAI format.
+
+ Raises:
+ `ValueError`:
+ If the source type is not supported.
+ """
+ source = image_block["source"]
+ if source["type"] == "url":
+ url = _to_openai_image_url(source["url"])
+ elif source["type"] == "base64":
+ data = source["data"]
+ media_type = source["media_type"]
+ url = f"data:{media_type};base64,{data}"
+ else:
+ raise ValueError(
+ f"Unsupported image source type: {source['type']}",
+ )
+
+ return {
+ "type": "image_url",
+ "image_url": {
+ "url": url,
+ },
+ }
+
+
def _to_openai_image_url(url: str) -> str:
"""Convert an image url to openai format. If the given url is a local
file, it will be converted to base64 format. Otherwise, it will be
@@ -118,8 +155,10 @@ def _to_openai_audio_data(source: URLSource | Base64Source) -> dict:
class OpenAIChatFormatter(TruncatedFormatterBase):
- """The class used to format message objects into the OpenAI API required
- format."""
+ """The OpenAI formatter class for chatbot scenario, where only a user
+ and an agent are involved. We use the `name` field in OpenAI API to
+ identify different entities in the conversation.
+ """
support_tools_api: bool = True
"""Whether support tools API"""
@@ -139,6 +178,33 @@ class OpenAIChatFormatter(TruncatedFormatterBase):
]
"""Supported message blocks for OpenAI API"""
+ def __init__(
+ self,
+ promote_tool_result_images: bool = False,
+ token_counter: TokenCounterBase | None = None,
+ max_tokens: int | None = None,
+ ) -> None:
+ """Initialize the OpenAI chat formatter.
+
+ Args:
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
+ token_counter (`TokenCounterBase | None`, optional):
+ A token counter instance used to count tokens in the messages.
+ If not provided, the formatter will format the messages
+ without considering token limits.
+ max_tokens (`int | None`, optional):
+ The maximum number of tokens allowed in the formatted
+ messages. If not provided, the formatter will not truncate
+ the messages.
+ """
+ super().__init__(token_counter=token_counter, max_tokens=max_tokens)
+ self.promote_tool_result_images = promote_tool_result_images
+
async def _format(
self,
msgs: list[Msg],
@@ -157,7 +223,9 @@ class OpenAIChatFormatter(TruncatedFormatterBase):
self.assert_list_of_msgs(msgs)
messages: list[dict] = []
- for msg in msgs:
+ i = 0
+ while i < len(msgs):
+ msg = msgs[i]
content_blocks = []
tool_calls = []
@@ -182,39 +250,75 @@ class OpenAIChatFormatter(TruncatedFormatterBase):
)
elif typ == "tool_result":
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(block["output"])
+
messages.append(
{
"role": "tool",
"tool_call_id": block.get("id"),
- "content": self.convert_tool_result_to_string(
- block.get("output"), # type: ignore[arg-type]
+ "content": ( # type: ignore[arg-type]
+ textual_output
),
"name": block.get("name"),
},
)
- elif typ == "image":
- source_type = block["source"]["type"]
- if source_type == "url":
- url = _to_openai_image_url(block["source"]["url"])
-
- elif source_type == "base64":
- data = block["source"]["data"]
- media_type = block["source"]["media_type"]
- url = f"data:{media_type};base64,{data}"
-
- else:
- raise ValueError(
- f"Unsupported image source type: {source_type}",
+ # Then, handle the multimodal data if any
+ promoted_blocks: list = []
+ for url, multimodal_block in multimodal_data:
+ if (
+ multimodal_block["type"] == "image"
+ and self.promote_tool_result_images
+ ):
+ promoted_blocks.extend(
+ [
+ TextBlock(
+ type="text",
+ text=f"\n- The image from '{url}': ",
+ ),
+ ImageBlock(
+ type="image",
+ source=URLSource(
+ type="url",
+ url=url,
+ ),
+ ),
+ ],
+ )
+
+ if promoted_blocks:
+ # Insert promoted blocks as new user message(s)
+ promoted_blocks = [
+ TextBlock(
+ type="text",
+ text="<system-info>The following are "
+ "the image contents from the tool "
+ f"result of '{block['name']}':",
+ ),
+ *promoted_blocks,
+ TextBlock(
+ type="text",
+ text="</system-info>",
+ ),
+ ]
+
+ msgs.insert(
+ i + 1,
+ Msg(
+ name="user",
+ content=promoted_blocks,
+ role="user",
+ ),
)
+ elif typ == "image":
content_blocks.append(
- {
- "type": "image_url",
- "image_url": {
- "url": url,
- },
- },
+ _format_openai_image_block(
+ block, # type: ignore[arg-type]
+ ),
)
elif typ == "audio":
@@ -245,6 +349,9 @@ class OpenAIChatFormatter(TruncatedFormatterBase):
if msg_openai["content"] or msg_openai.get("tool_calls"):
messages.append(msg_openai)
+ # Move to next message
+ i += 1
+
return messages
@@ -281,6 +388,7 @@ class OpenAIMultiAgentFormatter(TruncatedFormatterBase):
"The content between <history></history> tags contains "
"your conversation history\n"
),
+ promote_tool_result_images: bool = False,
token_counter: TokenCounterBase | None = None,
max_tokens: int | None = None,
) -> None:
@@ -289,9 +397,24 @@ class OpenAIMultiAgentFormatter(TruncatedFormatterBase):
Args:
conversation_history_prompt (`str`):
The prompt to use for the conversation history section.
+ promote_tool_result_images (`bool`, defaults to `False`):
+ Whether to promote images from tool results to user messages.
+ Most LLM APIs don't support images in tool result blocks, but
+ do support them in user message blocks. When `True`, images are
+ extracted and appended as a separate user message with
+ explanatory text indicating their source.
+ token_counter (`TokenCounterBase | None`, optional):
+ A token counter instance used to count tokens in the messages.
+ If not provided, the formatter will format the messages
+ without considering token limits.
+ max_tokens (`int | None`, optional):
+ The maximum number of tokens allowed in the formatted
+ messages. If not provided, the formatter will not truncate
+ the messages.
"""
super().__init__(token_counter=token_counter, max_tokens=max_tokens)
self.conversation_history_prompt = conversation_history_prompt
+ self.promote_tool_result_images = promote_tool_result_images
async def _format_tool_sequence(
self,
@@ -299,7 +422,9 @@ class OpenAIMultiAgentFormatter(TruncatedFormatterBase):
) -> list[dict[str, Any]]:
"""Given a sequence of tool call/result messages, format them into
the required format for the OpenAI API."""
- return await OpenAIChatFormatter().format(msgs)
+ return await OpenAIChatFormatter(
+ promote_tool_result_images=self.promote_tool_result_images,
+ ).format(msgs)
async def _format_agent_message(
self,
@@ -328,27 +453,7 @@ class OpenAIMultiAgentFormatter(TruncatedFormatterBase):
accumulated_text.append(f"{msg.name}: {block['text']}")
elif block["type"] == "image":
- source_type = block["source"]["type"]
- if source_type == "url":
- url = _to_openai_image_url(block["source"]["url"])
-
- elif source_type == "base64":
- data = block["source"]["data"]
- media_type = block["source"]["media_type"]
- url = f"data:{media_type};base64,{data}"
-
- else:
- raise ValueError(
- f"Unsupported image source type: {source_type}",
- )
- images.append(
- {
- "type": "image_url",
- "image_url": {
- "url": url,
- },
- },
- )
+ images.append(_format_openai_image_block(block))
elif block["type"] == "audio":
input_audio = _to_openai_audio_data(block["source"])
audios.append(
diff --git a/tests/formatter_dashscope_test.py b/tests/formatter_dashscope_test.py
index 779d19eab..cdd0a8720 100644
--- a/tests/formatter_dashscope_test.py
+++ b/tests/formatter_dashscope_test.py
@@ -523,6 +523,112 @@ class TestDashScopeFormatter(IsolatedAsyncioTestCase):
res = await formatter.format([])
self.assertListEqual(res, [])
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_chat_formatter_with_extract_image_blocks(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the chat formatter with promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = DashScopeChatFormatter(promote_tool_result_images=True)
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],
+ )
+
+ # Expected result: image blocks should be extracted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "content": "You're a helpful assistant.",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "text": "What is the capital of France?",
+ },
+ {
+ "image": f"file://{os.path.abspath(self.image_path)}",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "The capital of France is Paris.",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "text": "What is the capital of Germany?",
+ },
+ {
+ "audio": "https://example.com/audio1.mp3",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "The capital of Germany is Berlin.",
+ },
+ {
+ "role": "user",
+ "content": "What is the capital of Japan?",
+ },
+ {
+ "role": "assistant",
+ "content": [{"text": None}],
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": '{"country": "Japan"}',
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n"
+ "- The returned image can be found at: ./image.png"
+ "\n- The returned audio can be found at: "
+ f"{self.mock_audio_path}",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "text": "\n- The image from './image.png': ",
+ },
+ {
+ "image": f"file://{os.path.abspath(self.image_path)}",
+ },
+ {
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "The capital of Japan is Tokyo.",
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
@patch("agentscope.formatter._formatter_base._save_base64_data")
async def test_multiagent_formater(
self,
@@ -624,6 +730,117 @@ class TestDashScopeFormatter(IsolatedAsyncioTestCase):
self.ground_truth_multiagent_without_first_conversation[1:],
)
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_multiagent_formatter_with_promote_tool_result_images(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the multi-agent formatter with
+ promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = DashScopeMultiAgentFormatter(
+ promote_tool_result_images=True,
+ )
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [
+ *self.msgs_system,
+ *self.msgs_conversation,
+ *self.msgs_tools,
+ ],
+ )
+
+ # Expected result: image blocks should be promoted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "content": "You're a helpful assistant.",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "text": "# Conversation History\nThe content between"
+ " <history></history> tags contains your"
+ " conversation history\n<history>\nuser: What"
+ " is the capital of France?",
+ },
+ {
+ "image": f"file://{os.path.abspath(self.image_path)}",
+ },
+ {
+ "text": "assistant: The capital of France is Paris."
+ "\nuser: What is the capital of Germany?",
+ },
+ {
+ "audio": "https://example.com/audio1.mp3",
+ },
+ {
+ "text": "assistant: The capital of Germany is Berlin."
+ "\nuser: What is the capital of Japan?"
+ "\n</history>",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "text": None,
+ },
+ ],
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": '{"country": "Japan"}',
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n- The returned"
+ " image can be found at: ./image.png\n- The"
+ " returned audio can be found at: "
+ f"{self.mock_audio_path}",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "text": "\n- The image from './image.png': ",
+ },
+ {
+ "image": f"file://{os.path.abspath(self.image_path)}",
+ },
+ {
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": "<history>\nassistant:"
+ " The capital of Japan is Tokyo.\n</history>",
+ },
+ ]
+
+ self.maxDiff = None
+ self.assertListEqual(expected_result, res)
+
async def asyncTearDown(self) -> None:
"""Clean up the test environment."""
if os.path.exists(self.image_path):
diff --git a/tests/formatter_gemini_test.py b/tests/formatter_gemini_test.py
index a502accc5..7530ad404 100644
--- a/tests/formatter_gemini_test.py
+++ b/tests/formatter_gemini_test.py
@@ -616,6 +616,151 @@ class TestGeminiFormatter(IsolatedAsyncioTestCase):
self.ground_truth_chat[: -len(self.msgs_tools)],
)
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_chat_formatter_with_extract_image_blocks(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the gemini chat formatter with
+ promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = GeminiChatFormatter(promote_tool_result_images=True)
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],
+ )
+
+ # Expected result: image blocks should be extracted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "You're a helpful assistant.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "What is the capital of France?",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBpbWFnZSBjb250ZW50",
+ "mime_type": "image/png",
+ },
+ },
+ ],
+ },
+ {
+ "role": "model",
+ "parts": [
+ {
+ "text": "The capital of France is Paris.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "What is the capital of Germany?",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBhdWRpbyBjb250ZW50",
+ "mime_type": "audio/mp3",
+ },
+ },
+ ],
+ },
+ {
+ "role": "model",
+ "parts": [
+ {
+ "text": "The capital of Germany is Berlin.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "What is the capital of Japan?",
+ },
+ ],
+ },
+ {
+ "role": "model",
+ "parts": [
+ {
+ "function_call": {
+ "id": "1",
+ "name": "get_capital",
+ "args": {
+ "country": "Japan",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "function_response": {
+ "id": "1",
+ "name": "get_capital",
+ "response": {
+ "output": "- The capital of Japan is Tokyo.\n"
+ "- The returned image can be found"
+ " at: ./image.png\n- The returned "
+ "audio can be found at: "
+ f"{self.mock_audio_path}",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "text": "\n- The image from './image.png': ",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBpbWFnZSBjb250ZW50",
+ "mime_type": "image/png",
+ },
+ },
+ {
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "model",
+ "parts": [
+ {
+ "text": "The capital of Japan is Tokyo.",
+ },
+ ],
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
@patch("agentscope.formatter._formatter_base._save_base64_data")
async def test_multi_agent_formatter(
self,
@@ -707,6 +852,138 @@ class TestGeminiFormatter(IsolatedAsyncioTestCase):
self.ground_truth_multiagent_without_first_conversation[1:],
)
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_multi_agent_formatter_with_promote_tool_result_images(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the gemini multi-agent formatter with
+ promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = GeminiMultiAgentFormatter(
+ promote_tool_result_images=True,
+ )
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [
+ *self.msgs_system,
+ *self.msgs_conversation,
+ *self.msgs_tools,
+ ],
+ )
+
+ # Expected result: image blocks should be promoted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "You're a helpful assistant.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "# Conversation History\nThe content between"
+ " <history></history> tags contains your"
+ " conversation history\n<history>user: What"
+ " is the capital of France?",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBpbWFnZSBjb250ZW50",
+ "mime_type": "image/png",
+ },
+ },
+ {
+ "text": "assistant: The capital of France is Paris."
+ "\nuser: What is the capital of Germany?",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBhdWRpbyBjb250ZW50",
+ "mime_type": "audio/mp3",
+ },
+ },
+ {
+ "text": "assistant: The capital of Germany is Berlin."
+ "\nuser: What is the capital of Japan?"
+ "\n</history>",
+ },
+ ],
+ },
+ {
+ "role": "model",
+ "parts": [
+ {
+ "function_call": {
+ "id": "1",
+ "name": "get_capital",
+ "args": {
+ "country": "Japan",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "function_response": {
+ "id": "1",
+ "name": "get_capital",
+ "response": {
+ "output": "- The capital of Japan is Tokyo."
+ "\n- The returned image can be found"
+ " at: ./image.png\n- The returned"
+ " audio can be found at: "
+ f"{self.mock_audio_path}",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "text": "\n- The image from './image.png': ",
+ },
+ {
+ "inline_data": {
+ "data": "ZmFrZSBpbWFnZSBjb250ZW50",
+ "mime_type": "image/png",
+ },
+ },
+ {
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "text": "<history>assistant:"
+ " The capital of Japan is Tokyo.\n</history>",
+ },
+ ],
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
async def asyncTearDown(self) -> None:
"""Clean up the test environment."""
if os.path.exists(self.image_path):
diff --git a/tests/formatter_ollama_test.py b/tests/formatter_ollama_test.py
index 8d4fc40e5..546de34d3 100644
--- a/tests/formatter_ollama_test.py
+++ b/tests/formatter_ollama_test.py
@@ -407,6 +407,81 @@ class TestOllamaFormatter(IsolatedAsyncioTestCase):
self.ground_truth_chat[: -len(self.msgs_tools)],
)
+ async def test_chat_formatter_with_extract_image_blocks(
+ self,
+ ) -> None:
+ """Test the Ollama chat formatter with
+ promote_tool_result_images=True."""
+ formatter = OllamaChatFormatter(promote_tool_result_images=True)
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],
+ )
+
+ # Expected result: image blocks should be extracted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "content": "You're a helpful assistant.",
+ },
+ {
+ "role": "user",
+ "content": "What is the capital of France?",
+ "images": [
+ "ZmFrZSBpbWFnZSBjb250ZW50",
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "The capital of France is Paris.",
+ },
+ {
+ "role": "user",
+ "content": "What is the capital of Japan?",
+ },
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": {
+ "country": "Japan",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n- The returned "
+ "image can be found at: ./image.png",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "content": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':\n\n- The image from "
+ "'./image.png': \n</system-info>",
+ "images": [
+ "ZmFrZSBpbWFnZSBjb250ZW50",
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": "The capital of Japan is Tokyo.",
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
async def test_multi_agent_formatter(
self,
) -> None:
@@ -496,6 +571,85 @@ class TestOllamaFormatter(IsolatedAsyncioTestCase):
self.ground_truth_multiagent_without_first_conversation[1:],
)
+ async def test_multi_agent_formatter_with_promote_tool_result_images(
+ self,
+ ) -> None:
+ """Test the Ollama multi-agent formatter with
+ promote_tool_result_images=True."""
+ formatter = OllamaMultiAgentFormatter(
+ promote_tool_result_images=True,
+ )
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [
+ *self.msgs_system,
+ *self.msgs_conversation,
+ *self.msgs_tools,
+ ],
+ )
+
+ # Expected result: image blocks should be promoted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "content": "You're a helpful assistant.",
+ },
+ {
+ "role": "user",
+ "content": "# Conversation History\nThe content between"
+ " <history></history> tags contains your"
+ " conversation history\n<history>\nuser: What is"
+ " the capital of France?\n\nassistant: The capital"
+ " of France is Paris.\nuser: What is the capital"
+ " of Japan?\n</history>",
+ "images": [
+ "ZmFrZSBpbWFnZSBjb250ZW50",
+ ],
+ },
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": {
+ "country": "Japan",
+ },
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n- The returned"
+ " image can be found at: ./image.png",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "content": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':\n\n- The image from "
+ "'./image.png': \n</system-info>",
+ "images": [
+ "ZmFrZSBpbWFnZSBjb250ZW50",
+ ],
+ },
+ {
+ "role": "user",
+ "content": "<history>\nassistant: The"
+ " capital of Japan is Tokyo.\n</history>",
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
async def asyncTearDown(self) -> None:
"""Clean up the test environment."""
if os.path.exists(self.image_path):
diff --git a/tests/formatter_openai_test.py b/tests/formatter_openai_test.py
index ac779cc1b..733f39588 100644
--- a/tests/formatter_openai_test.py
+++ b/tests/formatter_openai_test.py
@@ -432,6 +432,165 @@ class TestOpenAIFormatter(IsolatedAsyncioTestCase):
self.ground_truth_chat[: -len(self.msgs_tools)],
)
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_formatter_with_extract_image_blocks(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the OpenAI chat formatter with
+ promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = OpenAIChatFormatter(promote_tool_result_images=True)
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [*self.msgs_system, *self.msgs_conversation, *self.msgs_tools],
+ )
+
+ # Expected result: image blocks should be extracted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "name": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "You're a helpful assistant.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What is the capital of France?",
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;"
+ "base64,ZmFrZSBpbWFnZSBjb250ZW50",
+ },
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "name": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "The capital of France is Paris.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What is the capital of Germany?",
+ },
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": "ZmFrZSBhdWRpbyBjb250ZW50",
+ "format": "wav",
+ },
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "name": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "The capital of Germany is Berlin.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "What is the capital of Japan?",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "name": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": '{"country": "Japan"}',
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n"
+ "- The returned image can be found at: "
+ f"{self.image_path}\n"
+ "- The returned audio can be found at: "
+ f"{self.mock_audio_path}",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "type": "text",
+ "text": f"\n- The image from '{self.image_path}': ",
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;"
+ "base64,ZmFrZSBpbWFnZSBjb250ZW50",
+ },
+ },
+ {
+ "type": "text",
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "name": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "The capital of Japan is Tokyo.",
+ },
+ ],
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
@patch("agentscope.formatter._formatter_base._save_base64_data")
async def test_multiagent_formatter(
self,
@@ -478,6 +637,139 @@ class TestOpenAIFormatter(IsolatedAsyncioTestCase):
self.ground_truth_multiagent_without_conversation[1:],
)
+ @patch("agentscope.formatter._formatter_base._save_base64_data")
+ async def test_multiagent_formatter_with_promote_tool_result_images(
+ self,
+ mock_save_base64_data: MagicMock,
+ ) -> None:
+ """Test the OpenAI multi-agent formatter with
+ promote_tool_result_images=True."""
+ mock_save_base64_data.return_value = self.mock_audio_path
+
+ formatter = OpenAIMultiAgentFormatter(
+ promote_tool_result_images=True,
+ )
+
+ # Test with tool result containing image blocks
+ res = await formatter.format(
+ [
+ *self.msgs_system,
+ *self.msgs_conversation,
+ *self.msgs_tools,
+ ],
+ )
+
+ # Expected result: image blocks should be promoted and inserted
+ # as a separate user message after the tool result message
+ expected_result = [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "You're a helpful assistant.",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "# Conversation History\n"
+ "The content between <history></history> tags contains"
+ " your conversation history\n"
+ "<history>\n"
+ "user: What is the capital of France?\n"
+ "assistant: The capital of France is Paris.\n"
+ "user: What is the capital of Germany?\n"
+ "assistant: The capital of Germany is Berlin.\n"
+ "user: What is the capital of Japan?\n"
+ "</history>",
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;base64,"
+ "ZmFrZSBpbWFnZSBjb250ZW50",
+ },
+ },
+ {
+ "type": "input_audio",
+ "input_audio": {
+ "data": "ZmFrZSBhdWRpbyBjb250ZW50",
+ "format": "wav",
+ },
+ },
+ ],
+ },
+ {
+ "role": "assistant",
+ "name": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "1",
+ "type": "function",
+ "function": {
+ "name": "get_capital",
+ "arguments": '{"country": "Japan"}',
+ },
+ },
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "1",
+ "content": "- The capital of Japan is Tokyo.\n"
+ "- The returned image can be found at: "
+ f"{self.image_path}\n"
+ "- The returned audio can be found at: "
+ f"{self.mock_audio_path}",
+ "name": "get_capital",
+ },
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<system-info>The following are "
+ "the image contents from the tool "
+ "result of 'get_capital':",
+ },
+ {
+ "type": "text",
+ "text": f"\n- The image from '{self.image_path}': ",
+ },
+ {
+ "type": "image_url",
+ "image_url": {
+ "url": "data:image/png;"
+ "base64,ZmFrZSBpbWFnZSBjb250ZW50",
+ },
+ },
+ {
+ "type": "text",
+ "text": "</system-info>",
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<history>\n"
+ "assistant: The capital of Japan is Tokyo.\n"
+ "</history>",
+ },
+ ],
+ },
+ ]
+
+ self.assertListEqual(expected_result, res)
+
async def asyncTearDown(self) -> None:
"""Clean up the test environment."""
if os.path.exists(self.image_path):