Skip to content

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

feat(tool): support DataBlock return in Read tool for binary and structured files (#2114)

qbc77524b8f6825
diff --git a/pyproject.toml b/pyproject.toml
index 8ca629b40..581cf397f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,6 +44,7 @@ dependencies = [
"tree_sitter",
"tree_sitter_bash",
"jsonschema",
+ "pypdf",
# The IANA timezone database, which is absent on Windows and slim images
"tzdata",
]
diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.py
index ad28e5ace..dd4d26fa9 100644
--- a/src/agentscope/formatter/_anthropic_formatter.py
+++ b/src/agentscope/formatter/_anthropic_formatter.py
@@ -303,70 +303,60 @@ class _AnthropicFormatterBase(FormatterBase, ABC):
)
return None
- # Anthropic only supports images
- if not media_type.startswith("image/"):
- logger.warning(
- "Anthropic only supports image data, got %s, skipped.",
- media_type,
- )
- return None
-
- return self._format_image_source(source)
+ # Anthropic supports images and PDF documents
+ if media_type.startswith("image/"):
+ return self._format_source(source, "image")
+ if media_type == "application/pdf":
+ return self._format_source(source, "document")
+
+ logger.warning(
+ "Anthropic only supports image and PDF data, got %s, skipped.",
+ media_type,
+ )
+ return None
@staticmethod
- def _format_image_source(
+ def _format_source(
source: URLSource | Base64Source,
+ block_type: str,
) -> dict[str, Any]:
- """Format an image source into Anthropic API format.
+ """Format an image or document source into an Anthropic base64
+ content block.
Args:
source (`URLSource | Base64Source`):
- The image source to format.
+ The source to format. Local ``file://`` URLs are read from
+ disk and remote URLs are downloaded.
+ block_type (`str`):
+ The Anthropic block type, ``"image"`` or ``"document"``.
Returns:
`dict[str, Any]`:
- The formatted image source.
+ The formatted content block.
"""
if isinstance(source, Base64Source):
- return {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": source.media_type,
- "data": source.data,
- },
- }
+ data = source.data
elif isinstance(source, URLSource):
url = str(source.url)
if url.startswith("file://"):
- # Local file - read and convert to base64
- file_path = url.removeprefix("file://")
- with open(file_path, "rb") as f:
+ with open(url.removeprefix("file://"), "rb") as f:
data = base64.b64encode(f.read()).decode("utf-8")
- return {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": source.media_type,
- "data": data,
- },
- }
else:
- # Remote URL - download and convert to base64
response = requests.get(url, timeout=30)
response.raise_for_status()
data = base64.b64encode(response.content).decode("utf-8")
- return {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": source.media_type,
- "data": data,
- },
- }
else:
raise ValueError(f"Unsupported source type: {type(source)}")
+ return {
+ "type": block_type,
+ "source": {
+ "type": "base64",
+ "media_type": source.media_type,
+ "data": data,
+ },
+ }
+
class AnthropicChatFormatter(_AnthropicFormatterBase):
"""The Anthropic formatter class for chatbot scenario, where only a user
@@ -375,10 +365,10 @@ class AnthropicChatFormatter(_AnthropicFormatterBase):
"""
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*"],
+ default_factory=lambda: ["text/plain", "image/*", "application/pdf"],
description=(
"The supported input types. "
- 'Defaults to ``["text/plain", "image/*"]``.'
+ 'Defaults to ``["text/plain", "image/*", "application/pdf"]``.'
),
)
@@ -420,10 +410,10 @@ class AnthropicMultiAgentFormatter(_AnthropicFormatterBase):
)
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*"],
+ default_factory=lambda: ["text/plain", "image/*", "application/pdf"],
description=(
"The supported input types. "
- 'Defaults to ``["text/plain", "image/*"]``.'
+ 'Defaults to ``["text/plain", "image/*", "application/pdf"]``.'
),
)
diff --git a/src/agentscope/formatter/_gemini_formatter.py b/src/agentscope/formatter/_gemini_formatter.py
index bf77638c8..b1a287c57 100644
--- a/src/agentscope/formatter/_gemini_formatter.py
+++ b/src/agentscope/formatter/_gemini_formatter.py
@@ -120,10 +120,11 @@ class GeminiChatFormatter(_GeminiFormatterBase):
"image/*",
"audio/*",
"video/*",
+ "application/pdf",
],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*", "video/*"]``.'
+ 'The supported input types. Defaults to ``["text/plain", '
+ '"image/*", "audio/*", "video/*", "application/pdf"]``.'
),
)
@@ -317,10 +318,11 @@ class GeminiMultiAgentFormatter(_GeminiFormatterBase):
"image/*",
"audio/*",
"video/*",
+ "application/pdf",
],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*", "video/*"]``.'
+ 'The supported input types. Defaults to ``["text/plain", '
+ '"image/*", "audio/*", "video/*", "application/pdf"]``.'
),
)
diff --git a/src/agentscope/formatter/_openai_formatter.py b/src/agentscope/formatter/_openai_formatter.py
index 245fc62dc..a94d8ae56 100644
--- a/src/agentscope/formatter/_openai_formatter.py
+++ b/src/agentscope/formatter/_openai_formatter.py
@@ -67,6 +67,9 @@ class _OpenAIFormatterBase(FormatterBase, ABC):
if main_type == "audio":
return self._format_audio_source(block.source)
+ if block.source.media_type == "application/pdf":
+ return self._format_file_source(block.source, block.name)
+
logger.warning(
"Unsupported main media type %s for OpenAI API. "
"This block will be skipped.",
@@ -136,16 +139,23 @@ class _OpenAIFormatterBase(FormatterBase, ABC):
"""
if isinstance(source, Base64Source):
media_type = source.media_type
- if media_type not in ["audio/wav", "audio/mp3"]:
+ _AUDIO_FORMAT_MAP = {
+ "audio/wav": "wav",
+ "audio/mp3": "mp3",
+ "audio/mpeg": "mp3",
+ }
+ fmt = _AUDIO_FORMAT_MAP.get(media_type)
+ if fmt is None:
raise TypeError(
f"Unsupported audio media type: {media_type}, "
- "only audio/wav and audio/mp3 are supported.",
+ "only audio/wav, audio/mp3 and audio/mpeg"
+ " are supported.",
)
return {
"type": "input_audio",
"input_audio": {
"data": source.data,
- "format": media_type.split("/")[-1],
+ "format": fmt,
},
}
@@ -185,6 +195,50 @@ class _OpenAIFormatterBase(FormatterBase, ABC):
raise TypeError(f"Unsupported audio source type: {type(source)}.")
+ @staticmethod
+ def _format_file_source(
+ source: URLSource | Base64Source,
+ name: str | None,
+ ) -> dict[str, Any]:
+ """Convert a PDF source to the OpenAI ``file`` content part.
+
+ Files are always inlined as base64 data URIs: local ``file://`` URLs
+ are read from disk and remote URLs are downloaded, since the Chat
+ Completions API has no URL form for files.
+
+ Args:
+ source (`URLSource | Base64Source`):
+ The file source to convert.
+ name (`str | None`):
+ The file name presented to the API, falls back to
+ ``"document.pdf"``.
+
+ Returns:
+ `dict[str, Any]`:
+ A dictionary with ``"type": "file"`` in OpenAI format.
+ """
+ if isinstance(source, Base64Source):
+ data = source.data
+ elif isinstance(source, URLSource):
+ url_str = str(source.url)
+ if url_str.startswith("file://"):
+ with open(url_str.removeprefix("file://"), "rb") as f:
+ data = base64.b64encode(f.read()).decode("utf-8")
+ else:
+ response = requests.get(url_str, timeout=30)
+ response.raise_for_status()
+ data = base64.b64encode(response.content).decode("utf-8")
+ else:
+ raise ValueError(f"Unsupported file source type: {type(source)}")
+
+ return {
+ "type": "file",
+ "file": {
+ "filename": name or "document.pdf",
+ "file_data": f"data:{source.media_type};base64,{data}",
+ },
+ }
+
class OpenAIChatFormatter(_OpenAIFormatterBase):
"""The OpenAI formatter class for chatbot scenario, where only a user
@@ -193,10 +247,15 @@ class OpenAIChatFormatter(_OpenAIFormatterBase):
"""
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*", "audio/*"],
+ default_factory=lambda: [
+ "text/plain",
+ "image/*",
+ "audio/*",
+ "application/pdf",
+ ],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*"]``.'
+ "The supported input types. Defaults to "
+ '``["text/plain", "image/*", "audio/*", "application/pdf"]``.'
),
)
@@ -385,10 +444,15 @@ class OpenAIMultiAgentFormatter(_OpenAIFormatterBase):
)
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*", "audio/*"],
+ default_factory=lambda: [
+ "text/plain",
+ "image/*",
+ "audio/*",
+ "application/pdf",
+ ],
description=(
- "The supported input types. "
- 'Defaults to ``["text/plain", "image/*", "audio/*"]``.'
+ "The supported input types. Defaults to "
+ '``["text/plain", "image/*", "audio/*", "application/pdf"]``.'
),
)
diff --git a/src/agentscope/formatter/_openai_response_formatter.py b/src/agentscope/formatter/_openai_response_formatter.py
index b96ae2037..be59159a4 100644
--- a/src/agentscope/formatter/_openai_response_formatter.py
+++ b/src/agentscope/formatter/_openai_response_formatter.py
@@ -27,10 +27,10 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):
"""
input_types: list[str] = Field(
- default_factory=lambda: ["text/plain", "image/*"],
+ default_factory=lambda: ["text/plain", "image/*", "application/pdf"],
description=(
"The supported input types. "
- 'Defaults to ``["text/plain", "image/*"]``. '
+ 'Defaults to ``["text/plain", "image/*", "application/pdf"]``. '
"Audio is not supported by the Responses API."
),
)
@@ -45,6 +45,7 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):
Completions API:
* ``image_url`` → ``input_image``
+ * ``file`` → ``input_file``
* ``input_audio`` → skipped (the Responses API does not support
audio input yet; use Chat Completions API instead). See
https://developers.openai.com/api/docs/guides/audio
@@ -82,6 +83,9 @@ class _OpenAIResponseFormatterBase(_OpenAIFormatterBase, ABC):
"image_url": base_result["image_url"]["url"],
}
+ if base_result.get("type") == "file":
+ return {"type": "input_file", **base_result["file"]}
+
return base_result
diff --git a/src/agentscope/model/_anthropic/_models/claude-fable-5.yaml b/src/agentscope/model/_anthropic/_models/claude-fable-5.yaml
index ddddbee9b..ec6172214 100644
--- a/src/agentscope/model/_anthropic/_models/claude-fable-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-fable-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-haiku-4-5.yaml b/src/agentscope/model/_anthropic/_models/claude-haiku-4-5.yaml
index eadc361f8..456350987 100644
--- a/src/agentscope/model/_anthropic/_models/claude-haiku-4-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-haiku-4-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-opus-4-5.yaml b/src/agentscope/model/_anthropic/_models/claude-opus-4-5.yaml
index 4b7e8048d..cf8c67a9d 100644
--- a/src/agentscope/model/_anthropic/_models/claude-opus-4-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-opus-4-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-opus-4-6.yaml b/src/agentscope/model/_anthropic/_models/claude-opus-4-6.yaml
index 7b395e0a6..b165755b2 100644
--- a/src/agentscope/model/_anthropic/_models/claude-opus-4-6.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-opus-4-6.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-opus-4-7.yaml b/src/agentscope/model/_anthropic/_models/claude-opus-4-7.yaml
index 1777373d8..f81a8a106 100644
--- a/src/agentscope/model/_anthropic/_models/claude-opus-4-7.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-opus-4-7.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-opus-4-8.yaml b/src/agentscope/model/_anthropic/_models/claude-opus-4-8.yaml
index 924f3a87f..14632f6d4 100644
--- a/src/agentscope/model/_anthropic/_models/claude-opus-4-8.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-opus-4-8.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-opus-5.yaml b/src/agentscope/model/_anthropic/_models/claude-opus-5.yaml
index 714c576bc..cfe22a130 100644
--- a/src/agentscope/model/_anthropic/_models/claude-opus-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-opus-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-sonnet-4-5.yaml b/src/agentscope/model/_anthropic/_models/claude-sonnet-4-5.yaml
index d97fe098b..f73b6c1f9 100644
--- a/src/agentscope/model/_anthropic/_models/claude-sonnet-4-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-sonnet-4-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-sonnet-4-6.yaml b/src/agentscope/model/_anthropic/_models/claude-sonnet-4-6.yaml
index b4783a1b1..cee6d05d0 100644
--- a/src/agentscope/model/_anthropic/_models/claude-sonnet-4-6.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-sonnet-4-6.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_anthropic/_models/claude-sonnet-5.yaml b/src/agentscope/model/_anthropic/_models/claude-sonnet-5.yaml
index 45d4008e0..d623d7b6e 100644
--- a/src/agentscope/model/_anthropic/_models/claude-sonnet-5.yaml
+++ b/src/agentscope/model/_anthropic/_models/claude-sonnet-5.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_gemini/_models/gemini-2.5-flash.yaml b/src/agentscope/model/_gemini/_models/gemini-2.5-flash.yaml
index 9e1b9020a..318f69c30 100644
--- a/src/agentscope/model/_gemini/_models/gemini-2.5-flash.yaml
+++ b/src/agentscope/model/_gemini/_models/gemini-2.5-flash.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
- audio/mp3
- audio/wav
- video/mp4
diff --git a/src/agentscope/model/_gemini/_models/gemini-2.5-pro.yaml b/src/agentscope/model/_gemini/_models/gemini-2.5-pro.yaml
index 6b975fe54..abbb9a64d 100644
--- a/src/agentscope/model/_gemini/_models/gemini-2.5-pro.yaml
+++ b/src/agentscope/model/_gemini/_models/gemini-2.5-pro.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
- audio/mp3
- audio/wav
- video/mp4
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-4.1-mini.yaml b/src/agentscope/model/_openai_chat/_models/gpt-4.1-mini.yaml
index cc66dcaa5..4ba62ba3e 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-4.1-mini.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-4.1-mini.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-4.1-nano.yaml b/src/agentscope/model/_openai_chat/_models/gpt-4.1-nano.yaml
index d8cfac057..c1317a3c6 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-4.1-nano.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-4.1-nano.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-4.1.yaml b/src/agentscope/model/_openai_chat/_models/gpt-4.1.yaml
index f26b14301..38ddfcd7a 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-4.1.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-4.1.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-4o-mini.yaml b/src/agentscope/model/_openai_chat/_models/gpt-4o-mini.yaml
index b41ac171c..cb2c84f33 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-4o-mini.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-4o-mini.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-4o.yaml b/src/agentscope/model/_openai_chat/_models/gpt-4o.yaml
index 5b19e6883..4a2d668ae 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-4o.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-4o.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-5.4.yaml b/src/agentscope/model/_openai_chat/_models/gpt-5.4.yaml
index dec7e31bd..770d1074a 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-5.4.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-5.4.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-5.5.yaml b/src/agentscope/model/_openai_chat/_models/gpt-5.5.yaml
index 75ed83d21..de15a32ea 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-5.5.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-5.5.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-5.6-luna.yaml b/src/agentscope/model/_openai_chat/_models/gpt-5.6-luna.yaml
index 4a77d13da..f04d847ae 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-5.6-luna.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-5.6-luna.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-5.6-sol.yaml b/src/agentscope/model/_openai_chat/_models/gpt-5.6-sol.yaml
index 23126dbc8..586fc8454 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-5.6-sol.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-5.6-sol.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/gpt-5.6-terra.yaml b/src/agentscope/model/_openai_chat/_models/gpt-5.6-terra.yaml
index 0688ce0f3..74913c60f 100644
--- a/src/agentscope/model/_openai_chat/_models/gpt-5.6-terra.yaml
+++ b/src/agentscope/model/_openai_chat/_models/gpt-5.6-terra.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/o3.yaml b/src/agentscope/model/_openai_chat/_models/o3.yaml
index 78473d0c7..56e0f678f 100644
--- a/src/agentscope/model/_openai_chat/_models/o3.yaml
+++ b/src/agentscope/model/_openai_chat/_models/o3.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_chat/_models/o4-mini.yaml b/src/agentscope/model/_openai_chat/_models/o4-mini.yaml
index 87fbcd9eb..b72f88242 100644
--- a/src/agentscope/model/_openai_chat/_models/o4-mini.yaml
+++ b/src/agentscope/model/_openai_chat/_models/o4-mini.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml
index a6bdad35e..06ccd7125 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1-mini.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml
index 34f000ffc..fd81fce7b 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1-nano.yaml
@@ -9,6 +9,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml b/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml
index 8a828ebfd..37d4ba47e 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-4.1.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml b/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml
index da2ec3901..e808f59bf 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-4o-mini.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-4o.yaml b/src/agentscope/model/_openai_response/_models/gpt-4o.yaml
index e19c9be73..419735bbd 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-4o.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-4o.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.4.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.4.yaml
index 6d99663b0..7dcf03ac8 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-5.4.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-5.4.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml
index 34c92a47b..3d1edf00a 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-5.5.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml
index 2817d739a..9f6fd13e5 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-luna.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml
index ee21e20c8..ebeb0b576 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-sol.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml b/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml
index b7c3535a6..4440e7e3e 100644
--- a/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml
+++ b/src/agentscope/model/_openai_response/_models/gpt-5.6-terra.yaml
@@ -8,6 +8,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/o3.yaml b/src/agentscope/model/_openai_response/_models/o3.yaml
index 8cd74f603..f226688b3 100644
--- a/src/agentscope/model/_openai_response/_models/o3.yaml
+++ b/src/agentscope/model/_openai_response/_models/o3.yaml
@@ -10,6 +10,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/model/_openai_response/_models/o4-mini.yaml b/src/agentscope/model/_openai_response/_models/o4-mini.yaml
index a8cd18a4f..cb40cc65f 100644
--- a/src/agentscope/model/_openai_response/_models/o4-mini.yaml
+++ b/src/agentscope/model/_openai_response/_models/o4-mini.yaml
@@ -10,6 +10,7 @@ input_types:
- image/png
- image/gif
- image/webp
+ - application/pdf
output_types:
- text/plain
diff --git a/src/agentscope/tool/_builtin/_read.py b/src/agentscope/tool/_builtin/_read.py
index 9d18006fb..2d90e2330 100644
--- a/src/agentscope/tool/_builtin/_read.py
+++ b/src/agentscope/tool/_builtin/_read.py
@@ -1,9 +1,14 @@
# -*- coding: utf-8 -*-
"""The read tool in agentscope."""
+import base64
import fnmatch
+import os
+import re
from typing import Any, List
-from .._base import ToolBase, ToolMiddlewareBase
+from pydantic import Field
+
+from .._base import ParamsBase, ToolBase, ToolMiddlewareBase
from ...permission import (
PermissionContext,
PermissionDecision,
@@ -11,10 +16,68 @@ from ...permission import (
PermissionRule,
)
from .._response import ToolChunk
-from ...message import TextBlock, ToolResultState
+from ...message import (
+ TextBlock,
+ DataBlock,
+ Base64Source,
+ ToolResultState,
+)
from ...state import AgentState
from ._backend import BackendBase, _normalize_newlines
+_IMAGE_EXTENSIONS: dict[str, str] = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".bmp": "image/bmp",
+ ".tiff": "image/tiff",
+ ".tif": "image/tiff",
+ ".ico": "image/x-icon",
+}
+
+# PDFs with more pages than this require an explicit ``pages`` range, and a
+# single read returns at most ``_PDF_MAX_PAGES_PER_READ`` pages.
+_PDF_MAX_PAGES_WITHOUT_RANGE = 10
+_PDF_MAX_PAGES_PER_READ = 20
+
+# Image types accepted by the Anthropic, OpenAI, Gemini and DashScope APIs.
+_DEFAULT_MODEL_INPUT_TYPES = [
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+]
+
+
+class _ReadParams(ParamsBase):
+ """The parameters of the Read tool."""
+
+ file_path: str = Field(
+ description="The absolute path to the file to read.",
+ )
+ offset: int = Field(
+ default=1,
+ ge=1,
+ description="Optional 1-based line number to start reading from. "
+ "Only applies to plain text files (default: 1)",
+ )
+ limit: int = Field(
+ default=2000,
+ ge=1,
+ le=2000,
+ description="Optional maximum number of lines to read. Only applies "
+ "to plain text files (default: 2000, max: 2000)",
+ )
+ pages: str | None = Field(
+ default=None,
+ description='Page range for PDF files (e.g. "1-5", "3", "10-20"), '
+ f"max {_PDF_MAX_PAGES_PER_READ} pages per request; required for "
+ f"PDFs over {_PDF_MAX_PAGES_WITHOUT_RANGE} pages. Only applies to "
+ "PDF files.",
+ )
+
class Read(ToolBase):
"""The read tool."""
@@ -23,43 +86,41 @@ class Read(ToolBase):
"""The tool name presented to the agent."""
# pylint: disable=line-too-long
- description: str = """Reads a file from the local filesystem. You can access any file directly by using this tool.
+ _DESCRIPTION_HEAD: str = """Reads a file from the local filesystem. You can access any file directly by using this tool.
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
Usage:
- The file_path parameter must be an absolute path, not a relative path
- By default, it reads up to 2000 lines starting from the beginning of the file
- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
-- Results are returned using cat -n format, with line numbers starting at 1
-- This tool allows you to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as you're a multimodal LLM.
-- This tool can read PDF files (.pdf). For large PDFs (more than 10 pages), you MUST provide the pages parameter to read specific pages.""" # noqa: E501
- """The description presented to the agent."""
-
- input_schema: dict[str, Any] = {
- "type": "object",
- "properties": {
- "file_path": {
- "type": "string",
- "description": "The absolute path to the file to read.",
- },
- "offset": {
- "type": "integer",
- "description": "Optional 1-based line number to start reading "
- "from (default: 1)",
- "default": 1,
- "minimum": 1,
- },
- "limit": {
- "type": "integer",
- "description": "Optional maximum number of lines to read "
- "(default: 2000, max: 2000)",
- "default": 2000,
- "maximum": 2000,
- "minimum": 1,
- },
- },
- "required": ["file_path"],
- }
+- Results are returned using cat -n format, with line numbers starting at 1""" # noqa: E501
+
+ @property
+ def description(self) -> str: # type: ignore[override]
+ """The description presented to the agent, with the image and PDF
+ bullets rendered from the model's accepted input types."""
+ lines = [self._DESCRIPTION_HEAD]
+ image_types = [
+ t for t in self.model_input_types if t.startswith("image/")
+ ]
+ if image_types:
+ lines.append(
+ f"- This tool allows you to read images ({', '.join(image_types)}). When reading an image file the contents are presented visually as you're a multimodal LLM.", # noqa: E501
+ )
+ pdf_presentation = (
+ "When reading a PDF file the pages are presented to you as a document." # noqa: E501
+ if any(
+ fnmatch.fnmatch("application/pdf", t)
+ for t in self.model_input_types
+ )
+ else "Text is extracted per page."
+ )
+ lines.append(
+ f"- This tool can read PDF files (.pdf). {pdf_presentation} For large PDFs (more than {_PDF_MAX_PAGES_WITHOUT_RANGE} pages), you MUST provide the pages parameter to read specific pages (max {_PDF_MAX_PAGES_PER_READ} pages per request).", # noqa: E501
+ )
+ return "\n".join(lines)
+
+ input_schema: dict[str, Any] = _ReadParams.model_json_schema()
is_mcp: bool = False
is_read_only: bool = True
@@ -70,6 +131,7 @@ Usage:
def __init__(
self,
max_line_characters: int = 2000,
+ model_input_types: list[str] | None = None,
middlewares: List[ToolMiddlewareBase] | None = None,
backend: BackendBase | None = None,
) -> None:
@@ -82,6 +144,17 @@ Usage:
a "[truncated]" suffix. This prevents overwhelming the agent
with excessively long lines while still providing useful
content.
+ model_input_types (`list[str] | None`, optional):
+ The media types the downstream model accepts as input,
+ aligned with the model card's ``input_types`` field so it
+ can be passed through directly, e.g.
+ ``Read(model_input_types=model_card.input_types)``. Glob
+ patterns like ``"image/*"`` are accepted. Files whose media
+ type is listed are returned as ``DataBlock`` for the model
+ to consume natively; otherwise images return an error and
+ PDFs fall back to local text extraction. Defaults to
+ ``image/png``, ``image/jpeg``, ``image/gif`` and
+ ``image/webp``.
middlewares (`List[ToolMiddlewareBase] | None`, optional):
Tool middlewares wrapping the tool execution.
backend (`BackendBase | None`, optional):
@@ -92,6 +165,10 @@ Usage:
super().__init__(middlewares=middlewares)
self._max_line_characters = max_line_characters
+ self.model_input_types = (
+ model_input_types or _DEFAULT_MODEL_INPUT_TYPES
+ )
+ """The media types the model accepts as input, see ``__init__``."""
self._backend = backend or LocalBackend()
async def check_permissions(
@@ -182,9 +259,16 @@ Usage:
file_path: str,
offset: int = 1,
limit: int = 2000,
+ pages: str | None = None,
_agent_state: AgentState | None = None,
) -> ToolChunk:
- """Read the file and return the content with line numbers."""
+ """Read a file and return content as appropriate block types.
+
+ Dispatches to format-specific readers based on file extension:
+ - PDF: text extraction via RAG parser
+ - Image: base64-encoded DataBlock
+ - Other: line-numbered text (TextBlock)
+ """
# Validate file_path is absolute
if not self._backend.isabs(file_path):
@@ -222,6 +306,196 @@ Usage:
is_last=True,
)
+ # Determine file type by extension. splitext on the basename works
+ # for both posix and windows style backend paths.
+ ext = os.path.splitext(self._backend.basename(file_path))[1].lower()
+
+ if ext == ".pdf":
+ return await self._read_pdf(file_path, pages)
+ if ext in _IMAGE_EXTENSIONS:
+ return await self._read_image_file(file_path, ext)
+
+ return await self._read_text_file(
+ file_path,
+ offset,
+ limit,
+ _agent_state,
+ )
+
+ async def _read_image_file(
+ self,
+ file_path: str,
+ ext: str,
+ ) -> ToolChunk:
+ """Read an image file and return as DataBlock."""
+ media_type = _IMAGE_EXTENSIONS[ext]
+ if not any(
+ fnmatch.fnmatch(media_type, t) for t in self.model_input_types
+ ):
+ image_types = [
+ t for t in self.model_input_types if t.startswith("image/")
+ ]
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Error: Unsupported image type {media_type}, "
+ f"only {', '.join(image_types) or 'none'} are "
+ "supported.",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ try:
+ raw = await self._backend.read_file(file_path)
+ except Exception as e:
+ return ToolChunk(
+ content=[
+ TextBlock(text=f"Error reading file: {str(e)}"),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ return ToolChunk(
+ content=[
+ DataBlock(
+ source=Base64Source(
+ data=base64.b64encode(raw).decode("ascii"),
+ media_type=media_type,
+ ),
+ name=self._backend.basename(file_path),
+ ),
+ ],
+ state=ToolResultState.RUNNING,
+ is_last=True,
+ )
+
+ async def _read_pdf(
+ self,
+ file_path: str,
+ pages: str | None = None,
+ ) -> ToolChunk:
+ """Read a PDF file. When the model accepts ``application/pdf`` the
+ requested pages are returned as a PDF ``DataBlock``, otherwise their
+ text is extracted locally into a ``TextBlock``."""
+ import io
+
+ from pypdf import PdfReader, PdfWriter
+
+ try:
+ raw = await self._backend.read_file(file_path)
+ reader = PdfReader(io.BytesIO(raw))
+ total_pages = len(reader.pages)
+ except Exception as e:
+ return ToolChunk(
+ content=[TextBlock(text=f"Error reading PDF: {str(e)}")],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ if pages is None:
+ if total_pages > _PDF_MAX_PAGES_WITHOUT_RANGE:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Error: PDF has {total_pages} pages, "
+ f"more than {_PDF_MAX_PAGES_WITHOUT_RANGE}. "
+ "You must provide the pages parameter (e.g. "
+ '"1-5") to read specific pages, max '
+ f"{_PDF_MAX_PAGES_PER_READ} pages per request.",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ first, last = 1, total_pages
+ else:
+ match = re.fullmatch(r"\s*(\d+)\s*(?:-\s*(\d+)\s*)?", pages)
+ if not match:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Error: Invalid pages {pages!r}. Expected "
+ 'a page number or range like "3" or "1-5".',
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ first = int(match.group(1))
+ last = int(match.group(2)) if match.group(2) else first
+ if first < 1 or first > last or first > total_pages:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Error: Invalid pages {pages!r}. PDF has "
+ f"{total_pages} page(s).",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+ last = min(last, total_pages)
+ if last - first + 1 > _PDF_MAX_PAGES_PER_READ:
+ return ToolChunk(
+ content=[
+ TextBlock(
+ text=f"Error: Requested {last - first + 1} "
+ f"pages, at most {_PDF_MAX_PAGES_PER_READ} "
+ "pages can be read per request.",
+ ),
+ ],
+ state=ToolResultState.ERROR,
+ is_last=True,
+ )
+
+ if not any(
+ fnmatch.fnmatch("application/pdf", t)
+ for t in self.model_input_types
+ ):
+ text_parts = [
+ f"--- Page {page_num}/{total_pages} ---\n"
+ f"{reader.pages[page_num - 1].extract_text() or ''}"
+ for page_num in range(first, last + 1)
+ ]
+ return ToolChunk(
+ content=[TextBlock(text="\n\n".join(text_parts))],
+ state=ToolResultState.RUNNING,
+ is_last=True,
+ )
+
+ # Hand the PDF itself to the model, trimmed to the requested pages.
+ if (first, last) != (1, total_pages):
+ writer = PdfWriter()
+ for page_num in range(first, last + 1):
+ writer.add_page(reader.pages[page_num - 1])
+ buf = io.BytesIO()
+ writer.write(buf)
+ raw = buf.getvalue()
+ return ToolChunk(
+ content=[
+ DataBlock(
+ source=Base64Source(
+ data=base64.b64encode(raw).decode("ascii"),
+ media_type="application/pdf",
+ ),
+ name=self._backend.basename(file_path),
+ ),
+ ],
+ state=ToolResultState.RUNNING,
+ is_last=True,
+ )
+
+ async def _read_text_file(
+ self,
+ file_path: str,
+ offset: int,
+ limit: int,
+ _agent_state: AgentState | None,
+ ) -> ToolChunk:
+ """Read a text file and return with line numbers."""
try:
# Read file content via backend
lines = None
@@ -257,7 +531,7 @@ Usage:
# Remove trailing newline if present
line_content = line.rstrip("\n\r")
- # Truncate lines longer than 2000 chars
+ # Truncate lines longer than max_line_characters
if len(line_content) > self._max_line_characters:
line_content = (
line_content[: self._max_line_characters]
diff --git a/tests/builtin_read_test.py b/tests/builtin_read_test.py
index ad82659ea..28d4fcf67 100644
--- a/tests/builtin_read_test.py
+++ b/tests/builtin_read_test.py
@@ -1,8 +1,11 @@
# -*- coding: utf-8 -*-
"""Read tool test case."""
+import base64
+import io
import os
import tempfile
from unittest.async_case import IsolatedAsyncioTestCase
+from utils import AnyString
from agentscope.tool import ToolChunk, Read
from agentscope.permission import (
@@ -13,6 +16,7 @@ from agentscope.permission import (
from agentscope.message import TextBlock
+# pylint: disable=too-many-public-methods
class ReadToolTest(IsolatedAsyncioTestCase):
"""The read tool test case."""
@@ -20,10 +24,12 @@ class ReadToolTest(IsolatedAsyncioTestCase):
"""The async setup method."""
self.read_tool = Read()
# Create a temporary file for testing
- self.temp_file = tempfile.NamedTemporaryFile(
- mode="w",
- delete=False,
- suffix=".txt",
+ self.temp_file = (
+ tempfile.NamedTemporaryFile( # pylint: disable=consider-using-with
+ mode="w",
+ delete=False,
+ suffix=".txt",
+ )
)
# Write multiple lines
for i in range(1, 11):
@@ -38,8 +44,73 @@ class ReadToolTest(IsolatedAsyncioTestCase):
async def test_tool_properties(self) -> None:
"""Test read tool properties."""
self.assertEqual(self.read_tool.name, "Read")
- self.assertIsInstance(self.read_tool.description, str)
- self.assertIsInstance(self.read_tool.input_schema, dict)
+ self.assertDictEqual(
+ self.read_tool.input_schema,
+ {
+ "type": "object",
+ "description": "The parameters of the Read tool.",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "The absolute path to the file to "
+ "read.",
+ },
+ "offset": {
+ "type": "integer",
+ "default": 1,
+ "minimum": 1,
+ "description": "Optional 1-based line number to "
+ "start reading from. Only applies to plain text "
+ "files (default: 1)",
+ },
+ "limit": {
+ "type": "integer",
+ "default": 2000,
+ "minimum": 1,
+ "maximum": 2000,
+ "description": "Optional maximum number of lines to "
+ "read. Only applies to plain text files (default: "
+ "2000, max: 2000)",
+ },
+ "pages": {
+ "anyOf": [{"type": "string"}, {"type": "null"}],
+ "default": None,
+ "description": 'Page range for PDF files (e.g. "1-5", '
+ '"3", "10-20"), max 20 pages per request; required '
+ "for PDFs over 10 pages. Only applies to PDF files.",
+ },
+ },
+ "required": ["file_path"],
+ },
+ )
+ # The image and PDF bullets follow the model's input types.
+ self.assertEqual(
+ self.read_tool.description.splitlines()[-2:],
+ [
+ "- This tool allows you to read images (image/png, "
+ "image/jpeg, image/gif, image/webp). When reading an image "
+ "file the contents are presented visually as you're a "
+ "multimodal LLM.",
+ "- This tool can read PDF files (.pdf). Text is extracted "
+ "per page. For large PDFs (more than 10 pages), you MUST "
+ "provide the pages parameter to read specific pages (max "
+ "20 pages per request).",
+ ],
+ )
+ self.assertEqual(
+ Read(
+ model_input_types=["text/plain", "application/pdf"],
+ ).description.splitlines()[-2:],
+ [
+ "- Results are returned using cat -n format, with line "
+ "numbers starting at 1",
+ "- This tool can read PDF files (.pdf). When reading a PDF "
+ "file the pages are presented to you as a document. For "
+ "large PDFs (more than 10 pages), you MUST provide the "
+ "pages parameter to read specific pages (max 20 pages per "
+ "request).",
+ ],
+ )
self.assertFalse(self.read_tool.is_mcp)
self.assertTrue(self.read_tool.is_read_only)
self.assertTrue(self.read_tool.is_concurrency_safe)
@@ -186,3 +257,379 @@ class ReadToolTest(IsolatedAsyncioTestCase):
{"file_path": "/test.py"},
)
self.assertGreater(len(suggestions), 0)
+
+ async def test_read_image_file_returns_data_block(self) -> None:
+ """Test reading an image file returns a base64 DataBlock."""
+ img_data = b"\x89PNG\r\n\x1a\n" + b"\x00" * 100
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as f:
+ f.write(img_data)
+ self.addCleanup(os.unlink, f.name)
+
+ chunk = await self.read_tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": base64.b64encode(img_data).decode(),
+ "media_type": "image/png",
+ },
+ "name": os.path.basename(f.name),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ async def test_read_image_unsupported_type(self) -> None:
+ """Test images outside ``model_input_types`` return an error."""
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".bmp") as f:
+ f.write(b"BM" + b"\x00" * 100)
+ self.addCleanup(os.unlink, f.name)
+
+ # image/bmp is not in the default input types.
+ chunk = await self.read_tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "Error: Unsupported image type image/bmp, "
+ "only image/png, image/jpeg, image/gif, image/webp "
+ "are supported.",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "error",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ # Model card style input types (non-image entries ignored) and glob
+ # patterns are accepted.
+ for model_input_types in [["text/plain", "image/bmp"], ["image/*"]]:
+ tool = Read(model_input_types=model_input_types)
+ chunk = await tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": base64.b64encode(
+ b"BM" + b"\x00" * 100,
+ ).decode(),
+ "media_type": "image/bmp",
+ },
+ "name": os.path.basename(f.name),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ # The attribute can be changed after construction.
+ tool.model_input_types = ["text/plain"]
+ chunk = await tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "Error: Unsupported image type image/bmp, "
+ "only none are supported.",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "error",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+ self.assertNotIn("read images", tool.description)
+
+ async def test_read_pdf_file(self) -> None:
+ """Test reading a PDF file extracts text per page."""
+ from pypdf import PdfWriter
+
+ writer = PdfWriter()
+ writer.add_blank_page(width=612, height=792)
+ writer.add_blank_page(width=612, height=792)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
+ writer.write(f)
+ self.addCleanup(os.unlink, f.name)
+
+ chunk = await self.read_tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "--- Page 1/2 ---\n\n\n--- Page 2/2 ---\n",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "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
+
+ writer = PdfWriter()
+ for _ in range(5):
+ writer.add_blank_page(width=612, height=792)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
+ writer.write(f)
+ self.addCleanup(os.unlink, f.name)
+
+ # A range, a single page, and a range clipped to the last page.
+ for pages, text in [
+ ("2-3", "--- Page 2/5 ---\n\n\n--- Page 3/5 ---\n"),
+ ("4", "--- Page 4/5 ---\n"),
+ ("4-99", "--- Page 4/5 ---\n\n\n--- Page 5/5 ---\n"),
+ ]:
+ chunk = await self.read_tool(file_path=f.name, pages=pages)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": text,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ pages,
+ )
+
+ async def test_read_pdf_invalid_pages(self) -> None:
+ """Test malformed or out-of-range pages return an error."""
+ from pypdf import PdfWriter
+
+ writer = PdfWriter()
+ writer.add_blank_page(width=612, height=792)
+ writer.add_blank_page(width=612, height=792)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
+ writer.write(f)
+ self.addCleanup(os.unlink, f.name)
+
+ for pages, text in [
+ (
+ "abc",
+ "Error: Invalid pages 'abc'. Expected a page number or "
+ 'range like "3" or "1-5".',
+ ),
+ (
+ "1-2-3",
+ "Error: Invalid pages '1-2-3'. Expected a page number or "
+ 'range like "3" or "1-5".',
+ ),
+ ("0", "Error: Invalid pages '0'. PDF has 2 page(s)."),
+ ("3", "Error: Invalid pages '3'. PDF has 2 page(s)."),
+ ("2-1", "Error: Invalid pages '2-1'. PDF has 2 page(s)."),
+ ]:
+ chunk = await self.read_tool(file_path=f.name, pages=pages)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": text,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "error",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ pages,
+ )
+
+ async def test_read_large_pdf_page_limits(self) -> None:
+ """Test PDFs over 10 pages need ``pages`` and reads cap at 20."""
+ from pypdf import PdfWriter
+
+ writer = PdfWriter()
+ for _ in range(25):
+ writer.add_blank_page(width=612, height=792)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
+ writer.write(f)
+ self.addCleanup(os.unlink, f.name)
+
+ for pages, text in [
+ (
+ None,
+ "Error: PDF has 25 pages, more than 10. You must provide "
+ 'the pages parameter (e.g. "1-5") to read specific pages, '
+ "max 20 pages per request.",
+ ),
+ (
+ "1-21",
+ "Error: Requested 21 pages, at most 20 pages can be read "
+ "per request.",
+ ),
+ ]:
+ chunk = await self.read_tool(file_path=f.name, pages=pages)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": text,
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "error",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ pages,
+ )
+
+ chunk = await self.read_tool(file_path=f.name, pages="6-25")
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "\n\n".join(
+ f"--- Page {i}/25 ---\n" for i in range(6, 26)
+ ),
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ async def test_read_pdf_passthrough(self) -> None:
+ """Test PDFs are handed to the model as DataBlock when accepted."""
+ from pypdf import PdfReader, PdfWriter
+
+ writer = PdfWriter()
+ for _ in range(5):
+ writer.add_blank_page(width=612, height=792)
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as f:
+ writer.write(f)
+ self.addCleanup(os.unlink, f.name)
+ with open(f.name, "rb") as fp:
+ pdf_bytes = fp.read()
+
+ tool = Read(model_input_types=["image/*", "application/pdf"])
+
+ # Without pages the original bytes are returned untouched.
+ chunk = await tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "data",
+ "id": AnyString(),
+ "source": {
+ "type": "base64",
+ "data": base64.b64encode(pdf_bytes).decode(),
+ "media_type": "application/pdf",
+ },
+ "name": os.path.basename(f.name),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
+ # With pages only the requested pages are kept.
+ chunk = await tool(file_path=f.name, pages="2-3")
+ self.assertEqual(chunk.content[0].source.media_type, "application/pdf")
+ trimmed = base64.b64decode(chunk.content[0].source.data)
+ self.assertEqual(len(PdfReader(io.BytesIO(trimmed)).pages), 2)
+
+ async def test_read_unknown_extension_as_text(self) -> None:
+ """Test files with unknown extensions are read as text."""
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ delete=False,
+ suffix=".xyz",
+ ) as f:
+ f.write("hello world\nsecond line\n")
+ self.addCleanup(os.unlink, f.name)
+
+ chunk = await self.read_tool(file_path=f.name)
+ self.assertDictEqual(
+ chunk.model_dump(mode="json"),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": " 1\thello world\n 2\tsecond line",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
diff --git a/tests/formatter_anthropic_test.py b/tests/formatter_anthropic_test.py
index 3e19354b3..440c9d98e 100644
--- a/tests/formatter_anthropic_test.py
+++ b/tests/formatter_anthropic_test.py
@@ -337,6 +337,45 @@ class TestAnthropicFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_base64_pdf(self) -> None:
+ """Base64-encoded PDF is formatted as an Anthropic document block."""
+ fmt = AnthropicChatFormatter()
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="Summarize this."),
+ DataBlock(
+ source=Base64Source(
+ data="JVBERi0xLjQgZmFrZQ==",
+ media_type="application/pdf",
+ ),
+ name="report.pdf",
+ ),
+ ],
+ ),
+ ]
+ res = await fmt.format(msgs)
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Summarize this."},
+ {
+ "type": "document",
+ "source": {
+ "type": "base64",
+ "media_type": "application/pdf",
+ "data": "JVBERi0xLjQgZmFrZQ==",
+ },
+ },
+ ],
+ },
+ ],
+ res,
+ )
+
async def test_chat_formatter_thinking_preserved(self) -> None:
"""ThinkingBlock with a signature is passed back as a thinking
content block."""
diff --git a/tests/formatter_gemini_test.py b/tests/formatter_gemini_test.py
index 21cd23da8..1430e3bfd 100644
--- a/tests/formatter_gemini_test.py
+++ b/tests/formatter_gemini_test.py
@@ -281,6 +281,42 @@ class TestGeminiFormatter(IsolatedAsyncioTestCase):
res = await fmt.format([])
self.assertListEqual([], res)
+ async def test_chat_formatter_base64_pdf(self) -> None:
+ """Base64-encoded PDF is passed through as ``inline_data``."""
+ fmt = GeminiChatFormatter()
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="Summarize this."),
+ DataBlock(
+ source=Base64Source(
+ data="JVBERi0xLjQgZmFrZQ==",
+ media_type="application/pdf",
+ ),
+ ),
+ ],
+ ),
+ ]
+ res = await fmt.format(msgs)
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "parts": [
+ {"text": "Summarize this."},
+ {
+ "inline_data": {
+ "data": "JVBERi0xLjQgZmFrZQ==",
+ "mime_type": "application/pdf",
+ },
+ },
+ ],
+ },
+ ],
+ res,
+ )
+
async def test_chat_formatter_thinking_preserved(self) -> None:
"""ThinkingBlock becomes a part with thought=True in Gemini format."""
fmt = GeminiChatFormatter()
diff --git a/tests/formatter_openai_chat_test.py b/tests/formatter_openai_chat_test.py
index 7ca7a4203..10999e7bc 100644
--- a/tests/formatter_openai_chat_test.py
+++ b/tests/formatter_openai_chat_test.py
@@ -349,6 +349,46 @@ class TestOpenAIFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_base64_pdf(self) -> None:
+ """Base64-encoded PDF becomes a ``file`` content part."""
+ fmt = OpenAIChatFormatter()
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="Summarize this."),
+ DataBlock(
+ source=Base64Source(
+ data="JVBERi0xLjQgZmFrZQ==",
+ media_type="application/pdf",
+ ),
+ name="report.pdf",
+ ),
+ ],
+ ),
+ ]
+ res = await fmt.format(msgs)
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "name": "user",
+ "content": [
+ {"type": "text", "text": "Summarize this."},
+ {
+ "type": "file",
+ "file": {
+ "filename": "report.pdf",
+ "file_data": "data:application/pdf;"
+ "base64,JVBERi0xLjQgZmFrZQ==",
+ },
+ },
+ ],
+ },
+ ],
+ res,
+ )
+
async def test_chat_formatter_thinking_dropped(self) -> None:
"""ThinkingBlock is silently dropped by OpenAI formatter."""
fmt = OpenAIChatFormatter()
diff --git a/tests/formatter_openai_response_test.py b/tests/formatter_openai_response_test.py
index bb1d66b27..3bb11c2d3 100644
--- a/tests/formatter_openai_response_test.py
+++ b/tests/formatter_openai_response_test.py
@@ -336,6 +336,42 @@ class TestOpenAIResponseFormatter(IsolatedAsyncioTestCase):
res,
)
+ async def test_chat_formatter_base64_pdf(self) -> None:
+ """Base64-encoded PDF becomes an ``input_file`` item."""
+ fmt = OpenAIResponseFormatter()
+ msgs = [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="Summarize this."),
+ DataBlock(
+ source=Base64Source(
+ data="JVBERi0xLjQgZmFrZQ==",
+ media_type="application/pdf",
+ ),
+ ),
+ ],
+ ),
+ ]
+ res = await fmt.format(msgs)
+ self.assertListEqual(
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": "Summarize this."},
+ {
+ "type": "input_file",
+ "filename": "document.pdf",
+ "file_data": "data:application/pdf;"
+ "base64,JVBERi0xLjQgZmFrZQ==",
+ },
+ ],
+ },
+ ],
+ res,
+ )
+
async def test_chat_formatter_thinking_dropped_without_reasoning_item_id(
self,
) -> None: