Skip to content

Python SDK reference

This page gives each public class, function and exception of the Python SDK of boxfork. The page is for a person who writes a Python program that uses sandboxes.

The SDK is a client of the HTTP API of the daemon. It uses only the standard library of Python. All calls are synchronous. The SDK has no async interface.

Source:

The repository also has a TypeScript SDK in sdk/typescript. This page does not describe it. It does not have the pool calls. Issue #55 brings it level.

The SDK needs Python 3.9 or later. It has no dependencies. Install it from the root directory of the repository:

Terminal window
pip install ./sdk/python

The package name is boxfork. The version is 0.1.0, also available as boxfork.__version__.

from boxfork import Sandbox
with Sandbox.create("python:3.12") as sbx:
sbx.files.write("/work/hello.py", "print('hello')")
print(sbx.run("python3 /work/hello.py").stdout)

from boxfork import ... gives these names:

Name Type Function
Sandbox class Create and control a sandbox.
SandboxInfo data class The properties of a sandbox.
CommandResult data class The result of a command.
Entry data class A file or a directory in a sandbox.
Snapshot data class A snapshot.
Volume data class A volume.
Mount data class A volume at a path in a sandbox.
Pool data class A pool.
GPU data class A GPU of the host.
gpus function List the GPUs of the host.
host_info function Describe the daemon.
Toolkit class Give the sandbox tools to a model.
ToolResult data class The result of a tool call.
BoxforkError and five more exceptions See Exceptions.

All data classes are frozen: you cannot change their fields.

Each function that calls the daemon accepts the keyword arguments url and api_key. The objects that these functions return keep the connection, thus their methods do not need the arguments again.

Argument Type Default
url Optional[str] The BOXFORK_URL variable, then http://127.0.0.1:7070.
api_key Optional[str] The BOXFORK_API_KEY variable, then the key file of a local daemon.

Rules:

  • An address without http:// or https:// gets http://.
  • The SDK reads the key file only when the host in the address is localhost, 127.0.0.1 or ::1.
  • The key file is api-key in the data directory of the daemon.
  • The data directory is BOXFORK_DATA_DIR. Without that variable, it is /var/lib/boxfork for the root user and ~/.boxfork for other users.
  • If the SDK finds no key, it raises BoxforkError.
  • If the address is wrong, the SDK raises BoxforkError.
  • The SDK does not set a time limit on a request. The daemon controls the time limits of sandboxes and commands.
  • The SDK does not follow a redirect. It raises APIError with the code http_error.
  • For a local daemon, the SDK ignores a proxy that the environment names.
  • The SDK does not read the BOXFORK_PIN_CERT variable.
from boxfork import Sandbox
sbx = Sandbox.create(url="https://sandbox.example.com:7070", api_key="abx_...")

A Sandbox object controls one sandbox.

Attribute Type Meaning
id str The identifier of the sandbox.
commands Commands Runs commands. See Commands.
files Files Reads and writes files. See Files.
info SandboxInfo A property. Each read asks the daemon for the current state.
gpus List[GPU] A property. The GPUs from the last state that the object got. It does not ask the daemon.

A Sandbox is a context manager. At the end of a with block, it kills the sandbox.

Sandbox.create(image=None, *, snapshot=None, gpu=0, cpus=None, memory_mb=None,
timeout=None, env=None, metadata=None, network=True,
suspend_after=None, volumes=None, url=None, api_key=None) -> Sandbox

This class method creates a sandbox and returns when the sandbox runs.

Parameter Type Default Meaning
image Optional[str] The default image of the daemon The image to start from.
snapshot str, Snapshot or None None A snapshot, or its identifier, to start from. Do not give image with it.
gpu int 0 The number of full GPUs to attach.
cpus Optional[float] The default of the daemon CPU cores.
memory_mb Optional[int] The default of the daemon Memory in MiB.
timeout Optional[float] The default timeout of the daemon The life of the sandbox in seconds. 0 means that the sandbox never ends.
env Optional[Mapping[str, str]] None Environment variables for the sandbox.
metadata Optional[Mapping[str, str]] None Labels that the daemon stores and returns.
network bool True False gives a sandbox without networking.
suspend_after Optional[float] The default of the daemon The idle time in seconds before the daemon suspends the sandbox. 0 means never. A value other than 0 must be 10 or more.
volumes Mount, str, or an iterable of them None The volumes to mount. A string has the form "name:/path" or "name:/path:ro". Each volume must exist.

Exceptions:

Exception Cause
GPUUnavailable The host cannot give the GPUs.
NotFound The snapshot or a volume does not exist.
APIError The daemon refused the request. code is, for example, invalid_request, limit_reached or unsupported.
ValueError A string in volumes does not have the correct form.
TypeError An item of volumes is not a Mount or a string.
from boxfork import Sandbox
sbx = Sandbox.create("python:3.12", timeout=600, env={"STAGE": "test"},
metadata={"job": "tests"}, network=False)
print(sbx.id)
sbx.kill()

A suspended sandbox has the state "suspended". The next command or file operation wakes it. The sandbox then has its files. It does not have the processes that ran before.

Sandbox.connect(sandbox_id, *, url=None, api_key=None) -> Sandbox

This class method returns a Sandbox object for a sandbox that exists. It raises NotFound if the sandbox does not exist.

sbx = Sandbox.connect("sbx_k3v7q2mzj5xw4n6a")
Sandbox.list(*, url=None, api_key=None) -> List[SandboxInfo]

This class method lists the sandboxes of the host, the oldest first. It returns SandboxInfo objects. Use Sandbox.connect to control one of them.

for info in Sandbox.list():
print(info.id, info.image, info.state)
Method Returns Meaning
run(cmd, **options) CommandResult Run a command. The same as commands.run.
snapshot(*, metadata=None) Snapshot Save the files of the sandbox. The snapshot does not contain the processes.
fork(count=1, *, gpu=None, timeout=None, metadata=None) List[Sandbox] Make new sandboxes with the same files.
pause() None Pause the sandbox. The timeout clock stops.
resume() None Resume a paused sandbox.
set_timeout(seconds) None Make the sandbox end this number of seconds from now. 0 means never.
kill() bool Kill the sandbox. False if the sandbox was gone before the call.

The parameters of fork:

Parameter Type Default Meaning
count int 1 The number of forks, from 1 to 64.
gpu Optional[int] The number of GPUs of this sandbox The GPUs of each fork. 0 gives forks without a GPU.
timeout Optional[float] The default timeout of the daemon The life of each fork in seconds.
metadata Optional[Mapping[str, str]] The metadata of this sandbox Metadata for the forks.

A fork is all or nothing. If the daemon cannot create one fork, it creates none and the method raises an exception. A fork has the files of the sandbox. It has none of its processes.

with Sandbox.create("python:3.12") as sbx:
sbx.run("pip install -q numpy", check=True)
snapshot = sbx.snapshot(metadata={"step": "deps"})
copies = sbx.fork(3)
for copy in copies:
print(copy.id)
copy.kill()
sbx.pause()
sbx.resume()
sbx.set_timeout(1800)
later = Sandbox.create(snapshot=snapshot)
later.kill()

sbx.commands is a Commands object. It has one method.

sbx.commands.run(cmd, *, cwd=None, env=None, timeout=None, stdin=None,
on_stdout=None, on_stderr=None, check=False) -> CommandResult

This method runs one command and waits until it ends. sbx.run(...) is the same call.

Parameter Type Default Meaning
cmd str or a sequence of str necessary A string is a command line for the shell of the sandbox. A list is a program with its arguments, which the sandbox runs directly.
cwd Optional[str] The default of the sandbox The directory in which the command runs.
env Optional[Mapping[str, str]] None Environment variables for this command.
timeout Optional[float] No time limit The daemon kills the command after this number of seconds.
stdin str, bytes or None None The input of the command.
on_stdout Optional[Callable[[str], None]] None A function that gets the standard output as text while the command runs.
on_stderr Optional[Callable[[str], None]] None A function that gets the standard error output as text while the command runs.
check bool False True raises CommandError if the command fails.

Rules:

  • Each call is a new process. A cd in one call has no effect on the next call. Use cwd.
  • Without on_stdout and on_stderr, the daemon keeps the first 4 MiB of each output.
  • With on_stdout or on_stderr, the daemon streams the output. The functions get all of it.
  • With a stream, the result also keeps only the first 4 MiB of each output.
  • If an output is longer than 4 MiB, truncated is True in the result.
  • The SDK decodes the output as UTF-8. It replaces bytes that are not valid.

Exceptions:

Exception Cause
CommandError check is True, and the command ended with an exit code other than 0, a signal or a time limit.
BoxforkError The sandbox cannot start the command, or the stream ended before the command did.
NotFound The sandbox does not exist.
APIError The daemon refused the request. For a paused sandbox, code is sandbox_paused.
result = sbx.run("ls /etc | wc -l")
print(result.stdout, result.exit_code)
sbx.run(["python3", "-c", "import sys; print(sys.version)"], check=True)
sbx.run("pip install numpy", on_stdout=print, timeout=300)
sbx.run("wc -c", stdin=b"\x00\x01\x02")
sbx.run("make test", cwd="/work", env={"STAGE": "test"})
Field Type Meaning
stdout str The standard output.
stderr str The standard error output.
exit_code int The exit code. For a command that a signal ended, 128 plus the number of the signal.
signal str The signal that ended the command, for example "SIGKILL". "" for none.
timed_out bool True if the time limit ended the command.
truncated bool True if an output was longer than the limit.
ok bool A property. True if exit_code is 0, with no signal and no time limit.

sbx.files is a Files object. All paths in the sandbox are absolute paths.

Method Returns Meaning
read(path) str Read a text file as UTF-8.
read_bytes(path) bytes Read a file as bytes.
write(path, data, *, executable=False, mode=None) int Create or replace a file. Returns its size in bytes.
upload(local_path, path) int Copy a file of your machine into the sandbox. Returns its size.
download(path, local_path) int Copy a file out of the sandbox. Returns its size.
list(path) List[Entry] List the entries of one directory.
stat(path) Entry Describe one path.
exists(path) bool Tell if the path exists.
remove(path) None Remove a file, or a directory and all its contents.
make_dir(path) None Make a directory and the directories above it.
rename(old_path, new_path) None Move a file or a directory.

Notes:

  • write accepts str or bytes. It creates the directories of the path if they do not exist.
  • mode is an integer of permission bits, for example 0o644. executable=True gives 0o755 when mode is None.
  • Without mode and executable, a new file gets 0644 and a file that exists keeps its mode.
  • upload gives the file in the sandbox the permission bits of the local file.
  • download gives the local file the permission bits of the file in the sandbox, less your umask.
  • download writes a temporary file in the same directory and then renames it. If it fails, it leaves nothing at local_path.
  • read_bytes and download raise BoxforkError if the download stops before the end.
  • read raises UnicodeDecodeError if the file is not valid UTF-8.
  • exists returns False only for the error code not_found. If the sandbox does not exist, it raises NotFound.
  • A path that does not exist raises NotFound with the code not_found.
  • Other file errors raise APIError. code is permission_denied, is_directory, not_directory, invalid_argument or io_error.
sbx.files.write("/work/run.sh", "#!/bin/sh\necho ok\n", executable=True)
print(sbx.files.read("/work/run.sh"))
sbx.files.upload("./data.csv", "/work/data.csv")
sbx.files.download("/work/result.json", "./result.json")
sbx.files.make_dir("/work/out")
sbx.files.rename("/work/run.sh", "/work/out/run.sh")
for entry in sbx.files.list("/work"):
print(entry.name, entry.type, entry.size, entry.mode)
if sbx.files.exists("/work/out/run.sh"):
sbx.files.remove("/work/out")
Field Type Meaning
name str The last part of the path.
path str The absolute path.
type str "file", "dir", "symlink" or "other".
size int The size in bytes.
mode str The permission bits as octal text, for example "0644".
modified_at Optional[datetime] The time of the last change.

Sandbox.list() and the info property return this data class.

Field Type Meaning
id str The identifier of the sandbox.
image str The image.
state str "running", "paused" or "suspended".
isolation str "gvisor" or "container".
cpus float The CPU limit, in cores.
memory_mb int The memory limit, in MiB.
gpus List[GPU] The GPUs of the sandbox.
network bool True if the sandbox has networking.
metadata Dict[str, str] The metadata.
created_at Optional[datetime] The time of creation.
expires_at Optional[datetime] The time when the daemon kills the sandbox. None for a sandbox without a timeout and for a paused sandbox.
snapshot str The snapshot from which the sandbox came. "" for none.
gpu_verified bool True if the sandbox reported exactly its own GPUs.
suspend_after int The idle time in seconds before a suspension. 0 means never.
unsaved_paths Tuple[str, ...] The directories that the image keeps in its own volumes. A snapshot does not contain them.
volumes Tuple[Mount, ...] The mounted volumes: those of the request and the default volumes of the daemon.
Field Type Meaning
id str The identifier of the snapshot.
sandbox_id str The sandbox that the snapshot came from.
image str The image of that sandbox.
metadata Dict[str, str] The metadata.
created_at Optional[datetime] The time of creation.
excluded_paths Tuple[str, ...] The directories of the sandbox that the snapshot does not contain.
Method Returns Meaning
Snapshot.list(*, url=None, api_key=None) List[Snapshot] A class method. List the snapshots, the oldest first.
delete() None Delete the snapshot.

sbx.snapshot() creates a snapshot. Sandbox.create(snapshot=...) creates a sandbox from it. delete() raises APIError with the code in_use while a sandbox or a pool uses the snapshot.

from boxfork import Sandbox, Snapshot
for snap in Snapshot.list():
print(snap.id, snap.sandbox_id, snap.created_at)
sbx = Sandbox.create(snapshot="snap_p4c6w2yzr7mq3b5d")

A volume is storage that stays when a sandbox goes. Sandboxes that mount the same volume share it.

Field of Volume Type Meaning
name str The name of the volume.
created_at Optional[datetime] The time of creation.
sandboxes Tuple[str, ...] The identifiers of the sandboxes that mount the volume.
default_path str The path at which each new sandbox mounts the volume. "" if the volume is not a default volume of the daemon.
Method Returns Meaning
Volume.create(name, *, url=None, api_key=None) Volume A class method. Create an empty volume.
Volume.list(*, url=None, api_key=None) List[Volume] A class method. List the volumes in the sequence of their names.
at(path, *, read_only=False) Mount This volume at a path, for the volumes parameter of Sandbox.create.
delete() None Delete the volume and all its contents.
  • A name has 1 to 63 characters: lower-case letters, digits, ., _ and -. The first character is a letter or a digit.
  • Volume.create raises APIError with the code already_exists if the name is in use.
  • delete() raises APIError with the code in_use while a sandbox mounts the volume. A suspended sandbox also counts.
Field of Mount Type Default Meaning
name str necessary The name of the volume.
path str necessary The absolute path in the sandbox.
read_only bool False True if the sandbox can read the volume but cannot write to it.

Mount.parse(text) is a class method. It reads a string of the form "name:/path", "name:/path:ro" or "name:/path:rw" and returns a Mount. It raises ValueError for a string of a different form.

from boxfork import Sandbox, Volume
data = Volume.create("data")
with Sandbox.create(volumes=[data.at("/data")]) as sbx:
sbx.run("echo kept > /data/note")
with Sandbox.create(volumes=["data:/data:ro"]) as sbx:
print(sbx.run("cat /data/note").stdout)
data.delete()

A pool keeps sandboxes started for one image or one snapshot. A Sandbox.create call for the same image or snapshot, cpus, memory_mb and network gets a waiting sandbox. A call with gpu, env or volumes does not get a waiting sandbox. The daemon creates that sandbox in the usual way.

Field Type Meaning
id str The identifier of the pool.
image str The image of the sandboxes. "" for a pool of a snapshot.
snapshot str The snapshot of the sandboxes. "" for a pool of an image.
size int The number of sandboxes that the pool keeps.
cpus float The CPU limit of each sandbox.
memory_mb int The memory limit of each sandbox, in MiB.
network bool True if the sandboxes have networking.
created_at Optional[datetime] The time of creation.
ready int The number of waiting sandboxes at the time of the read.
last_error str The reason why the daemon did not start the last sandbox of the pool. "" for none.
Pool.create(image=None, *, size, snapshot=None, cpus=None, memory_mb=None,
network=True, url=None, api_key=None) -> Pool

This class method creates a pool. It returns immediately, and the daemon starts the sandboxes after that. If a pool for the same image or snapshot, cpus, memory_mb and network exists, the call changes its size.

Parameter Type Default Meaning
image Optional[str] The default image of the daemon The image of the sandboxes.
size int necessary The number of sandboxes to keep. The minimum is 1.
snapshot str, Snapshot or None None A snapshot to start from. Do not give image with it.
cpus Optional[float] The default of the daemon CPU cores of each sandbox.
memory_mb Optional[int] The default of the daemon Memory of each sandbox in MiB.
network bool True False gives sandboxes without networking.

The call raises APIError with the code limit_reached if the pools go above the limit of the host.

Method Returns Meaning
Pool.list(*, url=None, api_key=None) List[Pool] A class method. List the pools, the oldest first.
refresh() Pool Return the pool with its current state. Raises NotFound if the pool is gone.
wait(timeout=120.0) Pool Wait until all sandboxes of the pool are ready. Return the pool with its state at that time.
resize(size) Pool Change the number of sandboxes that the pool keeps. Raises NotFound if the pool is gone.
delete() None Delete the pool and its waiting sandboxes. Sandboxes that the daemon handed out stay.

wait asks the daemon again each 0.05 seconds. It raises BoxforkError when the daemon cannot start a sandbox of the pool. The message has the reason. It raises the built-in TimeoutError after timeout seconds.

A Pool object is frozen. refresh, wait and resize return a new object.

from boxfork import Pool, Sandbox
pool = Pool.create("python:3.12", size=8).wait()
print(pool.ready, pool.size)
sbx = Sandbox.create("python:3.12")
sbx.kill()
pool = pool.resize(4)
pool.delete()
boxfork.gpus(*, url=None, api_key=None) -> List[GPU]
boxfork.host_info(*, url=None, api_key=None) -> Dict[str, Any]

gpus() lists the GPUs of the host. On a host without a GPU, the list is empty. host_info() returns the answer of GET /v1/info as a dictionary. http-api.md describes its fields.

Field of GPU Type Meaning
index int The index of the device.
uuid str The identifier that the driver gives the device.
name str The model name.
memory_mb int The memory of the device in MiB.
sandbox_id str The sandbox that holds the device. "" if the device is free.
busy bool True if a program that is not boxfork uses the device.
missing bool True if the driver does not list the device at this time.
suspect bool True if the last sandbox that got the device failed the GPU check.

In SandboxInfo.gpus, only the first five fields have values from the daemon.

import boxfork
info = boxfork.host_info()
print(info["version"], info["isolation"], info["gpus"])
for gpu in boxfork.gpus():
print(gpu.index, gpu.name, gpu.sandbox_id or "free")
BoxforkError
├── DaemonUnreachable
├── APIError
│ ├── NotFound
│ ├── Unauthorized
│ └── GPUUnavailable
└── CommandError
Exception Cause Attributes
BoxforkError The base class of all errors of the SDK. The SDK also raises it directly, for example for a missing API key. none
DaemonUnreachable The daemon gave no answer. The daemon does not run, or the address is wrong. none
APIError The daemon answered with an error. status (int), code (str), message (str)
NotFound The status is 404. A sandbox, a snapshot, a volume, a pool or a file does not exist. The same as APIError.
Unauthorized The status is 401. The API key is missing or wrong. The same as APIError.
GPUUnavailable The code is gpu_unavailable. The same as APIError.
CommandError A command with check=True failed. result (CommandResult)

