Skip to content
Blog

Sandboxed Agents: Safe Code Execution with Container Workspaces

Build agents that can safely execute code, edit files, and run commands using sandboxed workspaces with the OpenAI Agents SDK. Learn to configure Docker and Unix-local sandboxes with filesystem and shell capabilities.

Published on September 6, 2026

AI Assistant

Modern agents work best when they can operate on real files in a filesystem. But giving an LLM direct access to your host system is a security risk. Sandbox Agents in the OpenAI Agents SDK solve this by giving the model a persistent, isolated workspace where it can search large document sets, edit files, run commands, generate artifacts, and pick work back up from saved sandbox state.

The SDK provides the execution harness without requiring you to wire together file staging, filesystem tools, shell access, sandbox lifecycle, snapshots, and provider-specific glue yourself.

In this tutorial, you will learn how to create a sandboxed agent with filesystem and shell capabilities, configure workspace mounts, and manage sandbox sessions.

Prerequisites

  • Python 3.10 or higher
  • Basic familiarity with the OpenAI Agents SDK
  • A sandbox client (start with UnixLocalSandboxClient for local development)
pip install openai-agents

# For Docker-backed sandboxes
pip install "openai-agents[docker]"

Creating a Local Sandbox Agent

The simplest sandbox agent uses a Unix-local sandbox client, which creates an isolated workspace on your machine:

import asyncio
from pathlib import Path

from agents import Runner
from agents.run import RunConfig
from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig
from agents.sandbox.capabilities import Capabilities, LocalDirLazySkillSource, Skills
from agents.sandbox.entries import LocalDir
from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient

EXAMPLE_DIR = Path(__file__).resolve().parent
HOST_REPO_DIR = EXAMPLE_DIR / "repo"
HOST_SKILLS_DIR = EXAMPLE_DIR / "skills"

def build_agent(model: str) -> SandboxAgent[None]:
    return SandboxAgent(
        name="Sandbox engineer",
        model=model,
        instructions=(
            "Read `repo/task.md` before editing files. Stay grounded in the repository, preserve "
            "existing behavior, and mention the exact verification command you ran. "
            "If you edit files with apply_patch, paths are relative to the sandbox workspace root."
        ),
        default_manifest=Manifest(
            entries={
                "repo": LocalDir(src=HOST_REPO_DIR),
            }
        ),
        capabilities=Capabilities.default() + [
            Skills(
                lazy_from=LocalDirLazySkillSource(
                    source=LocalDir(src=HOST_SKILLS_DIR),
                )
            ),
        ],
    )

async def main() -> None:
    result = await Runner.run(
        build_agent("gpt-5.6-sol"),
        "Open `repo/task.md`, fix the issue, run the targeted test, and summarize the change.",
        run_config=RunConfig(
            sandbox=SandboxRunConfig(client=UnixLocalSandboxClient()),
            workflow_name="Sandbox coding example",
        ),
    )
    print(result.final_output)

if __name__ == "__main__":
    asyncio.run(main())

Understanding the Components

Manifest

The Manifest defines what files and directories are available in the sandbox:

from agents.sandbox import Manifest
from agents.sandbox.entries import LocalDir, LocalFile

manifest = Manifest(
    entries={
        "repo": LocalDir(src=Path("/path/to/repo")),      # Mount a directory
        "config.yaml": LocalFile(src=Path("/path/to/config.yaml")),  # Mount a file
    }
)

Capabilities

Capabilities define what the agent can do inside the sandbox:

from agents.sandbox.capabilities import Capabilities, Skills, Memory

capabilities = Capabilities.default()  # Includes filesystem + shell

The default capabilities include:

CapabilityDescription
FilesystemRead, write, and search files in the workspace
ShellExecute commands in the sandbox environment
SkillsLoad and execute agent skills
MemoryPersist state across sandbox sessions

SandboxRunConfig

The run configuration specifies the sandbox backend:

from agents.sandbox import SandboxRunConfig
from agents.sandbox.sandboxes.unix_local import UnixLocalSandboxClient
from agents.sandbox.sandboxes.docker import DockerSandboxClient

# Local Unix sandbox (for development)
config = SandboxRunConfig(client=UnixLocalSandboxClient())

# Docker sandbox (for production isolation)
config = SandboxRunConfig(client=DockerSandboxClient())

Docker Sandboxes

For production workloads, use Docker-backed sandboxes for stronger isolation:

from agents.sandbox.sandboxes.docker import DockerSandboxClient

client = DockerSandboxClient(
    image="python:3.11-slim",  # Base Docker image
    # network_mode="none",     # Optional: disable network access
)

result = await Runner.run(
    build_agent("gpt-5.6-sol"),
    "Analyze the codebase and generate a report.",
    run_config=RunConfig(
        sandbox=SandboxRunConfig(client=client),
    ),
)

Workspace Snapshots

Snapshots allow agents to save and restore workspace state across sessions:

from agents.sandbox import SnapshotSpec

# Save workspace state after a run
snapshot = SnapshotSpec(
    name="after-analysis",
    description="State after code analysis",
)

# Restore from a snapshot in a new run
config = SandboxRunConfig(
    client=UnixLocalSandboxClient(),
    snapshot=snapshot,
)

Agent Memory in Sandboxes

Sandbox agents can persist lessons learned across runs using the memory capability:

from agents.sandbox.capabilities import Memory

agent = SandboxAgent(
    name="Learning Agent",
    model="gpt-5.6-sol",
    instructions="Remember patterns from previous runs.",
    capabilities=Capabilities.default() + [Memory()],
)

The agent can save key findings to memory and recall them in future sessions, building context over time without starting from scratch.

Key Choices

When building sandbox agents, the decisions most teams reach for next are:

  • default_manifest: The files, repos, directories, and mounts for fresh sandbox sessions
  • instructions: Short workflow rules that apply across prompts
  • base_instructions: Advanced escape hatch for replacing the SDK sandbox prompt
  • capabilities: Sandbox-native tools such as filesystem editing, image inspection, shell, skills, memory, and compaction
  • run_as: The sandbox user account under which model-facing tools execute
  • SandboxRunConfig.client: The sandbox backend (UnixLocal, Docker, hosted)
  • SandboxRunConfig.session / session_state / snapshot: How later runs reconnect to prior work

When to Use Sandbox Agents

Use sandbox agents when:

  • Your agent needs to read and modify real files
  • You need workspace isolation for security
  • Sessions need to resume from saved state
  • The agent needs shell access for running commands
  • Multiple agents share or partition workspaces

Stick with regular agents and the tools guide when:

  • Shell access is occasional, not core to the workflow
  • You’re building simple tool-calling agents
  • Filesystem operations aren’t required

Next Steps

  • Read Sandbox Concepts to understand manifests, capabilities, permissions, and composition patterns
  • Explore Sandbox Clients for choosing Unix-local, Docker, or hosted providers
  • Learn about Agent Memory for preserving and reusing lessons from previous sandbox runs

Sandbox agents bring the power of real file operations to your AI agents while maintaining the security boundaries your production systems require.