> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandboxed Agent

> Local agent loop with optional tool sandboxing for secure execution

Sandboxed agents keep the agent loop local while optionally running tools in secure sandboxes.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai import SandboxedAgent, SandboxedAgentConfig
from praisonaiagents import Agent

sandboxed = SandboxedAgent(
    config=SandboxedAgentConfig(
        model="gpt-4o",
        system="You are a coding assistant.",
    )
)
agent = Agent(name="coder", backend=sandboxed)
agent.start("Create a Python script that prints hello")
```

The user asks the agent to run code; tool calls execute in E2B or Docker sandboxes instead of on the host.

<Tip>
  Not sure where the loop and the tools run? Run `print(agent.where_does_it_run())` — see [Where Your Agent Runs](/docs/features/where-does-it-run).
</Tip>

<Note>
  E2B/Docker execution now runs through the standalone [praisonai-sandbox](/docs/docs/features/praisonai-sandbox-package) package under the hood — no user-visible change. The `SandboxedAgent`/`SandboxedAgentConfig` API is untouched. As of [PR #4092](https://github.com/MervinPraison/PraisonAI/pull/4092), the vendor compute providers also live in that package (same names, same behaviour; old `praisonai.integrations.compute.*` imports still work through a shim).
</Note>

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Sandboxed Agent Architecture"
        A[👤 User Input] --> B[🧠 Local Agent Loop]
        B --> C{🔧 Tool Execution}
        C -->|Sandboxed| D[📦 E2B/Docker]
        C -->|Local| E[🖥️ Host System]
        D --> F[✅ Result]
        E --> F
    end
    
    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef loop fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef sandbox fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef local fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A input
    class B loop
    class C,D sandbox
    class E local
    class F output
```

## Quick Start

<Steps>
  <Step title="Basic Usage">
    Local loop, local tools - simplest configuration.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import SandboxedAgent, SandboxedAgentConfig
    from praisonaiagents import Agent

    sandboxed = SandboxedAgent(
        config=SandboxedAgentConfig(
            model="gpt-4o",
            system="You are a coding assistant.",
        )
    )

    agent = Agent(name="coder", backend=sandboxed)
    result = agent.start("Create a Python script that prints hello")
    ```
  </Step>

  <Step title="With Tool Sandboxing">
    Local loop, tools run in E2B sandbox for security.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import SandboxedAgent, SandboxedAgentConfig

    sandboxed = SandboxedAgent(
        compute="e2b",  # Tools run in E2B, thinking stays local
        config=SandboxedAgentConfig(
            model="gpt-4o",
            system="You are a coding assistant.",
            tools=["execute_command", "read_file", "write_file"],
            packages={"pip": ["pandas", "numpy"]},
        )
    )

    agent = Agent(name="secure_coder", backend=sandboxed)
    result = agent.start("Analyze CSV data with pandas")
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant AgentLoop
    participant Tools
    participant Sandbox
    
    User->>AgentLoop: "Create Python script"
    AgentLoop->>Tools: Determine tools needed
    alt Tool sandboxing enabled
        Tools->>Sandbox: Execute in E2B/Docker
        Sandbox-->>Tools: Secure result
    else Local execution
        Tools->>Tools: Execute on host
    end
    Tools-->>AgentLoop: Tool output
    AgentLoop-->>User: Generated script
```

| Component          | Location         | Purpose                            |
| ------------------ | ---------------- | ---------------------------------- |
| **Agent Loop**     | Local            | LLM calls, decision making, memory |
| **Tool Execution** | Local or Sandbox | Code execution, file operations    |
| **Memory & State** | Local            | Session persistence, context       |

***

## Configuration Options

<Card title="SandboxedAgentConfig Reference" icon="code" href="/docs/sdk/reference/typescript/classes/SandboxProtocol">
  Full configuration options for sandboxed agents
</Card>

### Essential Configuration

| Option             | Type                   | Default                                                                      | Description                                                                                                                |
| ------------------ | ---------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `model`            | `str`                  | `"gpt-4o"`                                                                   | LLM model to use                                                                                                           |
| `system`           | `str`                  | `"You are a helpful coding assistant."`                                      | System prompt                                                                                                              |
| `tools`            | `List[str]`            | `["execute_command", "read_file", "write_file", "list_files", "search_web"]` | Available tools                                                                                                            |
| `packages`         | `Dict[str, List[str]]` | `None`                                                                       | Package dependencies. PEP 508 specifiers only; pip options such as `--upgrade` or `-r file` are rejected with `ValueError` |
| `networking`       | `Dict[str, Any]`       | `{"type": "unrestricted"}`                                                   | Network access rules                                                                                                       |
| `host_packages_ok` | `bool`                 | `False`                                                                      | Allow host package installation                                                                                            |

***

## Common Patterns