code is the error code of the HTTP API. http-api.md lists the codes. If an error answer does not have the error format of the API, code is http_error.

The SDK also raises these built-in exceptions:

Exception Raised by
ValueError Mount.parse, and Sandbox.create for a wrong string in volumes.
TypeError Sandbox.create for an item of volumes that is not a Mount or a string.
TimeoutError Pool.wait.
UnicodeDecodeError files.read for a file that is not valid UTF-8.
OSError files.upload and files.download for an error with the local file.
from boxfork import APIError, CommandError, GPUUnavailable, NotFound, Sandbox
try:
sbx = Sandbox.create("python:3.12", gpu=1)
except GPUUnavailable as e:
print("no GPU:", e.message)
except APIError as e:
print(e.status, e.code, e.message)
else:
try:
sbx.run("python3 -c 'raise SystemExit(3)'", check=True)
except CommandError as e:
print(e.result.exit_code)
finally:
sbx.kill()

A Toolkit gives a model the sandbox tools and does the tool calls of the model. The tool kit does not call a model. It works with each model API that accepts tools as JSON Schema.

The daemon has the tool definitions. The tool kit gets them from GET /v1/tools and does each call through POST /v1/tools/{name}. mcp-and-tools.md describes the nine tools, their arguments and their answers.

Toolkit(*, url=None, api_key=None, image=None, gpu=0, idle_timeout=1800,
max_sandboxes=16, keep=False)
Parameter Type Default Meaning
url, api_key Optional[str] See Connection to the daemon The daemon to use.
image Optional[str] The default image of the daemon The image of the sandbox that the tool kit creates for itself.
gpu int 0 The number of GPUs of that sandbox. A negative number is an error.
idle_timeout float 1800 The time in seconds that a sandbox of the tool kit lives without use. The value must be more than zero.
max_sandboxes int 16 The maximum number of sandboxes of the tool kit at one time. 0 means no limit.
keep bool False True does not kill the sandboxes at close().

The parameters image, gpu, idle_timeout, max_sandboxes and keep are also attributes of the object.

A Toolkit is one session. It applies these rules:

  • The first tool call that needs a sandbox and gives no sandbox_id makes the tool kit create a sandbox. The tool kit uses this sandbox for each subsequent call without sandbox_id.
  • This applies to sandbox_exec, sandbox_read_file, sandbox_write_file, sandbox_snapshot and sandbox_fork.
  • If that sandbox is gone, the tool kit creates a new one and does the call again. The text of the result tells the model.
  • When the model creates a sandbox or a fork without timeout_seconds, the tool kit sets the timeout to idle_timeout.
  • After each call in such a sandbox, the tool kit sets its timeout to idle_timeout again.
  • While a sandbox_exec call runs, the tool kit adds the longest time of a call, 1800 seconds, to that timeout.
  • A call that goes above max_sandboxes gets an error result with the code limit_reached.
  • close() kills all sandboxes that the tool kit started, unless keep is True.

You can use one Toolkit from more than one thread. A Toolkit is a context manager: the end of a with block calls close().

kit.tools(format="openai") -> List[Dict[str, Any]]

This method returns the tool definitions in the form that a model API accepts. The first call gets the definitions from the daemon. The tool kit keeps them for the subsequent calls.

format Form of each item
"openai" {"type": "function", "function": {"name", "description", "parameters"}}, for the Chat Completions API and compatible servers.
"openai-responses" {"type": "function", "name", "description", "parameters"}, for the Responses API.
"anthropic" {"name", "description", "input_schema"}, for the Messages API.
"gemini" {"name", "description", "parameters"}, for a function_declarations list. The schema has no additionalProperties key.
"raw" The definition from the daemon: name, title, description, input_schema and the flags.

A different value raises BoxforkError. boxfork.toolkit.FORMATS is the tuple of the five names.

kit.run_tool(name, arguments=None, *, call_id="") -> ToolResult

This method does one tool call.

Parameter Type Default Meaning
name str necessary The name of the tool.
arguments dict, str, bytes or None None The arguments of the call, as a dictionary or as JSON text. None and "" mean no arguments.
call_id str "" The identifier that the model gave the call. The result has the same value.

