Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tool): merge base64 tool response chunks by bytes (#1901)
lewis11db23a53307
diff --git a/src/agentscope/tool/_response.py b/src/agentscope/tool/_response.pyindex 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 binasciifrom typing import List, Literal, Selffrom pydantic import BaseModel, Field@@ -8,6 +10,21 @@ from .._utils._common import _generate_idfrom ..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 providedtarget_block.name = (chunk_block.name or target_block.namediff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex 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 base64import jsonfrom typing import Any, AsyncGenerator, Generatorfrom 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."""