Skip to content

API Reference

Complete API documentation for pydantic-ai-backend.

Quick Example

Python
from dataclasses import dataclass
from pydantic_ai import Agent
from pydantic_ai_backends import LocalBackend, create_console_toolset

@dataclass
class Deps:
    backend: LocalBackend

backend = LocalBackend(root_dir=".")
toolset = create_console_toolset()
agent = Agent("openai:gpt-4o", deps_type=Deps).with_toolset(toolset)

result = agent.run_sync("Create hello.py and run it", deps=Deps(backend=backend))

Modules

Module Description
Backends LocalBackend, StateBackend, CompositeBackend
Docker DockerSandbox, SessionManager, RuntimeConfig
Daytona DaytonaSandbox cloud sandbox
Toolsets Console toolset for pydantic-ai
Types Type definitions

Import Reference

Python
# Toolset for pydantic-ai agents (requires [console] extra)
from pydantic_ai_backends import (
    create_console_toolset,
    get_console_system_prompt,
    ConsoleDeps,
)

# Backends
from pydantic_ai_backends import (
    LocalBackend,
    StateBackend,
    CompositeBackend,
)

# Docker (requires [docker] extra)
from pydantic_ai_backends import (
    DockerSandbox,
    SessionManager,
    RuntimeConfig,
    BUILTIN_RUNTIMES,
)

# Types
from pydantic_ai_backends import (
    FileInfo,
    WriteResult,
    EditResult,
    ExecuteResponse,
    GrepMatch,
)

# Protocols
from pydantic_ai_backends import (
    BackendProtocol,
    SandboxProtocol,
)

Protocols

BackendProtocol

All backends implement this interface.

pydantic_ai_backends.protocol.BackendProtocol

Bases: Protocol

Protocol for file storage backends.

All backends must implement these methods for basic file operations. This allows using different storage backends (in-memory, filesystem, Docker, cloud storage) interchangeably.

Example
Python
from pydantic_ai_backends import BackendProtocol, StateBackend

def process_files(backend: BackendProtocol) -> None:
    # Works with any backend implementation
    files = backend.ls_info("/")
    for f in files:
        content = backend.read(f["path"])
        print(content)
Source code in src/pydantic_ai_backends/protocol.py
Python
@runtime_checkable
class BackendProtocol(Protocol):
    """Protocol for file storage backends.

    All backends must implement these methods for basic file operations.
    This allows using different storage backends (in-memory, filesystem,
    Docker, cloud storage) interchangeably.

    Example:
        ```python
        from pydantic_ai_backends import BackendProtocol, StateBackend

        def process_files(backend: BackendProtocol) -> None:
            # Works with any backend implementation
            files = backend.ls_info("/")
            for f in files:
                content = backend.read(f["path"])
                print(content)
        ```
    """

    def exists(self, path: str) -> bool:
        """Check whether a file exists at the given path.

        Args:
            path: File path to check.

        Returns:
            True if the path resolves to an existing file, False otherwise.
            Returns False for invalid paths, directories, and permission errors —
            callers must use ls_info() to distinguish directories from missing paths.
        """
        ...

    def ls_info(self, path: str) -> list[FileInfo]:
        """List files and directories at the given path.

        Args:
            path: Directory path to list.

        Returns:
            List of FileInfo objects for each entry.
        """
        ...

    def read_bytes(self, path: str) -> bytes:
        """Read raw bytes from a file.

        Args:
            path: File path to read.

        Returns:
            File content as bytes.
        """
        ...

    def read(self, path: str, offset: int = 0, limit: int = 2000) -> str:
        """Read file content with line numbers.

        Args:
            path: File path to read.
            offset: Line number to start reading from (0-indexed).
            limit: Maximum number of lines to read.

        Returns:
            File content as a string with line numbers prefixed.
        """
        ...

    def write(self, path: str, content: str | bytes) -> WriteResult:
        """Write content to a file.

        Args:
            path: File path to write to.
            content: Content to write (string or bytes).

        Returns:
            WriteResult with path or error.
        """
        ...

    def edit(
        self, path: str, old_string: str, new_string: str, replace_all: bool = False
    ) -> EditResult:
        """Edit a file by replacing strings.

        Args:
            path: File path to edit.
            old_string: String to find and replace.
            new_string: Replacement string.
            replace_all: If True, replace all occurrences. Otherwise, replace only first.

        Returns:
            EditResult with path, error, or occurrence count.
        """
        ...

    def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
        """Find files matching a glob pattern.

        Args:
            pattern: Glob pattern (e.g., "**/*.py").
            path: Base directory to search from.

        Returns:
            List of matching FileInfo objects.
        """
        ...

    def grep_raw(
        self,
        pattern: str,
        path: str | None = None,
        glob: str | None = None,
        ignore_hidden: bool = True,
    ) -> list[GrepMatch] | str:
        """Search for pattern in files.

        Args:
            pattern: Regex pattern to search for.
            path: Specific file or directory to search.
            glob: Glob pattern to filter files.
            ignore_hidden: If True, ignore hidden files.

        Returns:
            List of GrepMatch objects or error string.
        """
        ...

ls_info(path)

List files and directories at the given path.

Parameters:

Name Type Description Default
path str

Directory path to list.

required

Returns:

Type Description
list[FileInfo]

List of FileInfo objects for each entry.

Source code in src/pydantic_ai_backends/protocol.py
Python
def ls_info(self, path: str) -> list[FileInfo]:
    """List files and directories at the given path.

    Args:
        path: Directory path to list.

    Returns:
        List of FileInfo objects for each entry.
    """
    ...

read_bytes(path)

Read raw bytes from a file.

Parameters:

Name Type Description Default
path str

File path to read.

required

Returns:

Type Description
bytes

File content as bytes.

Source code in src/pydantic_ai_backends/protocol.py
Python
def read_bytes(self, path: str) -> bytes:
    """Read raw bytes from a file.

    Args:
        path: File path to read.

    Returns:
        File content as bytes.
    """
    ...

read(path, offset=0, limit=2000)

Read file content with line numbers.

Parameters:

Name Type Description Default
path str

File path to read.

required
offset int

Line number to start reading from (0-indexed).

0
limit int

Maximum number of lines to read.

2000

Returns:

Type Description
str

File content as a string with line numbers prefixed.

Source code in src/pydantic_ai_backends/protocol.py
Python
def read(self, path: str, offset: int = 0, limit: int = 2000) -> str:
    """Read file content with line numbers.

    Args:
        path: File path to read.
        offset: Line number to start reading from (0-indexed).
        limit: Maximum number of lines to read.

    Returns:
        File content as a string with line numbers prefixed.
    """
    ...

write(path, content)

Write content to a file.

Parameters:

Name Type Description Default
path str

File path to write to.

required
content str | bytes

Content to write (string or bytes).

required

Returns:

Type Description
WriteResult

WriteResult with path or error.

Source code in src/pydantic_ai_backends/protocol.py
Python
def write(self, path: str, content: str | bytes) -> WriteResult:
    """Write content to a file.

    Args:
        path: File path to write to.
        content: Content to write (string or bytes).

    Returns:
        WriteResult with path or error.
    """
    ...

edit(path, old_string, new_string, replace_all=False)

Edit a file by replacing strings.

Parameters:

Name Type Description Default
path str

File path to edit.

required
old_string str

String to find and replace.

required
new_string str

Replacement string.

required
replace_all bool

If True, replace all occurrences. Otherwise, replace only first.

False

Returns:

Type Description
EditResult

EditResult with path, error, or occurrence count.

Source code in src/pydantic_ai_backends/protocol.py
Python
def edit(
    self, path: str, old_string: str, new_string: str, replace_all: bool = False
) -> EditResult:
    """Edit a file by replacing strings.

    Args:
        path: File path to edit.
        old_string: String to find and replace.
        new_string: Replacement string.
        replace_all: If True, replace all occurrences. Otherwise, replace only first.

    Returns:
        EditResult with path, error, or occurrence count.
    """
    ...

