Foundational Compute

Run code from an LLM

Run model code with a time limit and read the output, the error or the timeout.

Templatebase (2 vCPU, 512 MiB, $0.039 per hour)
Run timeAbout 11 seconds
Cost of a runLess than $0.001
CleanupThe finally block kills the sandbox. The 5-minute lifetime ends it if your process stops first.

1The code

generated stands in for model code: one snippet works, one reads the system, one raises an error and one never ends.

Python · TypeScript

interpreter.py
from fdtn import Sandbox, CommandExitException, TimeoutException

# Code from a model. Treat it as untrusted.
generated = [
    "import math\nprint(sum(math.factorial(n) for n in range(10)))",
    "import os\nprint(open('/etc/hostname').read().strip(), os.getuid())",
    "raise ValueError('bad input')",
    "while True:\n    pass",
]

sbx = Sandbox.create(
    "base",
    timeout=300,                       # the sandbox lives 5 minutes at most
    metadata={"example": "interpreter"},
)
try:
    for i, code in enumerate(generated):
        path = f"/home/user/snippet_{i}.py"
        sbx.files.write(path, code)
        try:
            r = sbx.commands.run(f"python3 {path}", timeout=10)   # 10 s per snippet
            print(f"[{i}] ok:", r.stdout.strip())
        except CommandExitException as e:
            print(f"[{i}] exit {e.exit_code}:", e.stderr.strip().splitlines()[-1])
        except TimeoutException:
            print(f"[{i}] stopped after 10 s")
finally:
    sbx.kill()

2Run it

$ python interpreter.py      # or: node interpreter.mjs
[0] ok: 409114
[1] ok: fdtn 1000
[2] exit 1: ValueError: bad input
[3] stopped after 10 s

Notes

  • A timeout stops the process in the sandbox and raises a timeout error.
  • A non-zero exit raises CommandExitException (Python) or CommandExitError (TypeScript) with the exit code, stdout and stderr. Give the last stderr line back to the model.
  • Code runs as user (uid 1000), not root. Snippets share one sandbox and its files. For full isolation, use one sandbox per snippet.
  • The sandbox has outbound internet but no private networks. Network rules

Next