← Blog

CrewAI agents that run code in a Sandscale sandbox, over the REST API

Give a CrewAI crew BaseTool subclasses that run commands and write files in a Firecracker sandbox through Sandscale's REST API with requests. A developer and a reviewer share one box per crew run, cleaned up in finally. Checked against crewai 1.15.

CrewAI organizes agents into crews with roles and tasks. A common crew for code is a developer who writes a module and a reviewer who tries to break it. Both need to run code, and the reviewer needs to run the developer’s code, which is exactly the code you should not run on the machine hosting the crew. This guide gives both agents tools backed by one Sandscale sandbox per crew run.

CrewAI is a Python framework, so this guide calls the Sandscale sandbox REST API with requests. The tool classes were imported and instantiated against crewai 1.15 and pydantic 2 to check that CrewAI accepts them; the requests match the endpoints in the guide.

Install

pip install crewai requests
export SANDSCALE_API_KEY=...   # a key that can create, use and stop sandboxes
export OPENAI_API_KEY=...      # or whichever model provider your crew uses

A small REST client

Five calls cover a sandbox’s life: create, run, write a file, and stop. Files travel as base64 in JSON. The HTTP timeout on run is longer than the command’s own timeout_sec, because the exec request answers only when the command finishes. Calling the sandbox REST API from Python explains each choice in more depth.

# sandbox_rest.py
import base64
import os

import requests

API = "https://api.sandscale.dev/api/v1/sandbox"


class SandboxAPIError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status = status
        self.code = code


class Sandboxes:
    def __init__(self, api_key=None):
        self.http = requests.Session()
        self.http.headers["Authorization"] = f"Bearer {api_key or os.environ['SANDSCALE_API_KEY']}"

    def _call(self, method, path, timeout=30, **kwargs):
        r = self.http.request(method, f"{API}{path}", timeout=timeout, **kwargs)
        if r.ok:
            return r.json() if r.content else None
        try:
            body = r.json()
        except ValueError:
            body = {}
        err = body.get("error") if isinstance(body.get("error"), dict) else body
        raise SandboxAPIError(r.status_code, err.get("code") or f"http_{r.status_code}", err.get("message") or r.reason)

    def create(self, template="builtin:python", ttl_seconds=1800, **fields):
        return self._call("POST", "/instances", json={"template_id": template, "ttl_seconds": ttl_seconds, **fields})

    def run(self, sandbox_id, command, timeout_sec=60, **fields):
        body = {"command": command, "timeout_sec": timeout_sec, **fields}
        return self._call("POST", f"/instances/{sandbox_id}/exec", json=body, timeout=timeout_sec + 30)

    def write_file(self, sandbox_id, path, data):
        if isinstance(data, str):
            data = data.encode()
        body = {"path": path, "content": base64.b64encode(data).decode()}
        self._call("PUT", f"/instances/{sandbox_id}/files", json=body)

    def stop(self, sandbox_id):
        try:
            self._call("DELETE", f"/instances/{sandbox_id}")
        except SandboxAPIError as e:
            if e.code != "sandbox_not_found":
                raise

The tools

CrewAI tools subclass BaseTool with a name, a description, a Pydantic args_schema, and a _run method. The sandbox id is a private attribute set in the constructor, not a tool argument, so an agent cannot point the tool at a different box.

# crew_tools.py
import json
from typing import Type

from crewai.tools import BaseTool
from pydantic import BaseModel, Field, PrivateAttr

from sandbox_rest import Sandboxes


def clip(s: str, n: int = 8000) -> str:
    return s if len(s) <= n else s[:n] + f"\n[cut {len(s) - n} chars]"


class RunCommandInput(BaseModel):
    command: str = Field(..., max_length=4000, description="A bash command to run in /workspace.")
    timeout_seconds: int = Field(60, ge=1, le=300, description="How long the command may run.")


class SandboxRunCommand(BaseTool):
    name: str = "run_command"
    description: str = (
        "Run a bash command in an isolated Linux sandbox, in /workspace. Files persist for this crew run. "
        "Returns JSON with exit_code, timed_out, oom_killed, stdout and stderr; output over 8,000 characters is cut."
    )
    args_schema: Type[BaseModel] = RunCommandInput
    _api: Sandboxes = PrivateAttr()
    _sandbox_id: str = PrivateAttr()

    def __init__(self, api: Sandboxes, sandbox_id: str, **kwargs):
        super().__init__(**kwargs)
        self._api = api
        self._sandbox_id = sandbox_id

    def _run(self, command: str, timeout_seconds: int = 60) -> str:
        r = self._api.run(self._sandbox_id, ["bash", "-lc", command], timeout_sec=timeout_seconds, workdir="/workspace")
        return json.dumps({
            "exit_code": r.get("exit_code"),
            "timed_out": r.get("timed_out", False),
            "oom_killed": r.get("oom_killed", False),
            "stdout": clip(r.get("stdout", "")),
            "stderr": clip(r.get("stderr", "")),
        })