glob_info(pattern, path='/')

Find files matching a glob pattern.

Parameters:

Name Type Description Default
pattern str

Glob pattern (e.g., "**/*.py").

required
path str

Base directory to search from.

'/'

Returns:

Type Description
list[FileInfo]

List of matching FileInfo objects.

Source code in src/pydantic_ai_backends/protocol.py
Python
def glob_info(self, pattern: str, path: str = "/") -> list[FileInfo]:
    """Find files matching a glob pattern.

    Args:
        pattern: Glob pattern (e.g., "**/*.py").
        path: Base directory to search from.

    Returns:
        List of matching FileInfo objects.
    """
    ...

grep_raw(pattern, path=None, glob=None, ignore_hidden=True)

Search for pattern in files.

Parameters:

Name Type Description Default
pattern str

Regex pattern to search for.

required
path str | None

Specific file or directory to search.

None
glob str | None

Glob pattern to filter files.

None
ignore_hidden bool

If True, ignore hidden files.

True

Returns:

Type Description
list[GrepMatch] | str

List of GrepMatch objects or error string.

Source code in src/pydantic_ai_backends/protocol.py
Python
def grep_raw(
    self,
    pattern: str,
    path: str | None = None,
    glob: str | None = None,
    ignore_hidden: bool = True,
) -> list[GrepMatch] | str:
    """Search for pattern in files.

    Args:
        pattern: Regex pattern to search for.
        path: Specific file or directory to search.
        glob: Glob pattern to filter files.
        ignore_hidden: If True, ignore hidden files.

    Returns:
        List of GrepMatch objects or error string.
    """
    ...

SandboxProtocol

Extends BackendProtocol with command execution.

pydantic_ai_backends.protocol.SandboxProtocol

Bases: BackendProtocol, Protocol

Extended protocol for backends that support command execution.

In addition to file operations, sandbox backends can execute shell commands. This is useful for running code, installing packages, or any shell operations.

Example
Python
from pydantic_ai_backends import SandboxProtocol, DockerSandbox

def run_python_script(sandbox: SandboxProtocol, script: str) -> str:
    sandbox.write("/tmp/script.py", script)
    result = sandbox.execute("python /tmp/script.py", timeout=30)
    return result.output
Source code in src/pydantic_ai_backends/protocol.py
Python
@runtime_checkable
class SandboxProtocol(BackendProtocol, Protocol):
    """Extended protocol for backends that support command execution.

    In addition to file operations, sandbox backends can execute shell commands.
    This is useful for running code, installing packages, or any shell operations.

    Example:
        ```python
        from pydantic_ai_backends import SandboxProtocol, DockerSandbox

        def run_python_script(sandbox: SandboxProtocol, script: str) -> str:
            sandbox.write("/tmp/script.py", script)
            result = sandbox.execute("python /tmp/script.py", timeout=30)
            return result.output
        ```
    """

    def execute(self, command: str, timeout: int | None = None) -> ExecuteResponse:
        """Execute a shell command.

        Args:
            command: Command to execute.
            timeout: Maximum execution time in seconds.

        Returns:
            ExecuteResponse with output, exit code, and truncation status.
        """
        ...

    @property
    def id(self) -> str:
        """Unique identifier for this sandbox instance."""
        ...

id property

Unique identifier for this sandbox instance.

execute(command, timeout=None)

Execute a shell command.

Parameters:

Name Type Description Default
command str

Command to execute.

required
timeout int | None

Maximum execution time in seconds.

None

Returns:

Type Description
ExecuteResponse

ExecuteResponse with output, exit code, and truncation status.

Source code in src/pydantic_ai_backends/protocol.py
Python
def execute(self, command: str, timeout: int | None = None) -> ExecuteResponse:
    """Execute a shell command.

    Args:
        command: Command to execute.
        timeout: Maximum execution time in seconds.

    Returns:
        ExecuteResponse with output, exit code, and truncation status.
    """
    ...