Skip to content

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

fix(formatter): promote tool-result media in the xai chat formatter (#2928)

ANIRUDDHA ADAK2b1f0f7d4509
diff --git a/src/agentscope/formatter/_xai_formatter.py b/src/agentscope/formatter/_xai_formatter.py
index 1f2bb8821..38ee4996e 100644
--- a/src/agentscope/formatter/_xai_formatter.py
+++ b/src/agentscope/formatter/_xai_formatter.py
@@ -200,8 +200,16 @@ class XAIChatFormatter(FormatterBase):
elif msg.role == "assistant":
pending_text: list[TextBlock] = []
pending_tool_calls: list[ToolCallBlock] = []
+ pending_media: list[Any] = []
for block in blocks:
+ if pending_media and not isinstance(
+ block,
+ ToolResultBlock,
+ ):
+ xai_messages.extend(pending_media)
+ pending_media = []
+
if isinstance(block, ToolResultBlock):
# Convert each ToolResultBlock to a tool_result
# message.
@@ -232,16 +240,34 @@ class XAIChatFormatter(FormatterBase):
xai_messages.append(assistant(text))
pending_text = []
- output_text = self._extract_result_text(
+ (
+ textual_output,
+ multimodal_data,
+ ) = self.convert_tool_result_to_string(
block.output,
)
xai_messages.append(
tool_result(
- output_text,
+ textual_output,
tool_call_id=block.id,
),
)
+ # Promote media that came back inside the tool
+ # result into a following user message, which is what
+ # the other formatters do via the same shared helper.
+ # ``xai_sdk`` re-hydrates binary tool results and
+ # ``input_types`` already advertises images, so the
+ # textual hint alone would lose the picture.
+ if multimodal_data:
+ promo_args = _xai_user_args_from_blocks(
+ multimodal_data,
+ image,
+ self.supported_input_media_types,
+ )
+ if promo_args:
+ pending_media.append(user(*promo_args))
+
elif isinstance(block, ToolCallBlock):
pending_tool_calls.append(block)
@@ -292,6 +318,8 @@ class XAIChatFormatter(FormatterBase):
if hint_args:
xai_messages.append(user(*hint_args))
+ xai_messages.extend(pending_media)
+
if pending_tool_calls:
# Assistant turn that triggered tool calls (history).
msg_proto = chat_pb2.Message()
@@ -325,39 +353,6 @@ class XAIChatFormatter(FormatterBase):
return xai_messages
- def _extract_result_text(self, output: Any) -> str:
- """Extract a plain-text string from a ``ToolResultBlock`` output.
-
- Args:
- output (`Any`):
- The raw output of a ``ToolResultBlock``, which may be a
- string, a list of blocks, or another type.
-
- Returns:
- `str`:
- A plain-text representation of the output.
- """
- if output is None:
- return ""
- if isinstance(output, str):
- return output
- if isinstance(output, list):
- parts = []
- for item in output:
- if isinstance(item, TextBlock):
- parts.append(item.text)
- elif isinstance(item, str):
- parts.append(item)
- elif isinstance(item, DataBlock):
- # Tool results are text-only here; media becomes a hint.
- parts.append(
- self._convert_unsupported_data_block_to_string(item),
- )
- else:
- parts.append(str(item))
- return "\n".join(parts)
- return str(output)
-
class XAIMultiAgentFormatter(FormatterBase):
"""Formatter for the xAI chat model in multi-agent conversations.
diff --git a/tests/formatter_xai_test.py b/tests/formatter_xai_test.py
index 30c60fbc1..f3d2166a3 100644
--- a/tests/formatter_xai_test.py
+++ b/tests/formatter_xai_test.py
@@ -7,8 +7,6 @@ dicts), a lightweight xai_sdk stub is built at module load so that tests run
without the real package. The stub objects support __eq__ and __repr__ so
full assertListEqual comparisons work.
"""
-import os
-import re
import sys
from typing import Any
from types import ModuleType
@@ -317,8 +315,14 @@ class TestXAIFormatter( # pylint: disable=too-many-public-methods
)
async def test_chat_formatter_tool_result_with_url_media(self) -> None:
- """URL media in a tool result becomes a placeholder with its URL."""
+ """URL media in a tool result is promoted as a real image part."""
fmt = XAIChatFormatter()
+ picture = DataBlock(
+ source=URLSource(
+ url="https://example.com/a.png",
+ media_type="image/png",
+ ),
+ )
res = await fmt.format(
[
AssistantMsg(
@@ -327,15 +331,7 @@ class TestXAIFormatter( # pylint: disable=too-many-public-methods
ToolResultBlock(
id="call_1",
name="screenshot",
- output=[
- TextBlock(text="done"),
- DataBlock(
- source=URLSource(
- url="https://example.com/a.png",
- media_type="image/png",
- ),
- ),
- ],
+ output=[TextBlock(text="done"), picture],
state=ToolResultState.SUCCESS,
),
],
@@ -347,18 +343,31 @@ class TestXAIFormatter( # pylint: disable=too-many-public-methods
[
tool_result(
"done\n<system-reminder>A(n) image file is returned "
- "and can be accessed at the URL: "
- "https://example.com/a.png.</system-reminder>",
+ "and will be presented to you with the identifier "
+ f"[{picture.id}].</system-reminder>",
tool_call_id="call_1",
),
+ user(
+ "<system-reminder>The multimodal data and their "
+ "identifiers are listed as follows:",
+ f"- {picture.id} (image file): ",
+ image("https://example.com/a.png"),
+ "</system-reminder>",
+ ),
],
)
async def test_chat_formatter_tool_result_with_base64_media(
self,
) -> None:
- """Base64 media in a tool result is saved to a file, not dumped."""
+ """Base64 media in a tool result is promoted as a data URI."""
fmt = XAIChatFormatter()
+ picture = DataBlock(
+ source=Base64Source(
+ data="iVBORw0KGgo=",
+ media_type="image/png",
+ ),
+ )
res = await fmt.format(
[
AssistantMsg(
@@ -367,11 +376,50 @@ class TestXAIFormatter( # pylint: disable=too-many-public-methods
ToolResultBlock(
id="call_1",
name="screenshot",
+ output=[picture],
+ state=ToolResultState.SUCCESS,
+ ),
+ ],
+ ),
+ ],
+ )
+ self.assertListEqual(
+ res,
+ [
+ tool_result(
+ "<system-reminder>A(n) image file is returned and "
+ "will be presented to you with the identifier "
+ f"[{picture.id}].</system-reminder>",
+ tool_call_id="call_1",
+ ),
+ user(
+ "<system-reminder>The multimodal data and their "
+ "identifiers are listed as follows:",
+ f"- {picture.id} (image file): ",
+ image("data:image/png;base64,iVBORw0KGgo="),
+ "</system-reminder>",
+ ),
+ ],
+ )
+
+ async def test_chat_formatter_tool_result_unsupported_media(
+ self,
+ ) -> None:
+ """Media the formatter cannot promote keeps the textual fallback."""
+ fmt = XAIChatFormatter()
+ res = await fmt.format(
+ [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ToolResultBlock(
+ id="call_1",
+ name="recording",
output=[
DataBlock(
- source=Base64Source(
- data="iVBORw0KGgo=",
- media_type="image/png",
+ source=URLSource(
+ url="https://example.com/a.wav",
+ media_type="audio/wav",
),
),
],
@@ -381,22 +429,123 @@ class TestXAIFormatter( # pylint: disable=too-many-public-methods
),
],
)
- path = re.search(
- r"saved locally at: (.+)\.</system-reminder>",
- res[0].args[0],
- ).group(1)
- os.unlink(path)
self.assertListEqual(
res,
[
tool_result(
- "<system-reminder>A(n) image file is returned and "
- f"saved locally at: {path}.</system-reminder>",
+ "<system-reminder>A(n) audio file is returned and "
+ "can be accessed at the URL: "
+ "https://example.com/a.wav.</system-reminder>",
tool_call_id="call_1",
),
],
)
+ async def test_chat_formatter_parallel_tool_media_after_tool_msgs(
+ self,
+ ) -> None:
+ """Promoted media does not split parallel tool-result messages."""
+ fmt = XAIChatFormatter()
+ picture = DataBlock(
+ id="image_1",
+ source=URLSource(
+ url="https://example.com/shot.png",
+ media_type="image/png",
+ ),
+ )
+ res = await fmt.format(
+ [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ToolCallBlock(
+ id="call_shot",
+ name="screenshot",
+ input="{}",
+ ),
+ ToolCallBlock(
+ id="call_title",
+ name="get_title",
+ input="{}",
+ ),
+ ToolResultBlock(
+ id="call_shot",
+ name="screenshot",
+ output=[
+ TextBlock(text="Screenshot taken."),
+ picture,
+ ],
+ state=ToolResultState.SUCCESS,
+ ),
+ ToolResultBlock(
+ id="call_title",
+ name="get_title",
+ output=[TextBlock(text="Example Domain")],
+ state=ToolResultState.SUCCESS,
+ ),
+ ],
+ ),
+ ],
+ )
+
+ normalized_res = [
+ (
+ res[0].role,
+ [part.text for part in res[0].content],
+ [
+ (
+ tool_call.id,
+ tool_call.type,
+ tool_call.function.name,
+ tool_call.function.arguments,
+ )
+ for tool_call in res[0].tool_calls
+ ],
+ ),
+ *res[1:],
+ ]
+ self.assertListEqual(
+ normalized_res,
+ [
+ (
+ 2,
+ [],
+ [
+ (
+ "call_shot",
+ 1,
+ "screenshot",
+ "{}",
+ ),
+ (
+ "call_title",
+ 1,
+ "get_title",
+ "{}",
+ ),
+ ],
+ ),
+ tool_result(
+ "Screenshot taken.\n"
+ "<system-reminder>A(n) image file is returned and "
+ "will be presented to you with the identifier "
+ "[image_1].</system-reminder>",
+ tool_call_id="call_shot",
+ ),
+ tool_result(
+ "Example Domain",
+ tool_call_id="call_title",
+ ),
+ user(
+ "<system-reminder>The multimodal data and their "
+ "identifiers are listed as follows:",
+ "- image_1 (image file): ",
+ image("https://example.com/shot.png"),
+ "</system-reminder>",
+ ),
+ ],
+ )
+
async def test_chat_formatter_thinking_dropped(self) -> None:
"""ThinkingBlock is silently ignored in user/assistant xAI
messages."""