### Secure Development Environment

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Development with package isolation
sandboxed = SandboxedAgent(
    compute="docker",
    config=SandboxedAgentConfig(
        model="claude-sonnet-4-6",
        tools=["execute_command", "read_file", "write_file"],
        packages={
            "pip": ["requests", "beautifulsoup4"],
            "npm": ["express", "lodash"]
        },
        networking={"type": "limited", "allowed_hosts": ["api.github.com"]}
    )
)
```

### Local Development (No Sandbox)

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Fast iteration, local execution
sandboxed = SandboxedAgent(
    config=SandboxedAgentConfig(
        model="gpt-4o-mini",
        host_packages_ok=True,  # Allow host package installs
        tools=["execute_command", "search_web"]
    )
)
```

### Multi-Provider Flexibility

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Use with any LLM provider
sandboxed = SandboxedAgent(
    config=SandboxedAgentConfig(
        model="ollama/llama3.3",  # Local model
        system="You are a Python expert.",
        tools=["execute_command"]
    )
)
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Security Considerations">
    Always use sandboxing when running untrusted code or installing packages:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Secure: Tools run in sandbox
    SandboxedAgent(compute="e2b", config=config)

    # Insecure: Tools run on host
    SandboxedAgent(config=config)  # Only if you trust the code
    ```
  </Accordion>

  <Accordion title="Performance Optimization">
    * Use local execution for trusted environments and faster iteration
    * Use sandbox for production or when handling user-generated code
    * Consider model choice: `gpt-4o-mini` for speed, `claude-sonnet-4-6` for complex tasks
  </Accordion>

  <Accordion title="Backward Compatibility">
    `LocalManagedAgent` and `SandboxedAgent` are the same class:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Both imports work identically
    from praisonai import LocalManagedAgent, LocalManagedConfig
    from praisonai import SandboxedAgent, SandboxedAgentConfig

    # Same functionality
    old_agent = LocalManagedAgent(config=LocalManagedConfig())
    new_agent = SandboxedAgent(config=SandboxedAgentConfig())
    ```
  </Accordion>

  <Accordion title="Tool Sandboxing vs Managed Runtime">
    * **SandboxedAgent**: Agent loop stays local, only tools may be sandboxed
    * **Managed Runtime**: Entire agent loop runs remotely (see [Managed Runtime Protocol](/docs/features/managed-runtime-protocol))
  </Accordion>

  <Accordion title="Package Specifier Validation">
    `packages={"pip": [...]}` accepts [PEP 508](https://peps.python.org/pep-0508/) requirement specifiers only. Pip options with a leading dash are rejected: `--upgrade`, `--pre`, `-r requirements.txt`, `-e ./pkg`. An invalid entry raises:

    ```text theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    ValueError: Invalid pip package specifier: '--upgrade'. Only pip requirement specifiers are allowed.
    ```

    Rewrite options as plain specifiers:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Rejected
    config = SandboxedAgentConfig(packages={"pip": ["--upgrade"]})

    # Accepted
    config = SandboxedAgentConfig(packages={"pip": ["pandas>=2", "numpy"]})
    ```
  </Accordion>

  <Accordion title="Binary write_file and EOF-safe Content">
    `write_file` accepts `bytes` and no longer truncates content that contains an `EOF` line.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import SandboxedAgent, SandboxedAgentConfig
    from praisonaiagents import Agent

    sandboxed = SandboxedAgent(
        compute="e2b",
        config=SandboxedAgentConfig(
            model="gpt-4o",
            tools=["write_file"],
        )
    )
    agent = Agent(name="writer", backend=sandboxed)
    agent.start("Save these bytes to /tmp/out.bin: b'\\x00\\x01\\x02'")
    ```

    Binary bytes round-trip exactly, and a line reading `EOF` inside the content no longer cuts the file short — every byte reaches the target.

    <Note>
      Requires `base64` on the sandbox image's `$PATH` — present on every stock PraisonAI compute image (Docker, E2B, Modal, Daytona, Novita, Fly.io). Bring-your-own minimal images must include it.
    </Note>
  </Accordion>

  <Accordion title="Multi-tenant Credential Isolation">
    Two `SandboxedAgent` instances with different API keys stay isolated in the same process.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import SandboxedAgent, SandboxedAgentConfig

    openai_tenant = SandboxedAgent(
        api_key="sk-openai-tenant",
        config=SandboxedAgentConfig(model="gpt-4o")
    )
    anthropic_tenant = SandboxedAgent(
        api_key="sk-ant-tenant",
        api_base="https://api.anthropic.com",
        config=SandboxedAgentConfig(model="claude-sonnet-4-6")
    )
    ```

    PraisonAI passes `api_key` and `base_url` directly to the inner agent, so credentials never leak into `os.environ` or a spawned subprocess.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Managed Runtime Protocol" icon="cloud" href="/docs/features/managed-runtime-protocol">
    Remote agent runtime for full managed execution
  </Card>

  <Card title="Sandbox" icon="shield-halved" href="/docs/features/sandbox">
    Core SDK sandbox execution on agents
  </Card>
</CardGroup>