class WriteFileInput(BaseModel):
    path: str = Field(..., description="Absolute path under /workspace/.")
    content: str = Field(..., max_length=200000)


class SandboxWriteFile(BaseTool):
    name: str = "write_file"
    description: str = "Write a text file in the sandbox. The path must be under /workspace/."
    args_schema: Type[BaseModel] = WriteFileInput
    _api: Sandboxes = PrivateAttr()
    _sandbox_id: str = PrivateAttr()

    def __init__(self, api: Sandboxes, sandbox_id: str, **kwargs):
        super().__init__(**kwargs)
        self._api = api
        self._sandbox_id = sandbox_id

    def _run(self, path: str, content: str) -> str:
        if not path.startswith("/workspace/"):
            return "error: path must be under /workspace/"
        self._api.write_file(self._sandbox_id, path, content)
        return f"wrote {len(content)} characters to {path}"

The crew

# crew_main.py
from crewai import Agent, Crew, Process, Task

from crew_tools import SandboxRunCommand, SandboxWriteFile
from sandbox_rest import Sandboxes


def build_and_review(spec: str) -> str:
    api = Sandboxes()
    box = api.create(template="builtin:python", ttl_seconds=1800, name="crewai-run", labels={"app": "crewai"})
    try:
        tools = [SandboxRunCommand(api, box["id"]), SandboxWriteFile(api, box["id"])]

        developer = Agent(
            role="Python developer",
            goal="Write a small, correct Python module and its unit tests",
            backstory="You write the code and tests in /workspace and run the tests before you finish.",
            tools=tools,
        )
        reviewer = Agent(
            role="Code reviewer",
            goal="Find bugs in the developer's module by running it, not just reading it",
            backstory="You add edge-case tests in /workspace/test_edge.py and run the whole suite.",
            tools=tools,
        )

        write = Task(
            description=f"Implement this in /workspace/solution.py with tests in /workspace/test_solution.py: {spec}",
            expected_output="The final test command and its result.",
            agent=developer,
        )
        review = Task(
            description="Review /workspace/solution.py. Add edge-case tests, run python3 -m unittest, and fix what fails.",
            expected_output="A short review: what you tested, what failed, what you changed, and the final test result.",
            agent=reviewer,
        )

        crew = Crew(agents=[developer, reviewer], tasks=[write, review], process=Process.sequential)
        return str(crew.kickoff())
    finally:
        api.stop(box["id"])


if __name__ == "__main__":
    print(build_and_review("a function that parses ISO 8601 durations like P1DT2H into seconds"))

Why it is built this way

One sandbox per crew run, shared by both agents. The reviewer has to run the developer’s code, so they need the same files. Each build_and_review call gets a fresh box, so two crews running at once never see each other’s work. Each sandbox is its own Firecracker microVM with its own kernel and disk.

Results as JSON with the reasons. run_command returns exit_code, timed_out and oom_killed next to the output. The exec response includes those flags, and passing them on lets an agent tell “the tests failed” from “the tests hung” from “the process ran out of memory”, which call for different fixes.

Narrow, validated inputs. The Pydantic schemas cap command length and timeout, and write_file refuses paths outside /workspace/. CrewAI uses args_schema to tell the model what each tool takes.

A lifetime even if Python dies. ttl_seconds=1800 on create means the sandbox stops by itself after 30 minutes, even if your process crashes before finally. Within normal runs, finally stops it as soon as the crew finishes, which deletes its disk.

Stop is idempotent. If the sandbox already stopped because its ttl_seconds ran out, stop treats sandbox_not_found as done.

Network

The tool descriptions do not promise internet access, and the agents should not need it for a self-contained module. Network access for a sandbox follows your plan and your organization’s policy. If your crew needs packages from an index, use your organization’s egress allowlist where your plan includes it, or build a template with the packages already in the image. Designing an egress allowlist covers what to allow.

Production notes

  • Retry reads, not writes. Retry 429 and 503 on GET with backoff. Do not blindly retry POST /instances or exec: a timeout does not tell you whether the server started the sandbox or ran the command.
  • Errors carry a code. The client raises SandboxAPIError with the HTTP status and a machine-readable code such as quota_exceeded or policy_denied. Branch on the code.
  • Secrets. If a task needs a token, pass vault_env on create so the value comes from Vault into that sandbox’s environment only, instead of putting it in a task description.
  • Every run is recorded. The exec response has a run_id, and GET /api/v1/sandbox/runs/{id} returns the run’s details, which is useful when a crew’s final answer does not match what happened.

Cost

A crew run uses awake vCPU-hours while its sandbox runs: 100 a month on the Free plan, 1,500 on Pro and 2,000 per member pooled on Team. See plans and limits.

Run your agents in a box of their own

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

Start free

Keep reading