Skip to content

Your first task

The quickstart drove a sandbox step by step. In this tutorial, the same kind of work becomes a task: a function under a decorator, which FastSandbox runs in a fresh sandbox at each call, with its input validated before the sandbox exists and its result validated after. You then run it from the command line and from Python.

What you need

The project of the quickstart, or any project with fastsandbox installed and Docker Sandboxes running. No AI account and no API key.

1. Write the task

Create count_words.py in the project:

count_words.py
import shlex

from pydantic import BaseModel

import fastsandbox
from fastsandbox import Context, FastSandbox

app = FastSandbox("tutorial")


class WordCount(BaseModel):
    text: str
    words: int


@app.task(kit="shell", timeout="5m")
async def count_words(ctx: Context, text: str) -> WordCount:
    """Counts the words of a text with `wc`, run in the sandbox."""
    command = f"printf '%s\\n' {shlex.quote(text)} | wc -w"
    output = await ctx.sandbox.exec(command, check=True)
    return WordCount(text=text, words=int(output.stdout))


if __name__ == "__main__":
    print(fastsandbox.run(count_words, text="one two three"))
  • Line 8: FastSandbox("tutorial") creates the application that holds the tasks. Its name starts the names of their sandboxes: a run of count_words creates tutorial-count-words- followed by a random suffix.
  • Lines 11 to 13: the result is a Pydantic model, validated when the task returns.
  • Line 16: @app.task declares the task and its sandbox: the shell kit, and a deadline of five minutes for the call of the function.
  • Line 17: the parameters drive the rest. ctx: Context is injected by its annotation, the Context of the run, whose ctx.sandbox is the sandbox; text: str is an input, validated before the sandbox is created.
  • Lines 19 and 20: the command runs in the sandbox. The text is quoted with shlex.quote, so that it reaches printf as a single argument whatever it holds; check=True raises CommandFailedError on a non-zero exit code.
  • Line 18: the docstring describes the task on the command line.

Where the code runs

The function runs on the host, in your process, with your user's rights: it is not isolated. Only the command it passes to ctx.sandbox.exec(...) runs in the sandbox. Keep host-side code to orchestration, and send anything you do not trust into the sandbox.

2. Run it from the command line

fastsandbox tasks lists the tasks of a file and their inputs, without creating a sandbox:

$ uv run fastsandbox tasks count_words.py
count_words  (task, kit shell)
    Counts the words of a text with `wc`, run in the sandbox.
    --text  str, required

fastsandbox run runs one, its inputs given as options, and prints the result as JSON:

$ uv run fastsandbox run count_words.py count_words --text "one two three"
{
  "text": "one two three",
  "words": 3
}

3. Run it from Python

The script ends with fastsandbox.run(...), which runs a task from synchronous code:

$ uv run python count_words.py
text='one two three' words=3

In async code, the same run is await app.run("count_words", text="..."). Running tasks covers every way, several runs at once included.

What a run does

shape: sequence_diagram
P: Your program (host)
F: FastSandbox (host)
D: sandboxd
S: Sandbox
P -> F: 'count_words(text="one two three")'
F -> F: validate the input
F -> D: "create the sandbox from the shell kit,\nhold a session"
F -> F: "call the function,\nunder the timeout"
F -> S: "printf ... | wc -w"
S -> F: "3" {style.stroke-dash: 3}
F -> D: remove the sandbox
F -> F: validate the result
F -> P: "WordCount(text=..., words=3)" {style.stroke-dash: 3}

The run removes its sandbox when the function returns, raises, times out or is cancelled. A sandbox is left behind when the process is killed, or when the removal fails: a run that ended well then logs a warning on the logger of the task and keeps its result, and a failed run notes the failure on its error. The lifecycle page details each case, and What a run does every step.

A task on a project

The same steps run the tests of a project of yours, on a copy of it:

run_tests.py
from pathlib import Path
from typing import Annotated

from pydantic import BaseModel

from fastsandbox import Context, FastSandbox, Network, Uploaded

app = FastSandbox("ci")


class Report(BaseModel):
    passed: bool
    summary: str


@app.task(kit="shell", network=Network.allow("pypi.org"), timeout="10m")
async def run_tests(
    ctx: Context, repo: Annotated[Path, Uploaded("/work")], command: str = "make test"
) -> Report:
    """Runs the tests of a project in a copy of it."""
    output = await ctx.sandbox.exec(f"cd /work && {command}")
    return Report(passed=output.ok, summary=(output.stdout + output.stderr)[-500:])
  • Line 16: network=Network.allow("pypi.org") adds pypi.org to what the global policy of the daemon allows; it confines the sandbox only where that policy denies the rest (see the network model). The deadline is ten minutes.
  • Line 18: Annotated[Path, Uploaded("/work")] copies the contents of the directory into /work once the sandbox runs: the tests run on a copy, and nothing comes back to the host. command is an input with a default.
uv run fastsandbox run run_tests.py run_tests --repo . --command "make test"

If it fails

Symptom Cause
fastsandbox: invalid inputs of task count_words: --text: Field required An input is missing or of the wrong type: the message names its option. Nothing was created, and the command exits with status 2.
CommandFailedError The command exited with a non-zero code; exit_code, stdout and stderr say why.
SandboxTimeoutError The function ran past its timeout.

Next

  • Your first coding agent: a task whose sandbox runs a coding agent.
  • FastSandbox: tasks, inputs and outputs, host directories, network rules and dependencies, one page each.
  • Testing: this task tested against the fake daemon, without Docker Sandboxes.