Skip to main content

Filesystem sandbox toolset for PydanticAI agents with LLM-friendly errors

Project description

pydantic-ai-filesystem-sandbox

Filesystem sandbox toolset for PydanticAI agents with LLM-friendly errors.

Why This Package?

When building LLM agents that interact with the filesystem, you need:

  1. Sandboxing - Restrict which directories the agent can access
  2. Read/Write Control - Fine-grained permissions per path
  3. LLM-Friendly Errors - Error messages that help the LLM correct its behavior
  4. Approval Integration - Works with human-in-the-loop approval flows

This package provides a FileSandboxImpl toolset that implements all of these as a PydanticAI AbstractToolset.

Installation

pip install pydantic-ai-filesystem-sandbox

Quick Start

from pydantic_ai import Agent
from pydantic_ai_filesystem_sandbox import (
    FileSandboxImpl,
    FileSandboxConfig,
    PathConfig,
)

# Configure sandbox paths
config = FileSandboxConfig(paths={
    "input": PathConfig(root="./data/input", mode="ro"),   # Read-only
    "output": PathConfig(root="./data/output", mode="rw"), # Read-write
})

# Create the sandbox toolset
sandbox = FileSandboxImpl(config)

# Use with PydanticAI agent
agent = Agent("openai:gpt-4", toolsets=[sandbox])

Configuration

PathConfig Options

Option Type Default Description
root str required Root directory path
mode "ro" | "rw" "ro" Access mode
suffixes list[str] | None None Allowed file extensions (None = all)
max_file_bytes int | None None Maximum file size limit
write_approval bool True Require approval for writes
read_approval bool False Require approval for reads

Example Configuration

config = FileSandboxConfig(paths={
    # Read-only input - any file type
    "input": PathConfig(
        root="./data/input",
        mode="ro",
    ),
    # Read-write output - only markdown and text
    "output": PathConfig(
        root="./data/output",
        mode="rw",
        suffixes=[".md", ".txt"],
        max_file_bytes=1_000_000,  # 1MB limit
    ),
    # Config files - read-only, requires approval
    "config": PathConfig(
        root="./config",
        mode="ro",
        read_approval=True,
    ),
})

Available Tools

The sandbox provides three tools to the agent:

read_file

Read a text file from the sandbox.

Path format: 'sandbox_name/relative/path'
Parameters:
  - path: str (required)
  - max_chars: int (default: 20,000)
  - offset: int (default: 0)

write_file

Write a text file to the sandbox (requires mode="rw").

Path format: 'sandbox_name/relative/path'
Parameters:
  - path: str (required)
  - content: str (required)

list_files

List files matching a glob pattern.

Parameters:
  - path: str (default: "." for all sandboxes)
  - pattern: str (default: "**/*")

LLM-Friendly Errors

All errors include guidance on what IS allowed:

# PathNotInSandboxError
"Cannot access 'secret/file.txt': path is outside sandbox.
Readable paths: input, output"

# PathNotWritableError
"Cannot write to 'input/file.txt': path is read-only.
Writable paths: output"

# SuffixNotAllowedError
"Cannot access 'output/data.json': suffix '.json' not allowed.
Allowed suffixes: .md, .txt"

# FileTooLargeError
"Cannot read 'output/huge.txt': file too large (5,000,000 bytes).
Maximum allowed: 1,000,000 bytes"

Approval Integration

Works with pydantic-ai-blocking-approval for human-in-the-loop:

from pydantic_ai_filesystem_sandbox import FileSandboxImpl, FileSandboxConfig, PathConfig
from pydantic_ai_blocking_approval import ApprovalToolset, ApprovalController

# Create sandbox
config = FileSandboxConfig(paths={
    "output": PathConfig(root="./output", mode="rw", write_approval=True),
})
sandbox = FileSandboxImpl(config)

# Wrap with approval
controller = ApprovalController(mode="interactive", approval_callback=my_prompt_fn)
approved_sandbox = ApprovalToolset(
    inner=sandbox,
    approval_callback=controller.approval_callback,
    memory=controller.memory,
)

agent = Agent(..., toolsets=[approved_sandbox])

The sandbox implements needs_approval() and present_for_approval() for fine-grained approval control.

ReadResult

The read_file tool returns a ReadResult object:

class ReadResult(BaseModel):
    content: str        # The file content read
    truncated: bool     # True if more content exists
    total_chars: int    # Total file size in characters
    offset: int         # Starting position used
    chars_read: int     # Characters actually returned

This allows agents to handle large files by reading in chunks:

# First read
result = sandbox.read("input/large.txt", max_chars=10000)
if result.truncated:
    # Continue reading
    result2 = sandbox.read("input/large.txt", max_chars=10000, offset=10000)

API Reference

Configuration

  • FileSandboxConfig - Top-level configuration with named paths
  • PathConfig - Configuration for a single sandbox path

Toolset

  • FileSandboxImpl - PydanticAI AbstractToolset implementation

Errors

  • FileSandboxError - Base class for all sandbox errors
  • PathNotInSandboxError - Path outside sandbox boundaries
  • PathNotWritableError - Write to read-only path
  • SuffixNotAllowedError - File extension not allowed
  • FileTooLargeError - File exceeds size limit

Types

  • ReadResult - Result of read operations with metadata

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_ai_filesystem_sandbox-0.2.0.tar.gz (178.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_ai_filesystem_sandbox-0.2.0-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_ai_filesystem_sandbox-0.2.0.tar.gz.

File metadata

File hashes

Hashes for pydantic_ai_filesystem_sandbox-0.2.0.tar.gz
Algorithm Hash digest
SHA256 fec1abeeab08fbb5d8ca62e6fdd28cdafe574a5c7b60c00586b68c73a0a4fe62
MD5 69eeae6882c2cabaead24ef1b145c05c
BLAKE2b-256 c5e89905c157491144b4330375771415445d6e3fcbebfdb55e0318ae8fb46ea6

See more details on using hashes here.

File details

Details for the file pydantic_ai_filesystem_sandbox-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_ai_filesystem_sandbox-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7afe2e00d62665b5026b7af488458b7e758d11b90cf44bd3c1fb920d7fe5a106
MD5 392a63e070fdf17ea3e8834aecf8c242
BLAKE2b-256 bbab5ceb4ad962de025fb427d6b2b3092574c75b52659fc43c91d6f85e111b8e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page