Skip to content

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

fix(formatter): keep images accumulated before a tool call (#2351)

Chengxiaodda3973aef0a
diff --git a/src/agentscope/formatter/_ollama_formatter.py b/src/agentscope/formatter/_ollama_formatter.py
index afee35723..5a563aa37 100644
--- a/src/agentscope/formatter/_ollama_formatter.py
+++ b/src/agentscope/formatter/_ollama_formatter.py
@@ -187,28 +187,12 @@ class OllamaChatFormatter(_OllamaFormatterBase):
elif isinstance(block, ToolCallBlock):
messages.append(
- {
- "role": msg.role,
- "content": "\n".join(content_parts)
- if content_parts
- else "",
- "tool_calls": [
- {
- "function": {
- "name": block.name,
- # Ollama SDK expects a dict, not a
- # JSON string. Use the repair helper
- # so a truncated input (from
- # interrupted streaming or context
- # compression) degrades to {} instead
- # of raising JSONDecodeError.
- "arguments": _json_loads_with_repair(
- block.input or "{}",
- ),
- },
- },
- ],
- },
+ self._format_tool_call_message(
+ msg.role,
+ content_parts,
+ images,
+ block,
+ ),
)
content_parts = []
images = []
@@ -291,6 +275,59 @@ class OllamaChatFormatter(_OllamaFormatterBase):
return messages
+ def _format_tool_call_message(
+ self,
+ role: str,
+ content_parts: list[str],
+ images: list[str],
+ block: ToolCallBlock,
+ ) -> dict[str, Any]:
+ """Format a tool call block as one assistant message, keeping
+ pending text and images on the same message.
+
+ Ollama merges consecutive same-role messages server-side by
+ appending only content to the first one, so a separate images or
+ tool_calls message would be discarded. Images therefore stay on
+ the tool call message itself.
+
+ Args:
+ role (`str`):
+ The role of the message.
+ content_parts (`list[str]`):
+ Pending text blocks accumulated for this message.
+ images (`list[str]`):
+ Pending formatted images accumulated for this message.
+ block (`ToolCallBlock`):
+ The tool call block to format.
+
+ Returns:
+ `dict[str, Any]`:
+ A single assistant message carrying content, images and
+ the tool call.
+ """
+ tool_call_msg: dict[str, Any] = {
+ "role": role,
+ "content": "\n".join(content_parts) if content_parts else "",
+ "tool_calls": [
+ {
+ "function": {
+ "name": block.name,
+ # Ollama SDK expects a dict, not a JSON string. Use
+ # the repair helper so a truncated input (from
+ # interrupted streaming or context compression)
+ # degrades to {} instead of raising
+ # JSONDecodeError.
+ "arguments": _json_loads_with_repair(
+ block.input or "{}",
+ ),
+ },
+ },
+ ],
+ }
+ if images:
+ tool_call_msg["images"] = images
+ return tool_call_msg
+
class OllamaMultiAgentFormatter(_OllamaFormatterBase):
"""
diff --git a/tests/formatter_ollama_test.py b/tests/formatter_ollama_test.py
index c354c53ac..b97bd67db 100644
--- a/tests/formatter_ollama_test.py
+++ b/tests/formatter_ollama_test.py
@@ -225,6 +225,48 @@ class TestOllamaFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_image_before_tool_call_kept(self) -> None:
+ """Images accumulated before a tool call stay on the same message."""
+ fmt = OllamaChatFormatter()
+ msgs = [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ TextBlock(text="Let me look."),
+ DataBlock(
+ source=Base64Source(
+ data=self.image_b64,
+ media_type="image/png",
+ ),
+ ),
+ ToolCallBlock(
+ id="c1",
+ name="search",
+ input='{"q": "weather"}',
+ ),
+ ],
+ ),
+ ]
+ res = await fmt.format(msgs)
+ self.assertListEqual(
+ [
+ {
+ "role": "assistant",
+ "content": "Let me look.",
+ "images": [self.image_b64],
+ "tool_calls": [
+ {
+ "function": {
+ "name": "search",
+ "arguments": {"q": "weather"},
+ },
+ },
+ ],
+ },
+ ],
+ res,
+ )
+
async def test_chat_formatter_base64_image(self) -> None:
"""Base64 image is placed in the 'images' list as a raw base64
string."""