Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion src/anthropic/lib/tools/agent_toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import os
import re
import uuid
import base64
import shutil
import logging
import subprocess
Expand Down Expand Up @@ -144,6 +145,20 @@ def _fs_error(op: str, file_path: str, e: OSError) -> ToolError:
return ToolError(f"{op}: {file_path}: {reason}")


_BINARY_MEDIA_TYPES: dict[str, str] = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
".pdf": "application/pdf",
}


def _binary_media_type(path: Path) -> str | None:
return _BINARY_MEDIA_TYPES.get(path.suffix.lower())


def _empty_skill_dirs() -> list[Path]:
return []

Expand Down Expand Up @@ -494,7 +509,7 @@ async def bash(

def beta_read_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
@beta_async_tool(name="read", input_schema=BetaManagedAgentsAgentToolset20260401ReadInput)
async def read(file_path: str, view_range: Optional[List[int]] = None) -> str:
async def read(file_path: str, view_range: Optional[List[int]] = None) -> Any:
Comment thread
vihaan-kk marked this conversation as resolved.
"""Read a file rooted at the working directory."""
try:
target = resolve_path(ctx, file_path)
Expand All @@ -513,9 +528,16 @@ async def read(file_path: str, view_range: Optional[List[int]] = None) -> str:
f"read: {file_path} is {st.st_size} bytes, exceeds {limit}-byte limit. "
"Use bash (head/tail/sed) to read a slice."
)
media = _binary_media_type(target)
if media is not None:
data = base64.standard_b64encode(target.read_bytes()).decode("ascii")
kind = "document" if media == "application/pdf" else "image"
return [{"type": kind, "source": {"type": "base64", "media_type": media, "data": data}}]
Comment thread
vihaan-kk marked this conversation as resolved.
Comment on lines 528 to +535
text = target.read_text()
Comment on lines +531 to 536
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, noted this in the PR description as a follow-up. A separate lower size cap for base64 responses makes sense but felt out of scope for this fix.

except ToolError:
raise
except UnicodeDecodeError as e:
raise ToolError(f"read: {file_path}: file is not valid UTF-8 text; use bash to inspect binary files") from e
except OSError as e:
raise _fs_error("read", file_path, e) from e
if not view_range:
Expand Down