Skip to content

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

fix(tool): report deferred PDF read failures (#3057)

Sicheng Han58da57a56583
diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.py
index b36b8a8a4..bc6463d53 100644
--- a/src/agentscope/tool/_builtin/_read.py
+++ b/src/agentscope/tool/_builtin/_read.py
@@ -313,7 +313,15 @@ Usage:
ext = os.path.splitext(self._backend.basename(file_path))[1].lower()
if ext == ".pdf":
- return await self._read_pdf(file_path, pages)
+ # PDF decoding and page serialization can fail after opening.
+ try:
+ return await self._read_pdf(file_path, pages)
+ except Exception as e:
+ return ToolChunk(
+ content=[TextBlock(text=f"Error reading PDF: {str(e)}")],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
if ext in _IMAGE_EXTENSIONS:
return await self._read_image_file(file_path, ext)
diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.py
index b24e63432..bb898e655 100644
--- a/tests/builtin_read_test.py
+++ b/tests/builtin_read_test.py
@@ -6,6 +6,7 @@ import os
import tempfile
import uuid
from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
from utils import AnyString
from agentscope.tool import ToolChunk, Read
@@ -442,6 +443,55 @@ class ReadToolTest(IsolatedAsyncioTestCase):
},
)
+ async def test_read_pdf_deferred_errors(self) -> None:
+ """Late extraction and PDF-writing errors become final error chunks."""
+ from pypdf import PdfWriter
+
+ writer = PdfWriter()
+ writer.add_blank_page(width=72, height=72)
+ writer.add_blank_page(width=72, height=72)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as fp:
+ writer.write(fp)
+ self.addCleanup(os.unlink, fp.name)
+
+ # Malformed streams may be tolerated by different pypdf versions.
+ # Inject failures at the actual deferred operations instead.
+ for method, message, native_pdf in (
+ ("PageObject.extract_text", "cannot extract text", False),
+ ("PdfWriter.add_page", "cannot copy page", True),
+ ("PdfWriter.write", "cannot write PDF", True),
+ ):
+ with self.subTest(method=method):
+ tool = Read(
+ model_input_types=["application/pdf"]
+ if native_pdf
+ else [],
+ )
+ with patch(
+ f"pypdf.{method}",
+ side_effect=ValueError(message),
+ ) as failure:
+ chunk = await tool(file_path=fp.name, pages="1")
+ failure.assert_called_once()
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": f"Error reading PDF: {message}",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "error",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
async def test_read_pdf_with_pages_param(self) -> None:
"""Test reading a page range and a single page from a PDF."""
from pypdf import PdfWriter