A call that fails does not raise an exception. The result has is_error set, and text tells the model the reason. This is also true when the daemon refuses the call or does not answer.

code of the result Cause
"" The call was good.
unknown_tool No tool has that name. The tool kit sends nothing to the daemon.
invalid_request The arguments are not a JSON object, or the daemon refused an argument.
limit_reached The call goes above max_sandboxes, or above a limit of the host.
closed The tool kit is closed.
unreachable The daemon does not answer, or the SDK cannot make the request.
timed_out The time limit of sandbox_exec killed the command.
a different code The error code of the daemon, for example sandbox_not_found or gpu_unavailable.
kit.run_tool_call(call) -> ToolResult

This method does a tool call in the form in which a model API returns it. It accepts an object or a dictionary.

API Where the method reads the name Arguments Identifier
Chat Completions call.function.name call.function.arguments call.id
Responses call.name call.arguments call.call_id
Messages call.name call.input call.id
Gemini call.name call.args none

If the call names no tool, the result has the code invalid_request.

Field Type Meaning
text str The result as text for the model. Give this text to the model.
data Any The same result as values for a program. None if the call has none.
is_error bool True if the call did not do the work.
code str The type of the failure. "" if the call was good.
call_id str The identifier that the model gave the call.
Method Returns
as_openai_message() {"role": "tool", "tool_call_id": call_id, "content": text}
as_anthropic_block() {"type": "tool_result", "tool_use_id": call_id, "content": text, "is_error": is_error}
kit.run_code_blocks(text, *, timeout=120, workdir="/tmp") -> Optional[str]

This method is for a model that cannot call tools. It runs the code blocks in a reply of the model.

  1. The method finds each fenced code block in text that has a known language mark.
  2. It writes the block to a file below workdir in the sandbox of the tool kit.
  3. It runs the file with sandbox_exec and the time limit timeout, in seconds.
  4. It returns the outputs of all blocks as one text. Send this text to the model.
Language mark Command
python, py, python3 python3
bash bash
sh, shell sh
javascript, js node

The method ignores a block with a different mark or with no mark. It returns None if text has no block that it can run.

kit.sandboxes is a property. It is the list of the identifiers of the sandboxes that the tool kit started and did not kill.

kit.close() kills these sandboxes, unless keep is True. After close(), each tool call returns an error result with the code closed. If the tool kit cannot kill a sandbox, close() raises BoxforkError with the identifiers. Those sandboxes stay in kit.sandboxes, thus you can call close() again. Their timeout also ends them.

If a call is in progress during close(), the tool kit kills the sandboxes of that call when the call returns.

The loop below uses a client of the Chat Completions API. The names client, model and messages come from your program.

from boxfork import Toolkit
with Toolkit(image="python:3.12") as kit:
reply = client.chat.completions.create(model=model, messages=messages,
tools=kit.tools("openai"))
message = reply.choices[0].message
messages.append(message)
for call in message.tool_calls or []:
result = kit.run_tool_call(call)
messages.append(result.as_openai_message())

A direct call, without a model:

from boxfork import Toolkit
with Toolkit() as kit:
result = kit.run_tool("sandbox_exec", {"command": "python3 --version"})
print(result.text)
print(result.is_error, result.code, kit.sandboxes)
reply_text = "Run this:\n```python\nprint(6 * 7)\n```\n"
print(kit.run_code_blocks(reply_text))
  • The SDK is synchronous. An async interface is not built.
  • The SDK does not give the model and min_memory_mb filters of the gpu field of the HTTP API. gpu is a number.
  • Snapshot has no method to get one snapshot by its identifier. Use Snapshot.list().
  • GPU does not have the memory_used_mb and utilization_pct fields of the HTTP API.
  • A fork and a SandboxInfo are separate from the Sandbox object: the fields of a SandboxInfo do not change after the read.
  • Nobody did a test of the tool kit with a live model. The tests use recorded tool calls.
  • The GPU parameters ran only against stand-ins, not against a real GPU.