Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(formatter): use native multimodal tool outputs (#2389)
Xinmin Zeng142c3411b6e7
diff --git a/src/agentscope/formatter/_formatter_base.py b/src/agentscope/formatter/_formatter_base.pyindex 102451c02..50fff0969 100644--- a/src/agentscope/formatter/_formatter_base.py+++ b/src/agentscope/formatter/_formatter_base.py@@ -15,7 +15,6 @@ from ..message import (DataBlock,TextBlock,URLSource,- Base64Source,)@@ -67,6 +66,43 @@ class FormatterBase(BaseModel):f"Expected Msg object, got {type(msg)} instead.",)+ @staticmethod+ def _convert_unsupported_data_block_to_string(block: DataBlock) -> str:+ """Convert an unsupported data block into its textual fallback.++ URL sources remain accessible through their URL. Base64 sources are+ persisted to a temporary file so the model can still reference the+ result when the target API cannot carry that media type directly.++ Args:+ block (`DataBlock`):+ The unsupported data block to convert.++ Returns:+ `str`:+ The textual fallback for the data block.+ """+ main_type = block.source.media_type.split("/")[0]++ if isinstance(block.source, URLSource):+ return (+ f"<system-reminder>A(n) {main_type} file is returned "+ f"and can be accessed at the URL: {block.source.url}."+ f"</system-reminder>"+ )++ extension = mimetypes.guess_extension(block.source.media_type)+ with tempfile.NamedTemporaryFile(+ suffix=extension,+ delete=False,+ ) as temp_file:+ decoded_data = base64.b64decode(block.source.data)+ temp_file.write(decoded_data)+ return (+ f"<system-reminder>A(n) {main_type} file is returned and "+ f"saved locally at: {temp_file.name}.</system-reminder>"+ )+def convert_tool_result_to_string(self,output: str | List[TextBlock | DataBlock],@@ -127,35 +163,12 @@ class FormatterBase(BaseModel):],)- # For unsupported media types, if it's a URL, include it in- # the textual output; if it's base64 data, save it locally- # and include the file path in the textual output.- # Note if you don't want to save the local file, you should- # transform the base64 data in the tool execution hook- # rather than changing the formatter.- elif isinstance(block.source, URLSource):+ # For unsupported media types, retain the existing textual+ # fallback rather than silently dropping the result.+ else:textual_output.append(- f"<system-reminder>A(n) {main_type} file is returned "- f"and can be accessed at the URL: {block.source.url}."- f"</system-reminder>",- )-- elif isinstance(block.source, Base64Source):- # Have to save the base64 data locally- extension = mimetypes.guess_extension(- block.source.media_type,+ self._convert_unsupported_data_block_to_string(block),)- with tempfile.NamedTemporaryFile(- suffix=extension,- delete=False,- ) as temp_file:- decoded_data = base64.b64decode(block.source.data)- temp_file.write(decoded_data)- textual_output.append(- f"<system-reminder>A(n) {main_type} file is "- f"returned and saved locally at: {temp_file.name}."- f"</system-reminder>",- )# Add system reminder tags if there is multimodal data to be promotedif multimodal_data:diff --git a/src/agentscope/formatter/_openai_response_formatter.py b/src/agentscope/formatter/_openai_response_formatter.pyindex be59159a4..e526832e9 100644--- a/src/agentscope/formatter/_openai_response_formatter.py+++ b/src/agentscope/formatter/_openai_response_formatter.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""Formatters for the OpenAI Responses API."""from abc import ABC+from fnmatch import fnmatchfrom typing import Anyfrom pydantic import Field@@ -88,6 +89,74 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):return base_result+ def _format_tool_result_output(+ self,+ output: str | list[TextBlock | DataBlock],+ ) -> str | list[dict[str, Any]]:+ """Format a tool result using the native Responses API schema.++ Text-only results remain strings. Once a supported image or file is+ present, every block is serialized into the ordered content array.+ Unsupported media remains visible through the formatter's textual+ fallback at its original position.++ Args:+ output (`str | list[TextBlock | DataBlock]`):+ The tool result to format.++ Returns:+ `str | list[dict[str, Any]]`:+ A string for text-only results, otherwise the ordered native+ content array.+ """+ if isinstance(output, str):+ return output++ output_parts: list[dict[str, Any]] = []+ has_native_media = False++ for block in output:+ if isinstance(block, TextBlock):+ output_parts.append(+ {"type": "input_text", "text": block.text},+ )+ continue++ media_type = block.source.media_type+ supports_native_output = (+ media_type.split("/", 1)[0] == "image"+ or media_type == "application/pdf"+ ) and any(+ fnmatch(media_type, pattern)+ for pattern in self.supported_input_media_types+ )++ if supports_native_output:+ formatted = self._format_response_data_block(block)+ if formatted is None:+ raise RuntimeError(+ "Supported OpenAI Responses tool-result media could "+ f"not be formatted: {media_type}.",+ )+ output_parts.append(formatted)+ has_native_media = True+ else:+ output_parts.append(+ {+ "type": "input_text",+ "text": (+ self._convert_unsupported_data_block_to_string(+ block,+ )+ ),+ },+ )++ if has_native_media:+ return output_parts++ return "\n".join(part["text"] for part in output_parts)+class OpenAIResponseFormatter(_OpenAIResponseFormatterBase):"""Formatter for the OpenAI Responses API in chat (single-agent) mode.@@ -270,43 +339,16 @@ class OpenAIResponseFormatter(_OpenAIResponseFormatterBase):)content_parts = []- (- textual_output,- multimodal_data,- ) = self.convert_tool_result_to_string(block.output)-items.append({"type": "function_call_output","call_id": block.id,- "output": textual_output,+ "output": self._format_tool_result_output(+ block.output,+ ),},)- if multimodal_data:- promo_content = []- for item in multimodal_data:- if isinstance(item, TextBlock):- promo_content.append(- {- "type": "input_text",- "text": item.text,- },- )- elif isinstance(item, DataBlock):- fmt_item = self._format_response_data_block(- item,- )- if fmt_item is not None:- promo_content.append(fmt_item)- if promo_content:- items.append(- {- "role": "user",- "content": promo_content,- },- )-else:logger.warning("Unsupported block type %s in the message, skipped.",diff --git a/tests/formatter_openai_response_test.py b/tests/formatter_openai_response_test.pyindex 3bb11c2d3..557be8c78 100644--- a/tests/formatter_openai_response_test.py+++ b/tests/formatter_openai_response_test.py@@ -11,7 +11,6 @@ Key differences from OpenAI Chat formatter:- ThinkingBlock: only echoed when it has a "reasoning_item_id" attribute."""from unittest import IsolatedAsyncioTestCase-from unittest.mock import patchfrom agentscope.formatter import (OpenAIResponseFormatter,@@ -33,9 +32,6 @@ from agentscope.message import ()-_FIXED_ID = "TESTID1234567"--class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):"""Comprehensive tests for OpenAI Responses API formatters."""@@ -598,103 +594,6 @@ class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):res,)- @patch(- "agentscope.formatter._formatter_base.shortuuid.uuid",- return_value=_FIXED_ID,- )- async def test_chat_formatter_url_image_in_tool_result(- self,- _mock_uuid: object,- ) -> None:- """URL images in tool results are promoted to a follow-up user- message."""- fmt = OpenAIResponseFormatter()- msgs = [- AssistantMsg(- name="assistant",- content=[- ToolCallBlock(- id="call_img",- name="get_map",- input='{"city": "Tokyo"}',- ),- ToolResultBlock(- id="call_img",- name="get_map",- output=[- TextBlock(text="Here is the map."),- DataBlock(- source=URLSource(- url=self.image_url,- media_type="image/png",- ),- ),- ],- state=ToolResultState.SUCCESS,- ),- TextBlock(text="Here is the map of Tokyo."),- ],- ),- ]- res = await fmt.format(msgs)-- expected_tool_content = (- "Here is the map.\n"- f"<system-reminder>A(n) image file is returned "- f"and will be presented to you with the identifier "- f"[{_FIXED_ID}].</system-reminder>"- )- self.assertListEqual(- [- {- "type": "function_call",- "call_id": "call_img",- "name": "get_map",- "arguments": '{"city": "Tokyo"}',- },- {- "type": "function_call_output",- "call_id": "call_img",- "output": expected_tool_content,- },- {- "role": "user",- "content": [- {- "type": "input_text",- "text": (- "<system-reminder>The multimodal data "- "and their identifiers are listed as "- "follows:"- ),- },- {- "type": "input_text",- "text": f"- {_FIXED_ID} (image file): ",- },- {- "type": "input_image",- "image_url": self.image_url,- },- {- "type": "input_text",- "text": "</system-reminder>",- },- ],- },- {- "role": "assistant",- "content": [- {- "type": "output_text",- "text": "Here is the map of Tokyo.",- },- ],- },- ],- res,- )-# -------------------------------------------------------------------# OpenAIResponseMultiAgentFormatter tests# -------------------------------------------------------------------@@ -775,7 +674,15 @@ class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):ToolResultBlock(id="call_1",name="func_1",- output=[TextBlock(text="result_1")],+ output=[+ TextBlock(text="result_1"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],state=ToolResultState.SUCCESS,),ToolResultBlock(@@ -837,7 +744,13 @@ class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):{"type": "function_call_output","call_id": "call_1",- "output": "result_1",+ "output": [+ {"type": "input_text", "text": "result_1"},+ {+ "type": "input_image",+ "image_url": self.image_data_uri,+ },+ ],},{"type": "function_call_output",diff --git a/tests/formatter_openai_response_tool_result_test.py b/tests/formatter_openai_response_tool_result_test.pynew file mode 100644index 000000000..7d10887ec--- /dev/null+++ b/tests/formatter_openai_response_tool_result_test.py@@ -0,0 +1,211 @@+# -*- coding: utf-8 -*-+"""Native tool-result tests for the OpenAI Responses formatter."""+import re+import tempfile+from functools import partial+from pathlib import Path+from unittest import IsolatedAsyncioTestCase+from unittest.mock import patch++from agentscope.formatter import OpenAIResponseFormatter+from agentscope.message import (+ AssistantMsg,+ Base64Source,+ DataBlock,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+ URLSource,+)+++class TestOpenAIResponseToolResultFormatter(IsolatedAsyncioTestCase):+ """Tests for native multimodal function-call output."""++ def setUp(self) -> None:+ """Set up image fixtures."""+ image_source = URLSource(+ url="https://example.com/image.png",+ media_type="image/png",+ )+ self.image_url = str(image_source.url)+ self.image_b64 = "ZmFrZSBpbWFnZSBkYXRh"+ self.image_data_uri = f"data:image/png;base64,{self.image_b64}"++ async def test_native_multimodal_tool_result(self) -> None:+ """Multimodal tool results use the native ordered output array."""+ fmt = OpenAIResponseFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call_img",+ name="get_map",+ input='{"city": "Tokyo"}',+ ),+ ToolResultBlock(+ id="call_img",+ name="get_map",+ output=[+ TextBlock(text="Here is the map."),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ TextBlock(text="The remote copy follows."),+ DataBlock(+ source=URLSource(+ url=self.image_url,+ media_type="image/png",+ ),+ ),+ DataBlock(+ source=URLSource(+ url="https://example.com/audio.mp3",+ media_type="audio/mpeg",+ ),+ ),+ DataBlock(+ name="report.pdf",+ source=Base64Source(+ data="JVBERi0xLjQgZmFrZQ==",+ media_type="application/pdf",+ ),+ ),+ TextBlock(text="End of result."),+ ],+ state=ToolResultState.SUCCESS,+ ),+ TextBlock(text="Here is the map of Tokyo."),+ ],+ ),+ ]++ res = await fmt.format(msgs)++ self.assertListEqual(+ [+ {+ "type": "function_call",+ "call_id": "call_img",+ "name": "get_map",+ "arguments": '{"city": "Tokyo"}',+ },+ {+ "type": "function_call_output",+ "call_id": "call_img",+ "output": [+ {"type": "input_text", "text": "Here is the map."},+ {+ "type": "input_image",+ "image_url": self.image_data_uri,+ },+ {+ "type": "input_text",+ "text": "The remote copy follows.",+ },+ {+ "type": "input_image",+ "image_url": self.image_url,+ },+ {+ "type": "input_text",+ "text": (+ "<system-reminder>A(n) audio file is "+ "returned and can be accessed at the URL: "+ "https://example.com/audio.mp3."+ "</system-reminder>"+ ),+ },+ {+ "type": "input_file",+ "filename": "report.pdf",+ "file_data": (+ "data:application/pdf;base64,"+ "JVBERi0xLjQgZmFrZQ=="+ ),+ },+ {"type": "input_text", "text": "End of result."},+ ],+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "output_text",+ "text": "Here is the map of Tokyo.",+ },+ ],+ },+ ],+ res,+ )++ async def test_unsupported_base64_audio_fallback(self) -> None:+ """Unsupported Base64 audio is persisted and returned as text."""+ fmt = OpenAIResponseFormatter()+ named_temp_file = tempfile.NamedTemporaryFile++ with tempfile.TemporaryDirectory() as temp_dir:+ with patch(+ "agentscope.formatter._formatter_base.tempfile."+ "NamedTemporaryFile",+ side_effect=partial(named_temp_file, dir=temp_dir),+ ):+ res = await fmt.format(+ [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call_audio",+ name="get_audio",+ input="{}",+ ),+ ToolResultBlock(+ id="call_audio",+ name="get_audio",+ output=[+ TextBlock(text="audio-before"),+ DataBlock(+ source=Base64Source(+ data="SUQzBAAA",+ media_type="audio/mpeg",+ ),+ ),+ TextBlock(text="audio-after"),+ ],+ state=ToolResultState.SUCCESS,+ ),+ ],+ ),+ ],+ )++ output = res[1]["output"]+ self.assertIsInstance(output, str)+ path_match = re.search(+ r"saved locally at: (?P<path>.+)\.</system-reminder>",+ output,+ )+ self.assertIsNotNone(path_match)+ audio_path = Path(path_match.group("path"))+ with audio_path.open("rb") as audio_file:+ self.assertEqual(audio_file.read(), b"ID3\x04\x00\x00")+ self.assertEqual(+ output,+ "\n".join(+ [+ "audio-before",+ "<system-reminder>A(n) audio file is returned and "+ f"saved locally at: {audio_path}.</system-reminder>",+ "audio-after",+ ],+ ),+ )++ self.assertFalse(audio_path.exists())diff --git a/tests/model_openai_response_test.py b/tests/model_openai_response_test.pyindex 50439fa07..42e6fb7d0 100644--- a/tests/model_openai_response_test.py+++ b/tests/model_openai_response_test.py@@ -12,7 +12,16 @@ from unittest.mock import AsyncMock, MagicMockfrom utils import AnyString-from agentscope.message import TextBlock, ToolCallBlock, ThinkingBlock+from agentscope.message import (+ AssistantMsg,+ Base64Source,+ DataBlock,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+ ThinkingBlock,+)from agentscope.model import OpenAIResponseModelfrom agentscope.credential import OpenAICredentialfrom agentscope.tool import ToolChoice@@ -194,6 +203,66 @@ class TestOpenAIResponseNonStream(IsolatedAsyncioTestCase):),)+ async def test_native_multimodal_tool_result_request(self) -> None:+ """The model sends native multimodal function-call output."""+ mock_create = AsyncMock(+ return_value=_mock_completion(text="verified"),+ )+ self.mock_client.responses.create = mock_create+ messages = [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call-image",+ name="inspect_image",+ input="{}",+ ),+ ToolResultBlock(+ id="call-image",+ name="inspect_image",+ output=[+ TextBlock(text="marker-before"),+ DataBlock(+ source=Base64Source(+ data="aW1hZ2U=",+ media_type="image/png",+ ),+ ),+ TextBlock(text="marker-after"),+ ],+ state=ToolResultState.SUCCESS,+ ),+ ],+ ),+ ]++ await self.model(messages)++ self.assertListEqual(+ mock_create.await_args.kwargs["input"],+ [+ {+ "type": "function_call",+ "call_id": "call-image",+ "name": "inspect_image",+ "arguments": "{}",+ },+ {+ "type": "function_call_output",+ "call_id": "call-image",+ "output": [+ {"type": "input_text", "text": "marker-before"},+ {+ "type": "input_image",+ "image_url": "data:image/png;base64,aW1hZ2U=",+ },+ {"type": "input_text", "text": "marker-after"},+ ],+ },+ ],+ )+async def test_reasoning_response(self,) -> None: