# Run code from an LLM Run model code with a time limit and read the output, the error or the timeout. | Template | `base` (2 vCPU, 512 MiB, $0.039 per hour) | |---|---| | Run time | About 11 seconds | | Cost of a run | Less than $0.001 | | Cleanup | The `finally` block kills the sandbox. The 5-minute lifetime ends it if your process stops first. | ## 1. The code `generated` stands in for model code: one snippet works, one reads the system, one raises an error and one never ends. Python (interpreter.py): ```python 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() ``` TypeScript (interpreter.mjs): ```typescript import { Sandbox, CommandExitError, TimeoutError } from '@fdtn/sdk' // Code from a model. Treat it as untrusted. const 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', ] const sbx = await Sandbox.create('base', { timeoutMs: 300_000, // the sandbox lives 5 minutes at most metadata: { example: 'interpreter' }, }) try { for (const [i, code] of generated.entries()) { const path = `/home/user/snippet_${i}.py` await sbx.files.write(path, code) try { const r = await sbx.commands.run(`python3 ${path}`, { timeoutMs: 10_000 }) // 10 s per snippet console.log(`[${i}] ok:`, r.stdout.trim()) } catch (e) { if (e instanceof CommandExitError) console.log(`[${i}] exit ${e.exitCode}:`, e.stderr.trim().split('\n').at(-1)) else if (e instanceof TimeoutError) console.log(`[${i}] stopped after 10 s`) else throw e } } } finally { await sbx.kill() } ``` ## 2. Run it ```bash $ 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](https://fdtn.dev/docs/security.md#network) ## Next - [**Give an agent a code tool**: Put a sandbox behind a model tool.](https://fdtn.dev/docs/examples/agent-tool.md) - [**Run commands**: Timeouts, exit codes and output.](https://fdtn.dev/docs/commands.md) Source: https://fdtn.dev/docs/examples/code-interpreter/