Skip to content

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

fix(tool): merge base64 tool response chunks by bytes (#1901)

lewis11db23a53307
diff --git a/src/agentscope/tool/_response.py b/src/agentscope/tool/_response.py
index 946466999..57d834965 100644
--- a/src/agentscope/tool/_response.py
+++ b/src/agentscope/tool/_response.py
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
"""The tool response class."""
+import base64
+import binascii
from typing import List, Literal, Self
from pydantic import BaseModel, Field
@@ -8,6 +10,21 @@ from .._utils._common import _generate_id
from ..message import DataBlock, TextBlock, Base64Source, ToolResultState
+def _merge_base64_chunks(existing: str, incoming: str) -> str:
+ """Merge independently encoded base64 chunks without corrupting padding."""
+ try:
+ merged = base64.b64decode(
+ existing,
+ validate=True,
+ ) + base64.b64decode(incoming, validate=True)
+ except (binascii.Error, ValueError):
+ # Keep compatibility with callers/tests that used placeholder strings
+ # instead of valid base64 payloads.
+ return existing + incoming
+
+ return base64.b64encode(merged).decode("ascii")
+
+
class ToolChunk(BaseModel):
"""The tool result chunk from a tool execution."""
@@ -80,8 +97,11 @@ class ToolResponse(BaseModel):
target_block.source,
Base64Source,
) and isinstance(chunk_block.source, Base64Source):
- # Accumulate the base64 data
- target_block.source.data += chunk_block.source.data
+ # Accumulate independently encoded base64 chunks.
+ target_block.source.data = _merge_base64_chunks(
+ target_block.source.data,
+ chunk_block.source.data,
+ )
# Update the newest media type and name if provided
target_block.name = (
chunk_block.name or target_block.name
diff --git a/tests/toolkit_test.py b/tests/toolkit_test.py
index 45388b36e..3be91d10b 100644
--- a/tests/toolkit_test.py
+++ b/tests/toolkit_test.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# pylint: disable=unused-argument
"""Toolkit test case."""
+import base64
import json
from typing import Any, AsyncGenerator, Generator
from unittest import TestCase
@@ -419,6 +420,47 @@ class ToolkitTest(IsolatedAsyncioTestCase):
},
)
+ async def test_tool_response_merges_base64_chunks_by_bytes(self) -> None:
+ """Base64 chunks with padding should merge as bytes, not strings."""
+ response = ToolResponse()
+ first = base64.b64encode(b"hello").decode("ascii")
+ second = base64.b64encode(b"world").decode("ascii")
+
+ response.append_chunk(
+ ToolChunk(
+ content=[
+ DataBlock(
+ id="image",
+ source=Base64Source(
+ data=first,
+ media_type="image/png",
+ ),
+ ),
+ ],
+ ),
+ )
+ response.append_chunk(
+ ToolChunk(
+ content=[
+ DataBlock(
+ id="image",
+ source=Base64Source(
+ data=second,
+ media_type="image/png",
+ ),
+ ),
+ ],
+ ),
+ )
+
+ self.assertEqual(len(response.content), 1)
+ merged = response.content[0]
+ self.assertIsInstance(merged, DataBlock)
+ self.assertEqual(
+ base64.b64decode(merged.source.data),
+ b"helloworld",
+ )
+
class RegisterFunctionTest(IsolatedAsyncioTestCase):
"""Test registering different functions in the toolkit."""